@llmnesia/mcp 0.1.0 → 0.1.2

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/dist/cli.js CHANGED
@@ -1,2812 +1,58 @@
1
1
  #!/usr/bin/env node
2
+ import { createRequire as __llmnesiaCreateRequire } from "node:module";
3
+ const require = __llmnesiaCreateRequire(import.meta.url);
2
4
  import {
3
- Corpus,
4
- SearchIndex,
5
- VERSION,
6
- deleteIndexDb,
7
- drainInbox,
8
- ingestFile,
9
- openSearchIndex,
10
- resolveCorpusDir
11
- } from "./chunk-OBJD6H4A.js";
12
-
13
- // src/cli.ts
14
- import { createInterface } from "readline/promises";
15
-
16
- // ../packages/native-host/install.mjs
17
- import { execFile } from "child_process";
18
- import { chmod, mkdir, readFile, rm, stat, writeFile } from "fs/promises";
19
- import { homedir, platform } from "os";
20
- import { dirname, join, resolve } from "path";
21
- import { fileURLToPath } from "url";
22
- import { promisify } from "util";
23
- var execFileAsync = promisify(execFile);
24
- var HOST_NAME = "com.llmnesia.claude_code";
25
- var STORE_EXTENSION_ID = "leekfgbdojiaabifbjbbgiiclannjdkf";
26
- var here = dirname(fileURLToPath(import.meta.url));
27
- var home = homedir();
28
- var osPlatform = process.env.LLMNESIA_FAKE_PLATFORM || platform();
29
- function expandHome(p) {
30
- if (p === "~") {
31
- return home;
32
- }
33
- if (p.startsWith("~/") || p.startsWith("~\\")) {
34
- return resolve(home, p.slice(2));
35
- }
36
- return resolve(p);
37
- }
38
- function resolveCorpusDir2(explicit) {
39
- const raw = explicit ?? process.env.LLMNESIA_CORPUS_DIR ?? "~/.llmnesia/corpus";
40
- return expandHome(raw);
41
- }
42
- async function exists(path) {
43
- try {
44
- await stat(path);
45
- return true;
46
- } catch {
47
- return false;
48
- }
49
- }
50
- function posixBrowsers(homeDir = home, forPlatform = osPlatform) {
51
- if (forPlatform === "darwin") {
52
- const base2 = join(homeDir, "Library", "Application Support");
53
- return [
54
- ["Brave", join(base2, "BraveSoftware", "Brave-Browser")],
55
- ["Chrome", join(base2, "Google", "Chrome")],
56
- ["Edge", join(base2, "Microsoft Edge")],
57
- ["Chromium", join(base2, "Chromium")]
58
- ];
59
- }
60
- const base = join(homeDir, ".config");
61
- return [
62
- ["Brave", join(base, "BraveSoftware", "Brave-Browser")],
63
- ["Chrome", join(base, "google-chrome")],
64
- ["Edge", join(base, "microsoft-edge")],
65
- ["Chromium", join(base, "chromium")]
66
- ];
67
- }
68
- async function installPosix(manifestBase, hostPath) {
69
- const manifest = { ...manifestBase, path: hostPath };
70
- let installed = 0;
71
- for (const [label, browserDir] of posixBrowsers()) {
72
- if (!await exists(browserDir)) {
73
- continue;
74
- }
75
- const dir = join(browserDir, "NativeMessagingHosts");
76
- await mkdir(dir, { recursive: true });
77
- await writeFile(join(dir, `${HOST_NAME}.json`), `${JSON.stringify(manifest, null, 2)}
78
- `, "utf8");
79
- console.log(`Manifest \u2192 ${label}: ${join(dir, `${HOST_NAME}.json`)}`);
80
- installed += 1;
81
- }
82
- return installed;
83
- }
84
- function windowsBrowsers() {
85
- const localAppData = process.env.LOCALAPPDATA || join(home, "AppData", "Local");
86
- return [
87
- ["Brave", join(localAppData, "BraveSoftware", "Brave-Browser", "User Data"), "Software\\BraveSoftware\\Brave-Browser"],
88
- ["Chrome", join(localAppData, "Google", "Chrome", "User Data"), "Software\\Google\\Chrome"],
89
- ["Edge", join(localAppData, "Microsoft", "Edge", "User Data"), "Software\\Microsoft\\Edge"],
90
- ["Chromium", join(localAppData, "Chromium", "User Data"), "Software\\Chromium"]
91
- ];
92
- }
93
- async function installWindows(manifestBase, hostPath, installDir) {
94
- const batPath = join(installDir, "llmnesia-claude-host.bat");
95
- await writeFile(batPath, `@echo off\r
96
- "${process.execPath}" "${hostPath}" %*\r
97
- `, "utf8");
98
- console.log(`Launcher \u2192 ${batPath}`);
99
- const manifest = { ...manifestBase, path: batPath };
100
- const manifestPath = join(installDir, `${HOST_NAME}.json`);
101
- await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}
102
- `, "utf8");
103
- console.log(`Manifest \u2192 ${manifestPath}`);
104
- let installed = 0;
105
- for (const [label, userDataDir, vendorKey] of windowsBrowsers()) {
106
- if (!await exists(userDataDir)) {
107
- continue;
108
- }
109
- const key = `HKCU\\${vendorKey}\\NativeMessagingHosts\\${HOST_NAME}`;
110
- const regExe = join(process.env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
111
- await execFileAsync(regExe, ["add", key, "/ve", "/t", "REG_SZ", "/d", manifestPath, "/f"]);
112
- console.log(`Registry \u2192 ${label}: ${key}`);
113
- installed += 1;
114
- }
115
- return installed;
116
- }
117
- async function installNativeHost({ ids = [], corpus, force = false } = {}) {
118
- const isWindows2 = osPlatform === "win32";
119
- const allIds = [.../* @__PURE__ */ new Set([STORE_EXTENSION_ID, ...ids])];
120
- const allowedOrigins = allIds.map((id) => `chrome-extension://${id}/`);
121
- const installDir = join(home, ".llmnesia");
122
- await mkdir(installDir, { recursive: true });
123
- const hostSource = await readFile(join(here, "llmnesia-claude-host.mjs"), "utf8");
124
- const hosted = isWindows2 ? hostSource : hostSource.replace(/^#![^\n]*\n/, `#!${process.execPath}
125
- `);
126
- const hostPath = join(installDir, "llmnesia-claude-host.mjs");
127
- await writeFile(hostPath, hosted, "utf8");
128
- if (!isWindows2) {
129
- await chmod(hostPath, 493);
130
- }
131
- console.log(`Host script \u2192 ${hostPath}`);
132
- const manifestBase = {
133
- name: HOST_NAME,
134
- description: "LLMnesia \u2014 reads local Claude Code sessions",
135
- type: "stdio",
136
- allowed_origins: allowedOrigins
137
- };
138
- const installedCount = isWindows2 ? await installWindows(manifestBase, hostPath, installDir) : await installPosix(manifestBase, hostPath);
139
- if (installedCount === 0) {
140
- throw new Error("No Chromium-based browsers found \u2014 nothing to install.");
141
- }
142
- const configPath = join(installDir, "config.json");
143
- const corpusRoot = resolveCorpusDir2(corpus);
144
- let existing = null;
145
- try {
146
- existing = JSON.parse(await readFile(configPath, "utf8"));
147
- } catch {
148
- }
149
- const existingRoot = existing && typeof existing.corpusRoot === "string" ? existing.corpusRoot : null;
150
- let corpusRootChanged = true;
151
- if (existingRoot && existingRoot !== corpusRoot && !force) {
152
- corpusRootChanged = false;
153
- console.log(`Corpus config kept \u2192 ${configPath}`);
154
- console.log(` already points at: ${existingRoot}`);
155
- console.log(` to change it: re-run with --corpus <dir> --force`);
156
- } else {
157
- await writeFile(configPath, `${JSON.stringify({ corpusRoot }, null, 2)}
158
- `, { encoding: "utf8", mode: 384 });
159
- await chmod(configPath, 384);
160
- console.log(`Corpus config \u2192 ${configPath}`);
161
- console.log(` corpus root: ${corpusRoot}`);
162
- }
163
- console.log(`
164
- Done. Allowed extension id(s): ${allIds.join(", ")}`);
165
- console.log("Fully quit and reopen the browser, then open LLMnesia Settings.");
166
- return {
167
- installedCount,
168
- allowedIds: allIds,
169
- configPath,
170
- corpusRoot: existingRoot && !corpusRootChanged ? existingRoot : corpusRoot,
171
- corpusRootChanged
172
- };
173
- }
174
- async function uninstallNativeHost() {
175
- const isWindows2 = osPlatform === "win32";
176
- const removed = [];
177
- const installDir = join(home, ".llmnesia");
178
- if (isWindows2) {
179
- const manifestPath = join(installDir, `${HOST_NAME}.json`);
180
- const batPath = join(installDir, "llmnesia-claude-host.bat");
181
- for (const [label, userDataDir, vendorKey] of windowsBrowsers()) {
182
- if (!await exists(userDataDir)) {
183
- continue;
184
- }
185
- const key = `HKCU\\${vendorKey}\\NativeMessagingHosts\\${HOST_NAME}`;
186
- const regExe = join(process.env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
187
- try {
188
- await execFileAsync(regExe, ["delete", key, "/f"]);
189
- removed.push(`registry:${label}`);
190
- } catch {
191
- }
192
- }
193
- await rm(manifestPath, { force: true });
194
- await rm(batPath, { force: true });
195
- removed.push("manifest", "launcher");
196
- } else {
197
- for (const [label, browserDir] of posixBrowsers()) {
198
- if (!await exists(browserDir)) {
199
- continue;
200
- }
201
- const manifestPath = join(browserDir, "NativeMessagingHosts", `${HOST_NAME}.json`);
202
- if (await exists(manifestPath)) {
203
- await rm(manifestPath, { force: true });
204
- removed.push(`manifest:${label}`);
205
- }
206
- }
207
- }
208
- const hostScriptPath = join(installDir, "llmnesia-claude-host.mjs");
209
- if (await exists(hostScriptPath)) {
210
- await rm(hostScriptPath, { force: true });
211
- removed.push("host-script");
212
- }
213
- const corpusRoot = resolveCorpusDir2();
214
- return { removed, corpusRoot };
215
- }
216
-
217
- // src/args.ts
218
- var OPTION_ALIASES = {
219
- c: "corpus",
220
- n: "limit",
221
- v: "version",
222
- h: "help",
223
- y: "yes"
224
- };
225
- var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["force", "yes", "version", "help"]);
226
- function parseArgs(argv) {
227
- const positionals = [];
228
- const options = {};
229
- const flags = /* @__PURE__ */ new Set();
230
- for (let i = 0; i < argv.length; i += 1) {
231
- const arg = argv[i];
232
- if (arg.startsWith("--") && arg.includes("=")) {
233
- const eq = arg.indexOf("=");
234
- options[arg.slice(2, eq)] = arg.slice(eq + 1);
235
- } else if (arg.startsWith("--")) {
236
- const key = arg.slice(2);
237
- if (BOOLEAN_FLAGS.has(key)) {
238
- flags.add(key);
239
- } else {
240
- options[key] = argv[++i] ?? "";
241
- }
242
- } else if (arg.startsWith("-") && arg.length === 2) {
243
- const key = OPTION_ALIASES[arg.slice(1)] ?? arg.slice(1);
244
- if (BOOLEAN_FLAGS.has(key)) {
245
- flags.add(key);
246
- } else {
247
- options[key] = argv[++i] ?? "";
248
- }
249
- } else {
250
- positionals.push(arg);
251
- }
252
- }
253
- return { command: positionals[0], positionals: positionals.slice(1), options, flags };
254
- }
255
-
256
- // ../node_modules/chokidar/esm/index.js
257
- import { stat as statcb } from "fs";
258
- import { stat as stat4, readdir as readdir2 } from "fs/promises";
259
- import { EventEmitter } from "events";
260
- import * as sysPath2 from "path";
261
-
262
- // ../node_modules/readdirp/esm/index.js
263
- import { stat as stat2, lstat, readdir, realpath } from "fs/promises";
264
- import { Readable } from "stream";
265
- import { resolve as presolve, relative as prelative, join as pjoin, sep as psep } from "path";
266
- var EntryTypes = {
267
- FILE_TYPE: "files",
268
- DIR_TYPE: "directories",
269
- FILE_DIR_TYPE: "files_directories",
270
- EVERYTHING_TYPE: "all"
271
- };
272
- var defaultOptions = {
273
- root: ".",
274
- fileFilter: (_entryInfo) => true,
275
- directoryFilter: (_entryInfo) => true,
276
- type: EntryTypes.FILE_TYPE,
277
- lstat: false,
278
- depth: 2147483648,
279
- alwaysStat: false,
280
- highWaterMark: 4096
281
- };
282
- Object.freeze(defaultOptions);
283
- var RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
284
- var NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
285
- var ALL_TYPES = [
286
- EntryTypes.DIR_TYPE,
287
- EntryTypes.EVERYTHING_TYPE,
288
- EntryTypes.FILE_DIR_TYPE,
289
- EntryTypes.FILE_TYPE
290
- ];
291
- var DIR_TYPES = /* @__PURE__ */ new Set([
292
- EntryTypes.DIR_TYPE,
293
- EntryTypes.EVERYTHING_TYPE,
294
- EntryTypes.FILE_DIR_TYPE
295
- ]);
296
- var FILE_TYPES = /* @__PURE__ */ new Set([
297
- EntryTypes.EVERYTHING_TYPE,
298
- EntryTypes.FILE_DIR_TYPE,
299
- EntryTypes.FILE_TYPE
300
- ]);
301
- var isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
302
- var wantBigintFsStats = process.platform === "win32";
303
- var emptyFn = (_entryInfo) => true;
304
- var normalizeFilter = (filter) => {
305
- if (filter === void 0)
306
- return emptyFn;
307
- if (typeof filter === "function")
308
- return filter;
309
- if (typeof filter === "string") {
310
- const fl = filter.trim();
311
- return (entry) => entry.basename === fl;
312
- }
313
- if (Array.isArray(filter)) {
314
- const trItems = filter.map((item) => item.trim());
315
- return (entry) => trItems.some((f) => entry.basename === f);
316
- }
317
- return emptyFn;
318
- };
319
- var ReaddirpStream = class extends Readable {
320
- constructor(options = {}) {
321
- super({
322
- objectMode: true,
323
- autoDestroy: true,
324
- highWaterMark: options.highWaterMark
325
- });
326
- const opts = { ...defaultOptions, ...options };
327
- const { root, type } = opts;
328
- this._fileFilter = normalizeFilter(opts.fileFilter);
329
- this._directoryFilter = normalizeFilter(opts.directoryFilter);
330
- const statMethod = opts.lstat ? lstat : stat2;
331
- if (wantBigintFsStats) {
332
- this._stat = (path) => statMethod(path, { bigint: true });
333
- } else {
334
- this._stat = statMethod;
335
- }
336
- this._maxDepth = opts.depth ?? defaultOptions.depth;
337
- this._wantsDir = type ? DIR_TYPES.has(type) : false;
338
- this._wantsFile = type ? FILE_TYPES.has(type) : false;
339
- this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
340
- this._root = presolve(root);
341
- this._isDirent = !opts.alwaysStat;
342
- this._statsProp = this._isDirent ? "dirent" : "stats";
343
- this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
344
- this.parents = [this._exploreDir(root, 1)];
345
- this.reading = false;
346
- this.parent = void 0;
347
- }
348
- async _read(batch) {
349
- if (this.reading)
350
- return;
351
- this.reading = true;
352
- try {
353
- while (!this.destroyed && batch > 0) {
354
- const par = this.parent;
355
- const fil = par && par.files;
356
- if (fil && fil.length > 0) {
357
- const { path, depth } = par;
358
- const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));
359
- const awaited = await Promise.all(slice);
360
- for (const entry of awaited) {
361
- if (!entry)
362
- continue;
363
- if (this.destroyed)
364
- return;
365
- const entryType = await this._getEntryType(entry);
366
- if (entryType === "directory" && this._directoryFilter(entry)) {
367
- if (depth <= this._maxDepth) {
368
- this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
369
- }
370
- if (this._wantsDir) {
371
- this.push(entry);
372
- batch--;
373
- }
374
- } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
375
- if (this._wantsFile) {
376
- this.push(entry);
377
- batch--;
378
- }
379
- }
380
- }
381
- } else {
382
- const parent = this.parents.pop();
383
- if (!parent) {
384
- this.push(null);
385
- break;
386
- }
387
- this.parent = await parent;
388
- if (this.destroyed)
389
- return;
390
- }
391
- }
392
- } catch (error) {
393
- this.destroy(error);
394
- } finally {
395
- this.reading = false;
396
- }
397
- }
398
- async _exploreDir(path, depth) {
399
- let files;
400
- try {
401
- files = await readdir(path, this._rdOptions);
402
- } catch (error) {
403
- this._onError(error);
404
- }
405
- return { files, depth, path };
406
- }
407
- async _formatEntry(dirent, path) {
408
- let entry;
409
- const basename3 = this._isDirent ? dirent.name : dirent;
410
- try {
411
- const fullPath = presolve(pjoin(path, basename3));
412
- entry = { path: prelative(this._root, fullPath), fullPath, basename: basename3 };
413
- entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
414
- } catch (err) {
415
- this._onError(err);
416
- return;
417
- }
418
- return entry;
419
- }
420
- _onError(err) {
421
- if (isNormalFlowError(err) && !this.destroyed) {
422
- this.emit("warn", err);
423
- } else {
424
- this.destroy(err);
425
- }
426
- }
427
- async _getEntryType(entry) {
428
- if (!entry && this._statsProp in entry) {
429
- return "";
430
- }
431
- const stats = entry[this._statsProp];
432
- if (stats.isFile())
433
- return "file";
434
- if (stats.isDirectory())
435
- return "directory";
436
- if (stats && stats.isSymbolicLink()) {
437
- const full = entry.fullPath;
438
- try {
439
- const entryRealPath = await realpath(full);
440
- const entryRealPathStats = await lstat(entryRealPath);
441
- if (entryRealPathStats.isFile()) {
442
- return "file";
443
- }
444
- if (entryRealPathStats.isDirectory()) {
445
- const len = entryRealPath.length;
446
- if (full.startsWith(entryRealPath) && full.substr(len, 1) === psep) {
447
- const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
448
- recursiveError.code = RECURSIVE_ERROR_CODE;
449
- return this._onError(recursiveError);
450
- }
451
- return "directory";
452
- }
453
- } catch (error) {
454
- this._onError(error);
455
- return "";
456
- }
457
- }
458
- }
459
- _includeAsFile(entry) {
460
- const stats = entry && entry[this._statsProp];
461
- return stats && this._wantsEverything && !stats.isDirectory();
462
- }
463
- };
464
- function readdirp(root, options = {}) {
465
- let type = options.entryType || options.type;
466
- if (type === "both")
467
- type = EntryTypes.FILE_DIR_TYPE;
468
- if (type)
469
- options.type = type;
470
- if (!root) {
471
- throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
472
- } else if (typeof root !== "string") {
473
- throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
474
- } else if (type && !ALL_TYPES.includes(type)) {
475
- throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
476
- }
477
- options.root = root;
478
- return new ReaddirpStream(options);
479
- }
480
-
481
- // ../node_modules/chokidar/esm/handler.js
482
- import { watchFile, unwatchFile, watch as fs_watch } from "fs";
483
- import { open, stat as stat3, lstat as lstat2, realpath as fsrealpath } from "fs/promises";
484
- import * as sysPath from "path";
485
- import { type as osType } from "os";
486
- var STR_DATA = "data";
487
- var STR_END = "end";
488
- var STR_CLOSE = "close";
489
- var EMPTY_FN = () => {
490
- };
491
- var pl = process.platform;
492
- var isWindows = pl === "win32";
493
- var isMacos = pl === "darwin";
494
- var isLinux = pl === "linux";
495
- var isFreeBSD = pl === "freebsd";
496
- var isIBMi = osType() === "OS400";
497
- var EVENTS = {
498
- ALL: "all",
499
- READY: "ready",
500
- ADD: "add",
501
- CHANGE: "change",
502
- ADD_DIR: "addDir",
503
- UNLINK: "unlink",
504
- UNLINK_DIR: "unlinkDir",
505
- RAW: "raw",
506
- ERROR: "error"
507
- };
508
- var EV = EVENTS;
509
- var THROTTLE_MODE_WATCH = "watch";
510
- var statMethods = { lstat: lstat2, stat: stat3 };
511
- var KEY_LISTENERS = "listeners";
512
- var KEY_ERR = "errHandlers";
513
- var KEY_RAW = "rawEmitters";
514
- var HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
515
- var binaryExtensions = /* @__PURE__ */ new Set([
516
- "3dm",
517
- "3ds",
518
- "3g2",
519
- "3gp",
520
- "7z",
521
- "a",
522
- "aac",
523
- "adp",
524
- "afdesign",
525
- "afphoto",
526
- "afpub",
527
- "ai",
528
- "aif",
529
- "aiff",
530
- "alz",
531
- "ape",
532
- "apk",
533
- "appimage",
534
- "ar",
535
- "arj",
536
- "asf",
537
- "au",
538
- "avi",
539
- "bak",
540
- "baml",
541
- "bh",
542
- "bin",
543
- "bk",
544
- "bmp",
545
- "btif",
546
- "bz2",
547
- "bzip2",
548
- "cab",
549
- "caf",
550
- "cgm",
551
- "class",
552
- "cmx",
553
- "cpio",
554
- "cr2",
555
- "cur",
556
- "dat",
557
- "dcm",
558
- "deb",
559
- "dex",
560
- "djvu",
561
- "dll",
562
- "dmg",
563
- "dng",
564
- "doc",
565
- "docm",
566
- "docx",
567
- "dot",
568
- "dotm",
569
- "dra",
570
- "DS_Store",
571
- "dsk",
572
- "dts",
573
- "dtshd",
574
- "dvb",
575
- "dwg",
576
- "dxf",
577
- "ecelp4800",
578
- "ecelp7470",
579
- "ecelp9600",
580
- "egg",
581
- "eol",
582
- "eot",
583
- "epub",
584
- "exe",
585
- "f4v",
586
- "fbs",
587
- "fh",
588
- "fla",
589
- "flac",
590
- "flatpak",
591
- "fli",
592
- "flv",
593
- "fpx",
594
- "fst",
595
- "fvt",
596
- "g3",
597
- "gh",
598
- "gif",
599
- "graffle",
600
- "gz",
601
- "gzip",
602
- "h261",
603
- "h263",
604
- "h264",
605
- "icns",
606
- "ico",
607
- "ief",
608
- "img",
609
- "ipa",
610
- "iso",
611
- "jar",
612
- "jpeg",
613
- "jpg",
614
- "jpgv",
615
- "jpm",
616
- "jxr",
617
- "key",
618
- "ktx",
619
- "lha",
620
- "lib",
621
- "lvp",
622
- "lz",
623
- "lzh",
624
- "lzma",
625
- "lzo",
626
- "m3u",
627
- "m4a",
628
- "m4v",
629
- "mar",
630
- "mdi",
631
- "mht",
632
- "mid",
633
- "midi",
634
- "mj2",
635
- "mka",
636
- "mkv",
637
- "mmr",
638
- "mng",
639
- "mobi",
640
- "mov",
641
- "movie",
642
- "mp3",
643
- "mp4",
644
- "mp4a",
645
- "mpeg",
646
- "mpg",
647
- "mpga",
648
- "mxu",
649
- "nef",
650
- "npx",
651
- "numbers",
652
- "nupkg",
653
- "o",
654
- "odp",
655
- "ods",
656
- "odt",
657
- "oga",
658
- "ogg",
659
- "ogv",
660
- "otf",
661
- "ott",
662
- "pages",
663
- "pbm",
664
- "pcx",
665
- "pdb",
666
- "pdf",
667
- "pea",
668
- "pgm",
669
- "pic",
670
- "png",
671
- "pnm",
672
- "pot",
673
- "potm",
674
- "potx",
675
- "ppa",
676
- "ppam",
677
- "ppm",
678
- "pps",
679
- "ppsm",
680
- "ppsx",
681
- "ppt",
682
- "pptm",
683
- "pptx",
684
- "psd",
685
- "pya",
686
- "pyc",
687
- "pyo",
688
- "pyv",
689
- "qt",
690
- "rar",
691
- "ras",
692
- "raw",
693
- "resources",
694
- "rgb",
695
- "rip",
696
- "rlc",
697
- "rmf",
698
- "rmvb",
699
- "rpm",
700
- "rtf",
701
- "rz",
702
- "s3m",
703
- "s7z",
704
- "scpt",
705
- "sgi",
706
- "shar",
707
- "snap",
708
- "sil",
709
- "sketch",
710
- "slk",
711
- "smv",
712
- "snk",
713
- "so",
714
- "stl",
715
- "suo",
716
- "sub",
717
- "swf",
718
- "tar",
719
- "tbz",
720
- "tbz2",
721
- "tga",
722
- "tgz",
723
- "thmx",
724
- "tif",
725
- "tiff",
726
- "tlz",
727
- "ttc",
728
- "ttf",
729
- "txz",
730
- "udf",
731
- "uvh",
732
- "uvi",
733
- "uvm",
734
- "uvp",
735
- "uvs",
736
- "uvu",
737
- "viv",
738
- "vob",
739
- "war",
740
- "wav",
741
- "wax",
742
- "wbmp",
743
- "wdp",
744
- "weba",
745
- "webm",
746
- "webp",
747
- "whl",
748
- "wim",
749
- "wm",
750
- "wma",
751
- "wmv",
752
- "wmx",
753
- "woff",
754
- "woff2",
755
- "wrm",
756
- "wvx",
757
- "xbm",
758
- "xif",
759
- "xla",
760
- "xlam",
761
- "xls",
762
- "xlsb",
763
- "xlsm",
764
- "xlsx",
765
- "xlt",
766
- "xltm",
767
- "xltx",
768
- "xm",
769
- "xmind",
770
- "xpi",
771
- "xpm",
772
- "xwd",
773
- "xz",
774
- "z",
775
- "zip",
776
- "zipx"
777
- ]);
778
- var isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase());
779
- var foreach = (val, fn) => {
780
- if (val instanceof Set) {
781
- val.forEach(fn);
782
- } else {
783
- fn(val);
784
- }
785
- };
786
- var addAndConvert = (main2, prop, item) => {
787
- let container = main2[prop];
788
- if (!(container instanceof Set)) {
789
- main2[prop] = container = /* @__PURE__ */ new Set([container]);
790
- }
791
- container.add(item);
792
- };
793
- var clearItem = (cont) => (key) => {
794
- const set = cont[key];
795
- if (set instanceof Set) {
796
- set.clear();
797
- } else {
798
- delete cont[key];
799
- }
800
- };
801
- var delFromSet = (main2, prop, item) => {
802
- const container = main2[prop];
803
- if (container instanceof Set) {
804
- container.delete(item);
805
- } else if (container === item) {
806
- delete main2[prop];
807
- }
808
- };
809
- var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
810
- var FsWatchInstances = /* @__PURE__ */ new Map();
811
- function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
812
- const handleEvent = (rawEvent, evPath) => {
813
- listener(path);
814
- emitRaw(rawEvent, evPath, { watchedPath: path });
815
- if (evPath && path !== evPath) {
816
- fsWatchBroadcast(sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath));
817
- }
818
- };
819
- try {
820
- return fs_watch(path, {
821
- persistent: options.persistent
822
- }, handleEvent);
823
- } catch (error) {
824
- errHandler(error);
825
- return void 0;
826
- }
827
- }
828
- var fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
829
- const cont = FsWatchInstances.get(fullPath);
830
- if (!cont)
831
- return;
832
- foreach(cont[listenerType], (listener) => {
833
- listener(val1, val2, val3);
834
- });
835
- };
836
- var setFsWatchListener = (path, fullPath, options, handlers) => {
837
- const { listener, errHandler, rawEmitter } = handlers;
838
- let cont = FsWatchInstances.get(fullPath);
839
- let watcher;
840
- if (!options.persistent) {
841
- watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
842
- if (!watcher)
843
- return;
844
- return watcher.close.bind(watcher);
845
- }
846
- if (cont) {
847
- addAndConvert(cont, KEY_LISTENERS, listener);
848
- addAndConvert(cont, KEY_ERR, errHandler);
849
- addAndConvert(cont, KEY_RAW, rawEmitter);
850
- } else {
851
- watcher = createFsWatchInstance(
852
- path,
853
- options,
854
- fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
855
- errHandler,
856
- // no need to use broadcast here
857
- fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
858
- );
859
- if (!watcher)
860
- return;
861
- watcher.on(EV.ERROR, async (error) => {
862
- const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
863
- if (cont)
864
- cont.watcherUnusable = true;
865
- if (isWindows && error.code === "EPERM") {
866
- try {
867
- const fd = await open(path, "r");
868
- await fd.close();
869
- broadcastErr(error);
870
- } catch (err) {
871
- }
872
- } else {
873
- broadcastErr(error);
874
- }
875
- });
876
- cont = {
877
- listeners: listener,
878
- errHandlers: errHandler,
879
- rawEmitters: rawEmitter,
880
- watcher
881
- };
882
- FsWatchInstances.set(fullPath, cont);
883
- }
884
- return () => {
885
- delFromSet(cont, KEY_LISTENERS, listener);
886
- delFromSet(cont, KEY_ERR, errHandler);
887
- delFromSet(cont, KEY_RAW, rawEmitter);
888
- if (isEmptySet(cont.listeners)) {
889
- cont.watcher.close();
890
- FsWatchInstances.delete(fullPath);
891
- HANDLER_KEYS.forEach(clearItem(cont));
892
- cont.watcher = void 0;
893
- Object.freeze(cont);
894
- }
895
- };
896
- };
897
- var FsWatchFileInstances = /* @__PURE__ */ new Map();
898
- var setFsWatchFileListener = (path, fullPath, options, handlers) => {
899
- const { listener, rawEmitter } = handlers;
900
- let cont = FsWatchFileInstances.get(fullPath);
901
- const copts = cont && cont.options;
902
- if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
903
- unwatchFile(fullPath);
904
- cont = void 0;
905
- }
906
- if (cont) {
907
- addAndConvert(cont, KEY_LISTENERS, listener);
908
- addAndConvert(cont, KEY_RAW, rawEmitter);
909
- } else {
910
- cont = {
911
- listeners: listener,
912
- rawEmitters: rawEmitter,
913
- options,
914
- watcher: watchFile(fullPath, options, (curr, prev) => {
915
- foreach(cont.rawEmitters, (rawEmitter2) => {
916
- rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
917
- });
918
- const currmtime = curr.mtimeMs;
919
- if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
920
- foreach(cont.listeners, (listener2) => listener2(path, curr));
921
- }
922
- })
923
- };
924
- FsWatchFileInstances.set(fullPath, cont);
925
- }
926
- return () => {
927
- delFromSet(cont, KEY_LISTENERS, listener);
928
- delFromSet(cont, KEY_RAW, rawEmitter);
929
- if (isEmptySet(cont.listeners)) {
930
- FsWatchFileInstances.delete(fullPath);
931
- unwatchFile(fullPath);
932
- cont.options = cont.watcher = void 0;
933
- Object.freeze(cont);
934
- }
935
- };
936
- };
937
- var NodeFsHandler = class {
938
- constructor(fsW) {
939
- this.fsw = fsW;
940
- this._boundHandleError = (error) => fsW._handleError(error);
941
- }
942
- /**
943
- * Watch file for changes with fs_watchFile or fs_watch.
944
- * @param path to file or dir
945
- * @param listener on fs change
946
- * @returns closer for the watcher instance
947
- */
948
- _watchWithNodeFs(path, listener) {
949
- const opts = this.fsw.options;
950
- const directory = sysPath.dirname(path);
951
- const basename3 = sysPath.basename(path);
952
- const parent = this.fsw._getWatchedDir(directory);
953
- parent.add(basename3);
954
- const absolutePath = sysPath.resolve(path);
955
- const options = {
956
- persistent: opts.persistent
957
- };
958
- if (!listener)
959
- listener = EMPTY_FN;
960
- let closer;
961
- if (opts.usePolling) {
962
- const enableBin = opts.interval !== opts.binaryInterval;
963
- options.interval = enableBin && isBinaryPath(basename3) ? opts.binaryInterval : opts.interval;
964
- closer = setFsWatchFileListener(path, absolutePath, options, {
965
- listener,
966
- rawEmitter: this.fsw._emitRaw
967
- });
968
- } else {
969
- closer = setFsWatchListener(path, absolutePath, options, {
970
- listener,
971
- errHandler: this._boundHandleError,
972
- rawEmitter: this.fsw._emitRaw
973
- });
974
- }
975
- return closer;
976
- }
977
- /**
978
- * Watch a file and emit add event if warranted.
979
- * @returns closer for the watcher instance
980
- */
981
- _handleFile(file, stats, initialAdd) {
982
- if (this.fsw.closed) {
983
- return;
984
- }
985
- const dirname7 = sysPath.dirname(file);
986
- const basename3 = sysPath.basename(file);
987
- const parent = this.fsw._getWatchedDir(dirname7);
988
- let prevStats = stats;
989
- if (parent.has(basename3))
990
- return;
991
- const listener = async (path, newStats) => {
992
- if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))
993
- return;
994
- if (!newStats || newStats.mtimeMs === 0) {
995
- try {
996
- const newStats2 = await stat3(file);
997
- if (this.fsw.closed)
998
- return;
999
- const at = newStats2.atimeMs;
1000
- const mt = newStats2.mtimeMs;
1001
- if (!at || at <= mt || mt !== prevStats.mtimeMs) {
1002
- this.fsw._emit(EV.CHANGE, file, newStats2);
1003
- }
1004
- if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
1005
- this.fsw._closeFile(path);
1006
- prevStats = newStats2;
1007
- const closer2 = this._watchWithNodeFs(file, listener);
1008
- if (closer2)
1009
- this.fsw._addPathCloser(path, closer2);
1010
- } else {
1011
- prevStats = newStats2;
1012
- }
1013
- } catch (error) {
1014
- this.fsw._remove(dirname7, basename3);
1015
- }
1016
- } else if (parent.has(basename3)) {
1017
- const at = newStats.atimeMs;
1018
- const mt = newStats.mtimeMs;
1019
- if (!at || at <= mt || mt !== prevStats.mtimeMs) {
1020
- this.fsw._emit(EV.CHANGE, file, newStats);
1021
- }
1022
- prevStats = newStats;
1023
- }
1024
- };
1025
- const closer = this._watchWithNodeFs(file, listener);
1026
- if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
1027
- if (!this.fsw._throttle(EV.ADD, file, 0))
1028
- return;
1029
- this.fsw._emit(EV.ADD, file, stats);
1030
- }
1031
- return closer;
1032
- }
1033
- /**
1034
- * Handle symlinks encountered while reading a dir.
1035
- * @param entry returned by readdirp
1036
- * @param directory path of dir being read
1037
- * @param path of this item
1038
- * @param item basename of this item
1039
- * @returns true if no more processing is needed for this entry.
1040
- */
1041
- async _handleSymlink(entry, directory, path, item) {
1042
- if (this.fsw.closed) {
1043
- return;
1044
- }
1045
- const full = entry.fullPath;
1046
- const dir = this.fsw._getWatchedDir(directory);
1047
- if (!this.fsw.options.followSymlinks) {
1048
- this.fsw._incrReadyCount();
1049
- let linkPath;
1050
- try {
1051
- linkPath = await fsrealpath(path);
1052
- } catch (e) {
1053
- this.fsw._emitReady();
1054
- return true;
1055
- }
1056
- if (this.fsw.closed)
1057
- return;
1058
- if (dir.has(item)) {
1059
- if (this.fsw._symlinkPaths.get(full) !== linkPath) {
1060
- this.fsw._symlinkPaths.set(full, linkPath);
1061
- this.fsw._emit(EV.CHANGE, path, entry.stats);
1062
- }
1063
- } else {
1064
- dir.add(item);
1065
- this.fsw._symlinkPaths.set(full, linkPath);
1066
- this.fsw._emit(EV.ADD, path, entry.stats);
1067
- }
1068
- this.fsw._emitReady();
1069
- return true;
1070
- }
1071
- if (this.fsw._symlinkPaths.has(full)) {
1072
- return true;
1073
- }
1074
- this.fsw._symlinkPaths.set(full, true);
1075
- }
1076
- _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
1077
- directory = sysPath.join(directory, "");
1078
- throttler = this.fsw._throttle("readdir", directory, 1e3);
1079
- if (!throttler)
1080
- return;
1081
- const previous = this.fsw._getWatchedDir(wh.path);
1082
- const current = /* @__PURE__ */ new Set();
1083
- let stream = this.fsw._readdirp(directory, {
1084
- fileFilter: (entry) => wh.filterPath(entry),
1085
- directoryFilter: (entry) => wh.filterDir(entry)
1086
- });
1087
- if (!stream)
1088
- return;
1089
- stream.on(STR_DATA, async (entry) => {
1090
- if (this.fsw.closed) {
1091
- stream = void 0;
1092
- return;
1093
- }
1094
- const item = entry.path;
1095
- let path = sysPath.join(directory, item);
1096
- current.add(item);
1097
- if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
1098
- return;
1099
- }
1100
- if (this.fsw.closed) {
1101
- stream = void 0;
1102
- return;
1103
- }
1104
- if (item === target || !target && !previous.has(item)) {
1105
- this.fsw._incrReadyCount();
1106
- path = sysPath.join(dir, sysPath.relative(dir, path));
1107
- this._addToNodeFs(path, initialAdd, wh, depth + 1);
1108
- }
1109
- }).on(EV.ERROR, this._boundHandleError);
1110
- return new Promise((resolve4, reject) => {
1111
- if (!stream)
1112
- return reject();
1113
- stream.once(STR_END, () => {
1114
- if (this.fsw.closed) {
1115
- stream = void 0;
1116
- return;
1117
- }
1118
- const wasThrottled = throttler ? throttler.clear() : false;
1119
- resolve4(void 0);
1120
- previous.getChildren().filter((item) => {
1121
- return item !== directory && !current.has(item);
1122
- }).forEach((item) => {
1123
- this.fsw._remove(directory, item);
1124
- });
1125
- stream = void 0;
1126
- if (wasThrottled)
1127
- this._handleRead(directory, false, wh, target, dir, depth, throttler);
1128
- });
1129
- });
1130
- }
1131
- /**
1132
- * Read directory to add / remove files from `@watched` list and re-read it on change.
1133
- * @param dir fs path
1134
- * @param stats
1135
- * @param initialAdd
1136
- * @param depth relative to user-supplied path
1137
- * @param target child path targeted for watch
1138
- * @param wh Common watch helpers for this path
1139
- * @param realpath
1140
- * @returns closer for the watcher instance.
1141
- */
1142
- async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath2) {
1143
- const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
1144
- const tracked = parentDir.has(sysPath.basename(dir));
1145
- if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
1146
- this.fsw._emit(EV.ADD_DIR, dir, stats);
1147
- }
1148
- parentDir.add(sysPath.basename(dir));
1149
- this.fsw._getWatchedDir(dir);
1150
- let throttler;
1151
- let closer;
1152
- const oDepth = this.fsw.options.depth;
1153
- if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath2)) {
1154
- if (!target) {
1155
- await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
1156
- if (this.fsw.closed)
1157
- return;
1158
- }
1159
- closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
1160
- if (stats2 && stats2.mtimeMs === 0)
1161
- return;
1162
- this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
1163
- });
1164
- }
1165
- return closer;
1166
- }
1167
- /**
1168
- * Handle added file, directory, or glob pattern.
1169
- * Delegates call to _handleFile / _handleDir after checks.
1170
- * @param path to file or ir
1171
- * @param initialAdd was the file added at watch instantiation?
1172
- * @param priorWh depth relative to user-supplied path
1173
- * @param depth Child path actually targeted for watch
1174
- * @param target Child path actually targeted for watch
1175
- */
1176
- async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
1177
- const ready = this.fsw._emitReady;
1178
- if (this.fsw._isIgnored(path) || this.fsw.closed) {
1179
- ready();
1180
- return false;
1181
- }
1182
- const wh = this.fsw._getWatchHelpers(path);
1183
- if (priorWh) {
1184
- wh.filterPath = (entry) => priorWh.filterPath(entry);
1185
- wh.filterDir = (entry) => priorWh.filterDir(entry);
1186
- }
1187
- try {
1188
- const stats = await statMethods[wh.statMethod](wh.watchPath);
1189
- if (this.fsw.closed)
1190
- return;
1191
- if (this.fsw._isIgnored(wh.watchPath, stats)) {
1192
- ready();
1193
- return false;
1194
- }
1195
- const follow = this.fsw.options.followSymlinks;
1196
- let closer;
1197
- if (stats.isDirectory()) {
1198
- const absPath = sysPath.resolve(path);
1199
- const targetPath = follow ? await fsrealpath(path) : path;
1200
- if (this.fsw.closed)
1201
- return;
1202
- closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
1203
- if (this.fsw.closed)
1204
- return;
1205
- if (absPath !== targetPath && targetPath !== void 0) {
1206
- this.fsw._symlinkPaths.set(absPath, targetPath);
1207
- }
1208
- } else if (stats.isSymbolicLink()) {
1209
- const targetPath = follow ? await fsrealpath(path) : path;
1210
- if (this.fsw.closed)
1211
- return;
1212
- const parent = sysPath.dirname(wh.watchPath);
1213
- this.fsw._getWatchedDir(parent).add(wh.watchPath);
1214
- this.fsw._emit(EV.ADD, wh.watchPath, stats);
1215
- closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
1216
- if (this.fsw.closed)
1217
- return;
1218
- if (targetPath !== void 0) {
1219
- this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
1220
- }
1221
- } else {
1222
- closer = this._handleFile(wh.watchPath, stats, initialAdd);
1223
- }
1224
- ready();
1225
- if (closer)
1226
- this.fsw._addPathCloser(path, closer);
1227
- return false;
1228
- } catch (error) {
1229
- if (this.fsw._handleError(error)) {
1230
- ready();
1231
- return path;
1232
- }
1233
- }
1234
- }
1235
- };
1236
-
1237
- // ../node_modules/chokidar/esm/index.js
1238
- var SLASH = "/";
1239
- var SLASH_SLASH = "//";
1240
- var ONE_DOT = ".";
1241
- var TWO_DOTS = "..";
1242
- var STRING_TYPE = "string";
1243
- var BACK_SLASH_RE = /\\/g;
1244
- var DOUBLE_SLASH_RE = /\/\//;
1245
- var DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
1246
- var REPLACER_RE = /^\.[/\\]/;
1247
- function arrify(item) {
1248
- return Array.isArray(item) ? item : [item];
1249
- }
1250
- var isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
1251
- function createPattern(matcher) {
1252
- if (typeof matcher === "function")
1253
- return matcher;
1254
- if (typeof matcher === "string")
1255
- return (string) => matcher === string;
1256
- if (matcher instanceof RegExp)
1257
- return (string) => matcher.test(string);
1258
- if (typeof matcher === "object" && matcher !== null) {
1259
- return (string) => {
1260
- if (matcher.path === string)
1261
- return true;
1262
- if (matcher.recursive) {
1263
- const relative3 = sysPath2.relative(matcher.path, string);
1264
- if (!relative3) {
1265
- return false;
1266
- }
1267
- return !relative3.startsWith("..") && !sysPath2.isAbsolute(relative3);
1268
- }
1269
- return false;
1270
- };
1271
- }
1272
- return () => false;
1273
- }
1274
- function normalizePath(path) {
1275
- if (typeof path !== "string")
1276
- throw new Error("string expected");
1277
- path = sysPath2.normalize(path);
1278
- path = path.replace(/\\/g, "/");
1279
- let prepend = false;
1280
- if (path.startsWith("//"))
1281
- prepend = true;
1282
- const DOUBLE_SLASH_RE2 = /\/\//;
1283
- while (path.match(DOUBLE_SLASH_RE2))
1284
- path = path.replace(DOUBLE_SLASH_RE2, "/");
1285
- if (prepend)
1286
- path = "/" + path;
1287
- return path;
1288
- }
1289
- function matchPatterns(patterns, testString, stats) {
1290
- const path = normalizePath(testString);
1291
- for (let index = 0; index < patterns.length; index++) {
1292
- const pattern = patterns[index];
1293
- if (pattern(path, stats)) {
1294
- return true;
1295
- }
1296
- }
1297
- return false;
1298
- }
1299
- function anymatch(matchers, testString) {
1300
- if (matchers == null) {
1301
- throw new TypeError("anymatch: specify first argument");
1302
- }
1303
- const matchersArray = arrify(matchers);
1304
- const patterns = matchersArray.map((matcher) => createPattern(matcher));
1305
- if (testString == null) {
1306
- return (testString2, stats) => {
1307
- return matchPatterns(patterns, testString2, stats);
1308
- };
1309
- }
1310
- return matchPatterns(patterns, testString);
1311
- }
1312
- var unifyPaths = (paths_) => {
1313
- const paths2 = arrify(paths_).flat();
1314
- if (!paths2.every((p) => typeof p === STRING_TYPE)) {
1315
- throw new TypeError(`Non-string provided as watch path: ${paths2}`);
1316
- }
1317
- return paths2.map(normalizePathToUnix);
1318
- };
1319
- var toUnix = (string) => {
1320
- let str = string.replace(BACK_SLASH_RE, SLASH);
1321
- let prepend = false;
1322
- if (str.startsWith(SLASH_SLASH)) {
1323
- prepend = true;
1324
- }
1325
- while (str.match(DOUBLE_SLASH_RE)) {
1326
- str = str.replace(DOUBLE_SLASH_RE, SLASH);
1327
- }
1328
- if (prepend) {
1329
- str = SLASH + str;
1330
- }
1331
- return str;
1332
- };
1333
- var normalizePathToUnix = (path) => toUnix(sysPath2.normalize(toUnix(path)));
1334
- var normalizeIgnored = (cwd = "") => (path) => {
1335
- if (typeof path === "string") {
1336
- return normalizePathToUnix(sysPath2.isAbsolute(path) ? path : sysPath2.join(cwd, path));
1337
- } else {
1338
- return path;
1339
- }
1340
- };
1341
- var getAbsolutePath = (path, cwd) => {
1342
- if (sysPath2.isAbsolute(path)) {
1343
- return path;
1344
- }
1345
- return sysPath2.join(cwd, path);
1346
- };
1347
- var EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
1348
- var DirEntry = class {
1349
- constructor(dir, removeWatcher) {
1350
- this.path = dir;
1351
- this._removeWatcher = removeWatcher;
1352
- this.items = /* @__PURE__ */ new Set();
1353
- }
1354
- add(item) {
1355
- const { items } = this;
1356
- if (!items)
1357
- return;
1358
- if (item !== ONE_DOT && item !== TWO_DOTS)
1359
- items.add(item);
1360
- }
1361
- async remove(item) {
1362
- const { items } = this;
1363
- if (!items)
1364
- return;
1365
- items.delete(item);
1366
- if (items.size > 0)
1367
- return;
1368
- const dir = this.path;
1369
- try {
1370
- await readdir2(dir);
1371
- } catch (err) {
1372
- if (this._removeWatcher) {
1373
- this._removeWatcher(sysPath2.dirname(dir), sysPath2.basename(dir));
1374
- }
1375
- }
1376
- }
1377
- has(item) {
1378
- const { items } = this;
1379
- if (!items)
1380
- return;
1381
- return items.has(item);
1382
- }
1383
- getChildren() {
1384
- const { items } = this;
1385
- if (!items)
1386
- return [];
1387
- return [...items.values()];
1388
- }
1389
- dispose() {
1390
- this.items.clear();
1391
- this.path = "";
1392
- this._removeWatcher = EMPTY_FN;
1393
- this.items = EMPTY_SET;
1394
- Object.freeze(this);
1395
- }
1396
- };
1397
- var STAT_METHOD_F = "stat";
1398
- var STAT_METHOD_L = "lstat";
1399
- var WatchHelper = class {
1400
- constructor(path, follow, fsw) {
1401
- this.fsw = fsw;
1402
- const watchPath = path;
1403
- this.path = path = path.replace(REPLACER_RE, "");
1404
- this.watchPath = watchPath;
1405
- this.fullWatchPath = sysPath2.resolve(watchPath);
1406
- this.dirParts = [];
1407
- this.dirParts.forEach((parts) => {
1408
- if (parts.length > 1)
1409
- parts.pop();
1410
- });
1411
- this.followSymlinks = follow;
1412
- this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
1413
- }
1414
- entryPath(entry) {
1415
- return sysPath2.join(this.watchPath, sysPath2.relative(this.watchPath, entry.fullPath));
1416
- }
1417
- filterPath(entry) {
1418
- const { stats } = entry;
1419
- if (stats && stats.isSymbolicLink())
1420
- return this.filterDir(entry);
1421
- const resolvedPath = this.entryPath(entry);
1422
- return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
1423
- }
1424
- filterDir(entry) {
1425
- return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
1426
- }
1427
- };
1428
- var FSWatcher = class extends EventEmitter {
1429
- // Not indenting methods for history sake; for now.
1430
- constructor(_opts = {}) {
1431
- super();
1432
- this.closed = false;
1433
- this._closers = /* @__PURE__ */ new Map();
1434
- this._ignoredPaths = /* @__PURE__ */ new Set();
1435
- this._throttled = /* @__PURE__ */ new Map();
1436
- this._streams = /* @__PURE__ */ new Set();
1437
- this._symlinkPaths = /* @__PURE__ */ new Map();
1438
- this._watched = /* @__PURE__ */ new Map();
1439
- this._pendingWrites = /* @__PURE__ */ new Map();
1440
- this._pendingUnlinks = /* @__PURE__ */ new Map();
1441
- this._readyCount = 0;
1442
- this._readyEmitted = false;
1443
- const awf = _opts.awaitWriteFinish;
1444
- const DEF_AWF = { stabilityThreshold: 2e3, pollInterval: 100 };
1445
- const opts = {
1446
- // Defaults
1447
- persistent: true,
1448
- ignoreInitial: false,
1449
- ignorePermissionErrors: false,
1450
- interval: 100,
1451
- binaryInterval: 300,
1452
- followSymlinks: true,
1453
- usePolling: false,
1454
- // useAsync: false,
1455
- atomic: true,
1456
- // NOTE: overwritten later (depends on usePolling)
1457
- ..._opts,
1458
- // Change format
1459
- ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
1460
- awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
1461
- };
1462
- if (isIBMi)
1463
- opts.usePolling = true;
1464
- if (opts.atomic === void 0)
1465
- opts.atomic = !opts.usePolling;
1466
- const envPoll = process.env.CHOKIDAR_USEPOLLING;
1467
- if (envPoll !== void 0) {
1468
- const envLower = envPoll.toLowerCase();
1469
- if (envLower === "false" || envLower === "0")
1470
- opts.usePolling = false;
1471
- else if (envLower === "true" || envLower === "1")
1472
- opts.usePolling = true;
1473
- else
1474
- opts.usePolling = !!envLower;
1475
- }
1476
- const envInterval = process.env.CHOKIDAR_INTERVAL;
1477
- if (envInterval)
1478
- opts.interval = Number.parseInt(envInterval, 10);
1479
- let readyCalls = 0;
1480
- this._emitReady = () => {
1481
- readyCalls++;
1482
- if (readyCalls >= this._readyCount) {
1483
- this._emitReady = EMPTY_FN;
1484
- this._readyEmitted = true;
1485
- process.nextTick(() => this.emit(EVENTS.READY));
1486
- }
1487
- };
1488
- this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
1489
- this._boundRemove = this._remove.bind(this);
1490
- this.options = opts;
1491
- this._nodeFsHandler = new NodeFsHandler(this);
1492
- Object.freeze(opts);
1493
- }
1494
- _addIgnoredPath(matcher) {
1495
- if (isMatcherObject(matcher)) {
1496
- for (const ignored of this._ignoredPaths) {
1497
- if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
1498
- return;
1499
- }
1500
- }
1501
- }
1502
- this._ignoredPaths.add(matcher);
1503
- }
1504
- _removeIgnoredPath(matcher) {
1505
- this._ignoredPaths.delete(matcher);
1506
- if (typeof matcher === "string") {
1507
- for (const ignored of this._ignoredPaths) {
1508
- if (isMatcherObject(ignored) && ignored.path === matcher) {
1509
- this._ignoredPaths.delete(ignored);
1510
- }
1511
- }
1512
- }
1513
- }
1514
- // Public methods
1515
- /**
1516
- * Adds paths to be watched on an existing FSWatcher instance.
1517
- * @param paths_ file or file list. Other arguments are unused
1518
- */
1519
- add(paths_, _origAdd, _internal) {
1520
- const { cwd } = this.options;
1521
- this.closed = false;
1522
- this._closePromise = void 0;
1523
- let paths2 = unifyPaths(paths_);
1524
- if (cwd) {
1525
- paths2 = paths2.map((path) => {
1526
- const absPath = getAbsolutePath(path, cwd);
1527
- return absPath;
1528
- });
1529
- }
1530
- paths2.forEach((path) => {
1531
- this._removeIgnoredPath(path);
1532
- });
1533
- this._userIgnored = void 0;
1534
- if (!this._readyCount)
1535
- this._readyCount = 0;
1536
- this._readyCount += paths2.length;
1537
- Promise.all(paths2.map(async (path) => {
1538
- const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, void 0, 0, _origAdd);
1539
- if (res)
1540
- this._emitReady();
1541
- return res;
1542
- })).then((results) => {
1543
- if (this.closed)
1544
- return;
1545
- results.forEach((item) => {
1546
- if (item)
1547
- this.add(sysPath2.dirname(item), sysPath2.basename(_origAdd || item));
1548
- });
1549
- });
1550
- return this;
1551
- }
1552
- /**
1553
- * Close watchers or start ignoring events from specified paths.
1554
- */
1555
- unwatch(paths_) {
1556
- if (this.closed)
1557
- return this;
1558
- const paths2 = unifyPaths(paths_);
1559
- const { cwd } = this.options;
1560
- paths2.forEach((path) => {
1561
- if (!sysPath2.isAbsolute(path) && !this._closers.has(path)) {
1562
- if (cwd)
1563
- path = sysPath2.join(cwd, path);
1564
- path = sysPath2.resolve(path);
1565
- }
1566
- this._closePath(path);
1567
- this._addIgnoredPath(path);
1568
- if (this._watched.has(path)) {
1569
- this._addIgnoredPath({
1570
- path,
1571
- recursive: true
1572
- });
1573
- }
1574
- this._userIgnored = void 0;
1575
- });
1576
- return this;
1577
- }
1578
- /**
1579
- * Close watchers and remove all listeners from watched paths.
1580
- */
1581
- close() {
1582
- if (this._closePromise) {
1583
- return this._closePromise;
1584
- }
1585
- this.closed = true;
1586
- this.removeAllListeners();
1587
- const closers = [];
1588
- this._closers.forEach((closerList) => closerList.forEach((closer) => {
1589
- const promise = closer();
1590
- if (promise instanceof Promise)
1591
- closers.push(promise);
1592
- }));
1593
- this._streams.forEach((stream) => stream.destroy());
1594
- this._userIgnored = void 0;
1595
- this._readyCount = 0;
1596
- this._readyEmitted = false;
1597
- this._watched.forEach((dirent) => dirent.dispose());
1598
- this._closers.clear();
1599
- this._watched.clear();
1600
- this._streams.clear();
1601
- this._symlinkPaths.clear();
1602
- this._throttled.clear();
1603
- this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
1604
- return this._closePromise;
1605
- }
1606
- /**
1607
- * Expose list of watched paths
1608
- * @returns for chaining
1609
- */
1610
- getWatched() {
1611
- const watchList = {};
1612
- this._watched.forEach((entry, dir) => {
1613
- const key = this.options.cwd ? sysPath2.relative(this.options.cwd, dir) : dir;
1614
- const index = key || ONE_DOT;
1615
- watchList[index] = entry.getChildren().sort();
1616
- });
1617
- return watchList;
1618
- }
1619
- emitWithAll(event, args) {
1620
- this.emit(event, ...args);
1621
- if (event !== EVENTS.ERROR)
1622
- this.emit(EVENTS.ALL, event, ...args);
1623
- }
1624
- // Common helpers
1625
- // --------------
1626
- /**
1627
- * Normalize and emit events.
1628
- * Calling _emit DOES NOT MEAN emit() would be called!
1629
- * @param event Type of event
1630
- * @param path File or directory path
1631
- * @param stats arguments to be passed with event
1632
- * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
1633
- */
1634
- async _emit(event, path, stats) {
1635
- if (this.closed)
1636
- return;
1637
- const opts = this.options;
1638
- if (isWindows)
1639
- path = sysPath2.normalize(path);
1640
- if (opts.cwd)
1641
- path = sysPath2.relative(opts.cwd, path);
1642
- const args = [path];
1643
- if (stats != null)
1644
- args.push(stats);
1645
- const awf = opts.awaitWriteFinish;
1646
- let pw;
1647
- if (awf && (pw = this._pendingWrites.get(path))) {
1648
- pw.lastChange = /* @__PURE__ */ new Date();
1649
- return this;
1650
- }
1651
- if (opts.atomic) {
1652
- if (event === EVENTS.UNLINK) {
1653
- this._pendingUnlinks.set(path, [event, ...args]);
1654
- setTimeout(() => {
1655
- this._pendingUnlinks.forEach((entry, path2) => {
1656
- this.emit(...entry);
1657
- this.emit(EVENTS.ALL, ...entry);
1658
- this._pendingUnlinks.delete(path2);
1659
- });
1660
- }, typeof opts.atomic === "number" ? opts.atomic : 100);
1661
- return this;
1662
- }
1663
- if (event === EVENTS.ADD && this._pendingUnlinks.has(path)) {
1664
- event = EVENTS.CHANGE;
1665
- this._pendingUnlinks.delete(path);
1666
- }
1667
- }
1668
- if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
1669
- const awfEmit = (err, stats2) => {
1670
- if (err) {
1671
- event = EVENTS.ERROR;
1672
- args[0] = err;
1673
- this.emitWithAll(event, args);
1674
- } else if (stats2) {
1675
- if (args.length > 1) {
1676
- args[1] = stats2;
1677
- } else {
1678
- args.push(stats2);
1679
- }
1680
- this.emitWithAll(event, args);
1681
- }
1682
- };
1683
- this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
1684
- return this;
1685
- }
1686
- if (event === EVENTS.CHANGE) {
1687
- const isThrottled = !this._throttle(EVENTS.CHANGE, path, 50);
1688
- if (isThrottled)
1689
- return this;
1690
- }
1691
- if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
1692
- const fullPath = opts.cwd ? sysPath2.join(opts.cwd, path) : path;
1693
- let stats2;
1694
- try {
1695
- stats2 = await stat4(fullPath);
1696
- } catch (err) {
1697
- }
1698
- if (!stats2 || this.closed)
1699
- return;
1700
- args.push(stats2);
1701
- }
1702
- this.emitWithAll(event, args);
1703
- return this;
1704
- }
1705
- /**
1706
- * Common handler for errors
1707
- * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
1708
- */
1709
- _handleError(error) {
1710
- const code = error && error.code;
1711
- if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
1712
- this.emit(EVENTS.ERROR, error);
1713
- }
1714
- return error || this.closed;
1715
- }
1716
- /**
1717
- * Helper utility for throttling
1718
- * @param actionType type being throttled
1719
- * @param path being acted upon
1720
- * @param timeout duration of time to suppress duplicate actions
1721
- * @returns tracking object or false if action should be suppressed
1722
- */
1723
- _throttle(actionType, path, timeout) {
1724
- if (!this._throttled.has(actionType)) {
1725
- this._throttled.set(actionType, /* @__PURE__ */ new Map());
1726
- }
1727
- const action = this._throttled.get(actionType);
1728
- if (!action)
1729
- throw new Error("invalid throttle");
1730
- const actionPath = action.get(path);
1731
- if (actionPath) {
1732
- actionPath.count++;
1733
- return false;
1734
- }
1735
- let timeoutObject;
1736
- const clear = () => {
1737
- const item = action.get(path);
1738
- const count = item ? item.count : 0;
1739
- action.delete(path);
1740
- clearTimeout(timeoutObject);
1741
- if (item)
1742
- clearTimeout(item.timeoutObject);
1743
- return count;
1744
- };
1745
- timeoutObject = setTimeout(clear, timeout);
1746
- const thr = { timeoutObject, clear, count: 0 };
1747
- action.set(path, thr);
1748
- return thr;
1749
- }
1750
- _incrReadyCount() {
1751
- return this._readyCount++;
1752
- }
1753
- /**
1754
- * Awaits write operation to finish.
1755
- * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
1756
- * @param path being acted upon
1757
- * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
1758
- * @param event
1759
- * @param awfEmit Callback to be called when ready for event to be emitted.
1760
- */
1761
- _awaitWriteFinish(path, threshold, event, awfEmit) {
1762
- const awf = this.options.awaitWriteFinish;
1763
- if (typeof awf !== "object")
1764
- return;
1765
- const pollInterval = awf.pollInterval;
1766
- let timeoutHandler;
1767
- let fullPath = path;
1768
- if (this.options.cwd && !sysPath2.isAbsolute(path)) {
1769
- fullPath = sysPath2.join(this.options.cwd, path);
1770
- }
1771
- const now = /* @__PURE__ */ new Date();
1772
- const writes = this._pendingWrites;
1773
- function awaitWriteFinishFn(prevStat) {
1774
- statcb(fullPath, (err, curStat) => {
1775
- if (err || !writes.has(path)) {
1776
- if (err && err.code !== "ENOENT")
1777
- awfEmit(err);
1778
- return;
1779
- }
1780
- const now2 = Number(/* @__PURE__ */ new Date());
1781
- if (prevStat && curStat.size !== prevStat.size) {
1782
- writes.get(path).lastChange = now2;
1783
- }
1784
- const pw = writes.get(path);
1785
- const df = now2 - pw.lastChange;
1786
- if (df >= threshold) {
1787
- writes.delete(path);
1788
- awfEmit(void 0, curStat);
1789
- } else {
1790
- timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
1791
- }
1792
- });
1793
- }
1794
- if (!writes.has(path)) {
1795
- writes.set(path, {
1796
- lastChange: now,
1797
- cancelWait: () => {
1798
- writes.delete(path);
1799
- clearTimeout(timeoutHandler);
1800
- return event;
1801
- }
1802
- });
1803
- timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
1804
- }
1805
- }
1806
- /**
1807
- * Determines whether user has asked to ignore this path.
1808
- */
1809
- _isIgnored(path, stats) {
1810
- if (this.options.atomic && DOT_RE.test(path))
1811
- return true;
1812
- if (!this._userIgnored) {
1813
- const { cwd } = this.options;
1814
- const ign = this.options.ignored;
1815
- const ignored = (ign || []).map(normalizeIgnored(cwd));
1816
- const ignoredPaths = [...this._ignoredPaths];
1817
- const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
1818
- this._userIgnored = anymatch(list, void 0);
1819
- }
1820
- return this._userIgnored(path, stats);
1821
- }
1822
- _isntIgnored(path, stat6) {
1823
- return !this._isIgnored(path, stat6);
1824
- }
1825
- /**
1826
- * Provides a set of common helpers and properties relating to symlink handling.
1827
- * @param path file or directory pattern being watched
1828
- */
1829
- _getWatchHelpers(path) {
1830
- return new WatchHelper(path, this.options.followSymlinks, this);
1831
- }
1832
- // Directory helpers
1833
- // -----------------
1834
- /**
1835
- * Provides directory tracking objects
1836
- * @param directory path of the directory
1837
- */
1838
- _getWatchedDir(directory) {
1839
- const dir = sysPath2.resolve(directory);
1840
- if (!this._watched.has(dir))
1841
- this._watched.set(dir, new DirEntry(dir, this._boundRemove));
1842
- return this._watched.get(dir);
1843
- }
1844
- // File helpers
1845
- // ------------
1846
- /**
1847
- * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
1848
- */
1849
- _hasReadPermissions(stats) {
1850
- if (this.options.ignorePermissionErrors)
1851
- return true;
1852
- return Boolean(Number(stats.mode) & 256);
1853
- }
1854
- /**
1855
- * Handles emitting unlink events for
1856
- * files and directories, and via recursion, for
1857
- * files and directories within directories that are unlinked
1858
- * @param directory within which the following item is located
1859
- * @param item base path of item/directory
1860
- */
1861
- _remove(directory, item, isDirectory) {
1862
- const path = sysPath2.join(directory, item);
1863
- const fullPath = sysPath2.resolve(path);
1864
- isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
1865
- if (!this._throttle("remove", path, 100))
1866
- return;
1867
- if (!isDirectory && this._watched.size === 1) {
1868
- this.add(directory, item, true);
1869
- }
1870
- const wp = this._getWatchedDir(path);
1871
- const nestedDirectoryChildren = wp.getChildren();
1872
- nestedDirectoryChildren.forEach((nested) => this._remove(path, nested));
1873
- const parent = this._getWatchedDir(directory);
1874
- const wasTracked = parent.has(item);
1875
- parent.remove(item);
1876
- if (this._symlinkPaths.has(fullPath)) {
1877
- this._symlinkPaths.delete(fullPath);
1878
- }
1879
- let relPath = path;
1880
- if (this.options.cwd)
1881
- relPath = sysPath2.relative(this.options.cwd, path);
1882
- if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
1883
- const event = this._pendingWrites.get(relPath).cancelWait();
1884
- if (event === EVENTS.ADD)
1885
- return;
1886
- }
1887
- this._watched.delete(path);
1888
- this._watched.delete(fullPath);
1889
- const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
1890
- if (wasTracked && !this._isIgnored(path))
1891
- this._emit(eventName, path);
1892
- this._closePath(path);
1893
- }
1894
- /**
1895
- * Closes all watchers for a path
1896
- */
1897
- _closePath(path) {
1898
- this._closeFile(path);
1899
- const dir = sysPath2.dirname(path);
1900
- this._getWatchedDir(dir).remove(sysPath2.basename(path));
1901
- }
1902
- /**
1903
- * Closes only file-specific watchers
1904
- */
1905
- _closeFile(path) {
1906
- const closers = this._closers.get(path);
1907
- if (!closers)
1908
- return;
1909
- closers.forEach((closer) => closer());
1910
- this._closers.delete(path);
1911
- }
1912
- _addPathCloser(path, closer) {
1913
- if (!closer)
1914
- return;
1915
- let list = this._closers.get(path);
1916
- if (!list) {
1917
- list = [];
1918
- this._closers.set(path, list);
1919
- }
1920
- list.push(closer);
1921
- }
1922
- _readdirp(root, opts) {
1923
- if (this.closed)
1924
- return;
1925
- const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
1926
- let stream = readdirp(root, options);
1927
- this._streams.add(stream);
1928
- stream.once(STR_CLOSE, () => {
1929
- stream = void 0;
1930
- });
1931
- stream.once(STR_END, () => {
1932
- if (stream) {
1933
- this._streams.delete(stream);
1934
- stream = void 0;
1935
- }
1936
- });
1937
- return stream;
1938
- }
1939
- };
1940
- function watch(paths2, options = {}) {
1941
- const watcher = new FSWatcher(options);
1942
- watcher.add(paths2);
1943
- return watcher;
1944
- }
1945
- var esm_default = { watch, FSWatcher };
1946
-
1947
- // src/watch.ts
1948
- async function watchInbox(corpus, onDrain) {
1949
- await corpus.init();
1950
- const index = await openSearchIndex(corpus);
1951
- let draining = false;
1952
- let pending = false;
1953
- const runDrain = async () => {
1954
- if (draining) {
1955
- pending = true;
1956
- return;
1957
- }
1958
- draining = true;
1959
- try {
1960
- do {
1961
- pending = false;
1962
- const report = await drainInbox(corpus, index);
1963
- if (report.files > 0) {
1964
- onDrain?.(report);
1965
- }
1966
- } while (pending);
1967
- } finally {
1968
- draining = false;
1969
- }
1970
- };
1971
- const watcher = esm_default.watch(corpus.paths.inboxDir, {
1972
- ignoreInitial: true,
1973
- depth: 0,
1974
- awaitWriteFinish: { stabilityThreshold: 300, pollInterval: 100 }
1975
- });
1976
- watcher.on("add", () => void runDrain());
1977
- await runDrain();
1978
- return {
1979
- close: async () => {
1980
- await watcher.close();
1981
- index.close();
1982
- }
1983
- };
1984
- }
1985
-
1986
- // src/clientRegistration.ts
1987
- import { execFile as execFile2 } from "child_process";
1988
- import { readFile as readFile2, stat as stat5, writeFile as writeFile2 } from "fs/promises";
1989
- import { homedir as homedir2, platform as platform2 } from "os";
1990
- import { dirname as dirname4, join as join4 } from "path";
1991
- import { promisify as promisify2 } from "util";
1992
- var execFileAsync2 = promisify2(execFile2);
1993
- var SERVER_NAME = "llmnesia";
1994
- var realClaudeCli = {
1995
- detect: async () => {
1996
- try {
1997
- await execFileAsync2(process.platform === "win32" ? "where" : "which", ["claude"]);
1998
- return true;
1999
- } catch {
2000
- return false;
2001
- }
2002
- },
2003
- add: async (name, serve) => {
2004
- await execFileAsync2("claude", ["mcp", "add", name, "--", serve.command, ...serve.args]);
2005
- },
2006
- remove: async (name) => {
2007
- await execFileAsync2("claude", ["mcp", "remove", name]);
2008
- }
2009
- };
2010
- function paths(home2, osPlatform2) {
2011
- const claudeDesktop = osPlatform2 === "darwin" ? join4(home2, "Library", "Application Support", "Claude", "claude_desktop_config.json") : osPlatform2 === "win32" ? join4(process.env.APPDATA || join4(home2, "AppData", "Roaming"), "Claude", "claude_desktop_config.json") : null;
2012
- return {
2013
- claudeDesktop,
2014
- cursor: join4(home2, ".cursor", "mcp.json"),
2015
- codex: join4(home2, ".codex", "config.toml")
2016
- };
2017
- }
2018
- async function readJsonFile(path) {
2019
- let raw;
2020
- try {
2021
- raw = await readFile2(path, "utf8");
2022
- } catch (err) {
2023
- if (isErrnoException(err) && err.code === "ENOENT") {
2024
- return { data: {}, existed: false };
2025
- }
2026
- throw new Error(`Could not read ${path}: ${errorMessage(err)}`, { cause: err });
2027
- }
2028
- try {
2029
- const parsed = JSON.parse(raw);
2030
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
2031
- throw new Error("the top-level value must be a JSON object");
2032
- }
2033
- return { data: parsed, existed: true };
2034
- } catch (err) {
2035
- throw new Error(`Could not parse ${path}: ${errorMessage(err)}. The file was left unchanged.`, { cause: err });
2036
- }
2037
- }
2038
- function isErrnoException(value) {
2039
- return value instanceof Error && "code" in value;
2040
- }
2041
- function errorMessage(value) {
2042
- return value instanceof Error ? value.message : String(value);
2043
- }
2044
- async function clientDirExists(configPath) {
2045
- try {
2046
- return (await stat5(dirname4(configPath))).isDirectory();
2047
- } catch {
5
+ VERSION
6
+ } from "./chunk-BQM5Q4XX.js";
7
+
8
+ // src/nodeVersion.ts
9
+ var MINIMUM_NODE_VERSION = "22.13.0";
10
+ function numericParts(version) {
11
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
12
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
13
+ }
14
+ function supportsNodeVersion(version) {
15
+ const actual = numericParts(version);
16
+ const minimum = numericParts(MINIMUM_NODE_VERSION);
17
+ if (!actual || !minimum) {
2048
18
  return false;
2049
19
  }
2050
- }
2051
- async function registerClaudeCode(serve, cli) {
2052
- const present = await cli.detect();
2053
- if (!present) {
2054
- return { client: "Claude Code", action: "skipped", detail: "`claude` not found on PATH." };
2055
- }
2056
- try {
2057
- await cli.add(SERVER_NAME, serve);
2058
- return {
2059
- client: "Claude Code",
2060
- action: "registered",
2061
- detail: `Ran: claude mcp add ${SERVER_NAME} -- ${serve.command} ${serve.args.join(" ")}`
2062
- };
2063
- } catch (err) {
2064
- return {
2065
- client: "Claude Code",
2066
- action: "error",
2067
- detail: `claude mcp add failed: ${err instanceof Error ? err.message : String(err)}`
2068
- };
2069
- }
2070
- }
2071
- async function registerJsonClient(clientLabel, configPath, serve, confirm, now) {
2072
- if (!await clientDirExists(configPath)) {
2073
- return {
2074
- client: clientLabel,
2075
- action: "skipped",
2076
- detail: `Not installed (no ${dirname4(configPath)}). Re-run install after setting it up.`
2077
- };
2078
- }
2079
- let data;
2080
- let existed;
2081
- try {
2082
- ({ data, existed } = await readJsonFile(configPath));
2083
- } catch (err) {
2084
- return { client: clientLabel, action: "error", detail: errorMessage(err) };
2085
- }
2086
- const servers = data.mcpServers && typeof data.mcpServers === "object" ? data.mcpServers : {};
2087
- const already = servers[SERVER_NAME];
2088
- const nextEntry = { command: serve.command, args: serve.args };
2089
- if (already && JSON.stringify(already) === JSON.stringify(nextEntry)) {
2090
- return { client: clientLabel, action: "skipped", detail: `Already registered at ${configPath}.` };
2091
- }
2092
- const preview = JSON.stringify({ mcpServers: { ...servers, [SERVER_NAME]: nextEntry } }, null, 2);
2093
- const message = existed ? `${clientLabel}: update ${configPath} to add the "${SERVER_NAME}" MCP server?
2094
- ${preview}` : `${clientLabel}: create ${configPath} with the "${SERVER_NAME}" MCP server?
2095
- ${preview}`;
2096
- const ok = await confirm(message);
2097
- if (!ok) {
2098
- return { client: clientLabel, action: "declined", detail: `Skipped by user. Config: ${configPath}` };
2099
- }
2100
- if (existed) {
2101
- const backupPath = `${configPath}.bak-${now()}`;
2102
- await writeFile2(backupPath, JSON.stringify(data, null, 2), "utf8");
2103
- }
2104
- const nextData = { ...data, mcpServers: { ...servers, [SERVER_NAME]: nextEntry } };
2105
- await writeFile2(configPath, `${JSON.stringify(nextData, null, 2)}
2106
- `, "utf8");
2107
- return { client: clientLabel, action: "registered", detail: `Wrote ${configPath}.` };
2108
- }
2109
- function codexBlock(serve) {
2110
- const argsToml = serve.args.map((a) => JSON.stringify(a)).join(", ");
2111
- return `[mcp_servers.${SERVER_NAME}]
2112
- command = ${JSON.stringify(serve.command)}
2113
- args = [${argsToml}]
2114
- `;
2115
- }
2116
- function genericBlock(serve) {
2117
- return JSON.stringify({ mcpServers: { [SERVER_NAME]: { command: serve.command, args: serve.args } } }, null, 2);
2118
- }
2119
- async function registerClients(options) {
2120
- const home2 = options.home ?? homedir2();
2121
- const osPlatform2 = options.osPlatform ?? platform2();
2122
- const now = options.now ?? (() => Date.now());
2123
- const { claudeDesktop, cursor, codex } = paths(home2, osPlatform2);
2124
- const results = [];
2125
- results.push(await registerClaudeCode(options.serve, options.claudeCli ?? realClaudeCli));
2126
- if (claudeDesktop) {
2127
- results.push(await registerJsonClient("Claude Desktop", claudeDesktop, options.serve, options.confirm, now));
2128
- }
2129
- results.push(await registerJsonClient("Cursor", cursor, options.serve, options.confirm, now));
2130
- results.push({
2131
- client: "Codex",
2132
- action: "printed",
2133
- detail: `Add this to ${codex} yourself (TOML is fragile to auto-edit):
2134
- ${codexBlock(options.serve)}`
2135
- });
2136
- results.push({
2137
- client: "Other MCP clients (Windsurf, Zed, LM Studio, ...)",
2138
- action: "printed",
2139
- detail: `Any client that accepts a stdio command+args block can use:
2140
- ${genericBlock(options.serve)}`
2141
- });
2142
- return results;
2143
- }
2144
- async function unregisterClaudeCode(cli) {
2145
- const present = await cli.detect();
2146
- if (!present) {
2147
- return { client: "Claude Code", action: "skipped", detail: "`claude` not found on PATH." };
2148
- }
2149
- try {
2150
- await cli.remove(SERVER_NAME);
2151
- return { client: "Claude Code", action: "registered", detail: `Ran: claude mcp remove ${SERVER_NAME}` };
2152
- } catch (err) {
2153
- return {
2154
- client: "Claude Code",
2155
- action: "error",
2156
- detail: `claude mcp remove failed (may already be unregistered): ${err instanceof Error ? err.message : String(err)}`
2157
- };
2158
- }
2159
- }
2160
- async function unregisterJsonClient(clientLabel, configPath, now) {
2161
- let data;
2162
- let existed;
2163
- try {
2164
- ({ data, existed } = await readJsonFile(configPath));
2165
- } catch (err) {
2166
- return { client: clientLabel, action: "error", detail: errorMessage(err) };
2167
- }
2168
- if (!existed) {
2169
- return { client: clientLabel, action: "skipped", detail: `No ${configPath}.` };
2170
- }
2171
- const servers = data.mcpServers && typeof data.mcpServers === "object" ? data.mcpServers : {};
2172
- if (!(SERVER_NAME in servers)) {
2173
- return { client: clientLabel, action: "skipped", detail: `Not registered in ${configPath}.` };
2174
- }
2175
- const backupPath = `${configPath}.bak-${now()}`;
2176
- await writeFile2(backupPath, JSON.stringify(data, null, 2), "utf8");
2177
- const { [SERVER_NAME]: _removed, ...rest } = servers;
2178
- const nextData = { ...data, mcpServers: rest };
2179
- await writeFile2(configPath, `${JSON.stringify(nextData, null, 2)}
2180
- `, "utf8");
2181
- return { client: clientLabel, action: "registered", detail: `Removed from ${configPath} (backup: ${backupPath}).` };
2182
- }
2183
- async function unregisterClients(options = {}) {
2184
- const home2 = options.home ?? homedir2();
2185
- const osPlatform2 = options.osPlatform ?? platform2();
2186
- const now = options.now ?? (() => Date.now());
2187
- const { claudeDesktop, cursor } = paths(home2, osPlatform2);
2188
- const results = [await unregisterClaudeCode(options.claudeCli ?? realClaudeCli)];
2189
- if (claudeDesktop) {
2190
- results.push(await unregisterJsonClient("Claude Desktop", claudeDesktop, now));
2191
- }
2192
- results.push(await unregisterJsonClient("Cursor", cursor, now));
2193
- results.push({
2194
- client: "Codex / other MCP clients",
2195
- action: "skipped",
2196
- detail: "These were only ever printed as copy-paste blocks, never auto-edited \u2014 remove the block yourself if you added it."
2197
- });
2198
- return results;
2199
- }
2200
-
2201
- // src/doctor.ts
2202
- import { existsSync as existsSync2, readFileSync } from "fs";
2203
- import { delimiter, dirname as dirname6, isAbsolute as isAbsolute2, join as join6, sep } from "path";
2204
- import { homedir as homedir4, platform as platform3 } from "os";
2205
-
2206
- // src/runtimeInstall.ts
2207
- import { cp, mkdir as mkdir2, readdir as readdir3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
2208
- import { existsSync } from "fs";
2209
- import { homedir as homedir3 } from "os";
2210
- import { dirname as dirname5, join as join5 } from "path";
2211
- import { fileURLToPath as fileURLToPath2 } from "url";
2212
- function defaultSourceDir() {
2213
- return dirname5(fileURLToPath2(import.meta.url));
2214
- }
2215
- function runtimeBinDir(home2 = homedir3()) {
2216
- return join5(home2, ".llmnesia", "bin");
2217
- }
2218
- async function installRuntime(options = {}) {
2219
- const home2 = options.home ?? homedir3();
2220
- const sourceDir = options.sourceDir ?? defaultSourceDir();
2221
- const nodePath = options.nodePath ?? process.execPath;
2222
- const binDir = runtimeBinDir(home2);
2223
- const sourceEntry = join5(sourceDir, "cli.js");
2224
- if (!existsSync(sourceEntry)) {
2225
- throw new Error(
2226
- `Cannot locate the built runtime: no cli.js in ${sourceDir}. Run this from an installed package (npx @llmnesia/mcp install) or build first (npm run build).`
2227
- );
2228
- }
2229
- await rm2(binDir, { recursive: true, force: true });
2230
- await mkdir2(binDir, { recursive: true });
2231
- for (const name of await readdir3(sourceDir)) {
2232
- await cp(join5(sourceDir, name), join5(binDir, name), { recursive: true });
2233
- }
2234
- await writeFile3(
2235
- join5(binDir, "package.json"),
2236
- `${JSON.stringify(
2237
- {
2238
- name: "llmnesia-mcp-runtime",
2239
- private: true,
2240
- type: "module",
2241
- comment: "Installed copy of @llmnesia/mcp's dist. Managed by `llmnesia-mcp install`; edits are lost on reinstall."
2242
- },
2243
- null,
2244
- 2
2245
- )}
2246
- `,
2247
- "utf8"
2248
- );
2249
- const entry = join5(binDir, "cli.js");
2250
- return {
2251
- binDir,
2252
- entry,
2253
- serve: { command: nodePath, args: [entry, "serve"] },
2254
- sourceDir,
2255
- nodePath
2256
- };
2257
- }
2258
- async function uninstallRuntime(home2 = homedir3()) {
2259
- const binDir = runtimeBinDir(home2);
2260
- if (!existsSync(binDir)) {
2261
- return null;
2262
- }
2263
- await rm2(binDir, { recursive: true, force: true });
2264
- return binDir;
2265
- }
2266
-
2267
- // src/doctor.ts
2268
- function checkNativeHostManifest(home2, osPlatform2) {
2269
- if (osPlatform2 === "win32") {
2270
- const manifestPath = join6(home2, ".llmnesia", `${HOST_NAME}.json`);
2271
- if (existsSync2(manifestPath)) {
2272
- return {
2273
- name: "Native messaging host",
2274
- status: "ok",
2275
- detail: `Manifest present at ${manifestPath}. (This confirms the file the installer writes, not the registry key independently \u2014 re-run "install" if a browser still can't find it.)`
2276
- };
2277
- }
2278
- return {
2279
- name: "Native messaging host",
2280
- status: "missing",
2281
- detail: `No manifest at ${manifestPath}. Run: llmnesia-mcp install`
2282
- };
2283
- }
2284
- const found = [];
2285
- for (const [label, browserDir] of posixBrowsers(home2, osPlatform2)) {
2286
- if (!existsSync2(browserDir)) {
2287
- continue;
2288
- }
2289
- const manifestPath = join6(browserDir, "NativeMessagingHosts", `${HOST_NAME}.json`);
2290
- if (existsSync2(manifestPath)) {
2291
- found.push(label);
2292
- }
2293
- }
2294
- if (found.length > 0) {
2295
- return { name: "Native messaging host", status: "ok", detail: `Registered for: ${found.join(", ")}.` };
2296
- }
2297
- return {
2298
- name: "Native messaging host",
2299
- status: "missing",
2300
- detail: "No browser has the native-messaging manifest installed. Run: llmnesia-mcp install"
2301
- };
2302
- }
2303
- async function checkCorpus(home2, corpusRoot) {
2304
- const configPath = join6(home2, ".llmnesia", "config.json");
2305
- if (!corpusRoot && !existsSync2(configPath)) {
2306
- return {
2307
- name: "Corpus config",
2308
- status: "missing",
2309
- detail: `No ${configPath}. Run: llmnesia-mcp install`
2310
- };
2311
- }
2312
- const root = corpusRoot ?? resolveCorpusDir();
2313
- if (!existsSync2(root)) {
2314
- return {
2315
- name: "Corpus",
2316
- status: "warn",
2317
- detail: `Config points at ${root}, but that directory doesn't exist yet. It's created on first sync from your browser \u2014 open a chat and wait ~a minute. Normal right after installing.`
2318
- };
2319
- }
2320
- try {
2321
- const corpus = new Corpus(root);
2322
- const stats = await corpus.stats();
2323
- if (stats.conversationCount === 0) {
2324
- return {
2325
- name: "Corpus",
2326
- status: "warn",
2327
- detail: `Corpus at ${root} exists but is empty. It fills in as you chat, or on the browser extension's first backfill sync.`
2328
- };
2329
- }
2330
- return {
2331
- name: "Corpus",
2332
- status: "ok",
2333
- detail: `${stats.conversationCount} conversation(s), ${stats.messageCount} message(s) at ${root}.`
2334
- };
2335
- } catch (err) {
2336
- return {
2337
- name: "Corpus",
2338
- status: "warn",
2339
- detail: `Couldn't read corpus at ${root}: ${err instanceof Error ? err.message : String(err)}`
2340
- };
2341
- }
2342
- }
2343
- function commandProblem(command, args = []) {
2344
- const looksLikePath = isAbsolute2(command) || command.includes(sep) || command.includes("/");
2345
- if (looksLikePath) {
2346
- if (!existsSync2(command)) {
2347
- return `its command does not exist: ${command}`;
2348
- }
2349
- } else if (!resolveOnPath(command)) {
2350
- return `its command "${command}" is not on PATH. GUI clients get a minimal PATH (no nvm, no homebrew), so a bare command name is unreliable even when your shell can find it. Re-run: llmnesia-mcp install`;
2351
- }
2352
- const script = args.find((a) => a.endsWith(".js") || a.endsWith(".mjs"));
2353
- if (script && (isAbsolute2(script) || script.includes(sep)) && !existsSync2(script)) {
2354
- return `its script does not exist: ${script}. Re-run: llmnesia-mcp install`;
2355
- }
2356
- return null;
2357
- }
2358
- function resolveOnPath(command) {
2359
- const exts = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
2360
- for (const dir of (process.env.PATH ?? "").split(delimiter)) {
2361
- if (!dir) {
2362
- continue;
2363
- }
2364
- for (const ext of exts) {
2365
- if (existsSync2(join6(dir, command + ext))) {
2366
- return true;
2367
- }
2368
- }
2369
- }
2370
- return false;
2371
- }
2372
- function checkRuntime(home2) {
2373
- const entry = join6(runtimeBinDir(home2), "cli.js");
2374
- if (existsSync2(entry)) {
2375
- return { name: "MCP server runtime", status: "ok", detail: `Installed at ${entry}.` };
2376
- }
2377
- return {
2378
- name: "MCP server runtime",
2379
- status: "missing",
2380
- detail: `No runtime at ${entry}. Clients spawn this copy, so registration alone is not enough. Run: llmnesia-mcp install`
2381
- };
2382
- }
2383
- async function checkJsonClient(label, configPath) {
2384
- if (!existsSync2(dirname6(configPath))) {
2385
- return { name: label, status: "warn", detail: `Not installed (no ${dirname6(configPath)}).` };
2386
- }
2387
- if (!existsSync2(configPath)) {
2388
- return {
2389
- name: label,
2390
- status: "missing",
2391
- detail: `${label} is installed but has no MCP config yet. Run: llmnesia-mcp install`
2392
- };
2393
- }
2394
- try {
2395
- const data = JSON.parse(readFileSync(configPath, "utf8"));
2396
- const entry = data.mcpServers?.[SERVER_NAME];
2397
- if (!entry) {
2398
- return {
2399
- name: label,
2400
- status: "missing",
2401
- detail: `${label} is installed but not registered. Run: llmnesia-mcp install`
2402
- };
2403
- }
2404
- if (typeof entry.command !== "string") {
2405
- return { name: label, status: "missing", detail: `Registered in ${configPath} but the entry has no command. Run: llmnesia-mcp install` };
2406
- }
2407
- const args = Array.isArray(entry.args) ? entry.args.filter((a) => typeof a === "string") : [];
2408
- const problem = commandProblem(entry.command, args);
2409
- if (problem) {
2410
- return { name: label, status: "missing", detail: `Registered in ${configPath}, but ${problem}` };
20
+ for (let index = 0; index < minimum.length; index += 1) {
21
+ if (actual[index] !== minimum[index]) {
22
+ return actual[index] > minimum[index];
2411
23
  }
2412
- return { name: label, status: "ok", detail: `Registered in ${configPath} and its command resolves.` };
2413
- } catch (err) {
2414
- return {
2415
- name: label,
2416
- status: "warn",
2417
- detail: `Found ${configPath} but couldn't parse it: ${err instanceof Error ? err.message : String(err)}`
2418
- };
2419
24
  }
25
+ return true;
2420
26
  }
2421
- async function checkClaudeCode(cli) {
2422
- if (!await cli.detect()) {
2423
- return {
2424
- name: "Claude Code",
2425
- status: "warn",
2426
- detail: "`claude` not found on PATH \u2014 not installed, or not registered here yet."
2427
- };
2428
- }
2429
- const { execFile: execFile3 } = await import("child_process");
2430
- const { promisify: promisify3 } = await import("util");
2431
- const execFileAsync3 = promisify3(execFile3);
2432
- try {
2433
- const { stdout } = await execFileAsync3("claude", ["mcp", "list"]);
2434
- const line = stdout.split("\n").find((l) => l.trimStart().startsWith(`${SERVER_NAME}:`));
2435
- if (!line) {
2436
- return { name: "Claude Code", status: "missing", detail: "`claude` found but not registered. Run: llmnesia-mcp install" };
2437
- }
2438
- if (/✗|failed|error/i.test(line)) {
2439
- return { name: "Claude Code", status: "missing", detail: `Registered but not connecting \u2014 ${line.trim()}` };
2440
- }
2441
- return { name: "Claude Code", status: "ok", detail: `Registered: ${line.trim()}` };
2442
- } catch (err) {
2443
- return {
2444
- name: "Claude Code",
2445
- status: "warn",
2446
- detail: `\`claude mcp list\` failed: ${err instanceof Error ? err.message : String(err)}`
2447
- };
2448
- }
2449
- }
2450
- function checkCodex(home2) {
2451
- const configPath = join6(home2, ".codex", "config.toml");
2452
- if (!existsSync2(configPath)) {
2453
- return { name: "Codex", status: "warn", detail: `Not installed (no ${configPath}), or never configured.` };
2454
- }
2455
- let text;
2456
- try {
2457
- text = readFileSync(configPath, "utf8");
2458
- } catch (err) {
2459
- return {
2460
- name: "Codex",
2461
- status: "warn",
2462
- detail: `Found ${configPath} but couldn't read it: ${err instanceof Error ? err.message : String(err)}`
2463
- };
2464
- }
2465
- if (text.includes(`mcp_servers.${SERVER_NAME}`)) {
2466
- return { name: "Codex", status: "ok", detail: `Found in ${configPath}.` };
2467
- }
2468
- return {
2469
- name: "Codex",
2470
- status: "missing",
2471
- detail: `Codex is installed but not configured. llmnesia-mcp install prints the TOML block to add to ${configPath}.`
2472
- };
2473
- }
2474
- async function runDoctor(options = {}) {
2475
- const home2 = options.home ?? homedir4();
2476
- const osPlatform2 = options.osPlatform ?? platform3();
2477
- const claudeCli = options.claudeCli ?? realClaudeCli;
2478
- const claudeDesktopPath = osPlatform2 === "darwin" ? join6(home2, "Library", "Application Support", "Claude", "claude_desktop_config.json") : osPlatform2 === "win32" ? join6(process.env.APPDATA || join6(home2, "AppData", "Roaming"), "Claude", "claude_desktop_config.json") : null;
2479
- const checks = [];
2480
- const run = async (name, fn) => {
2481
- try {
2482
- checks.push(await fn());
2483
- } catch (err) {
2484
- checks.push({
2485
- name,
2486
- status: "warn",
2487
- detail: `Check failed unexpectedly: ${err instanceof Error ? err.message : String(err)}`
2488
- });
2489
- }
2490
- };
2491
- await run("Native messaging host", () => checkNativeHostManifest(home2, osPlatform2));
2492
- await run("MCP server runtime", () => checkRuntime(home2));
2493
- await run("Corpus", () => checkCorpus(home2, options.corpusRoot));
2494
- if (claudeDesktopPath) {
2495
- await run("Claude Desktop", () => checkJsonClient("Claude Desktop", claudeDesktopPath));
2496
- }
2497
- await run("Cursor", () => checkJsonClient("Cursor", join6(home2, ".cursor", "mcp.json")));
2498
- await run("Claude Code", () => checkClaudeCode(claudeCli));
2499
- await run("Codex", () => checkCodex(home2));
2500
- checks.push({
2501
- name: "Reminder",
2502
- status: "warn",
2503
- detail: "This can't detect whether you've restarted your browser or MCP client since installing \u2014 a fully quit-and-reopen is required for any of the above to take effect."
2504
- });
2505
- return { checks, allOk: checks.every((c) => c.status !== "missing") };
2506
- }
2507
- function formatDoctorReport(report) {
2508
- const icon = { ok: "\u2713", warn: "\u2022", missing: "\u2717" };
2509
- return report.checks.map((c) => `${icon[c.status]} ${c.name}: ${c.detail}`).join("\n");
2510
- }
2511
-
2512
- // src/cli.ts
2513
- var USAGE = `llmnesia-mcp ${VERSION}
27
+ function unsupportedNodeMessage(version) {
28
+ return `LLMnesia MCP requires Node.js ${MINIMUM_NODE_VERSION} or newer, but this command is running on Node.js ${version}.
2514
29
 
2515
- Usage: llmnesia-mcp <command> [options]
30
+ Install the current Node.js LTS release from https://nodejs.org/ and then run:
31
+ npx -y @llmnesia/mcp@latest install
2516
32
 
2517
- Setup:
2518
- install [ext-id...] Install the native host + register this MCP server with
2519
- detected clients (Claude Code/Desktop, Cursor, Codex, ...)
2520
- doctor Diagnose: host installed? corpus present? clients wired?
2521
- uninstall Remove native host + client registrations (never deletes
2522
- your corpus \u2014 see the printed path if you want that too)
2523
- serve Run the MCP stdio server (what install registers with clients)
2524
-
2525
- Power-user / debugging:
2526
- init Create the corpus directory skeleton
2527
- ingest <file...> Ingest one or more NDJSON backup files into the corpus
2528
- drain Ingest every file in <corpus>/inbox, then archive them
2529
- watch Watch <corpus>/inbox and ingest new deltas live
2530
- stats Print corpus counts (conversations, messages, platforms)
2531
- reindex Drop and rebuild the search index from the corpus
2532
- search <query> Full-text search the corpus (BM25)
2533
-
2534
- Options:
2535
- -c, --corpus <dir> Corpus root (default: $LLMNESIA_CORPUS_DIR or ~/.llmnesia/corpus)
2536
- -n, --limit <n> search: max results (default 10)
2537
- --platform <name> search: restrict to one platform
2538
- --title <substr> search: title must contain this substring
2539
- --from <iso|ms> search: only conversations created on/after this date
2540
- --to <iso|ms> search: only conversations created on/before this date
2541
- --force install: overwrite a differing corpus root in config.json
2542
- --yes, -y install/uninstall: skip confirmation prompts
2543
- --version, -v print the version and exit
33
+ npx cannot install Node.js for you. If \`npx\` itself is not found, Node.js is not installed yet.
2544
34
  `;
2545
- function parseDate(value) {
2546
- if (!value) {
2547
- return void 0;
2548
- }
2549
- if (/^\d+$/.test(value)) {
2550
- return Number(value);
2551
- }
2552
- const ms = Date.parse(value);
2553
- return Number.isNaN(ms) ? void 0 : ms;
2554
35
  }
2555
- async function promptConfirm(message) {
2556
- const rl = createInterface({ input: process.stdin, output: process.stdout });
2557
- try {
2558
- process.stdout.write(`
2559
- ${message}
2560
- `);
2561
- const answer = await rl.question("Proceed? [y/N] ");
2562
- return /^y(es)?$/i.test(answer.trim());
2563
- } finally {
2564
- rl.close();
2565
- }
2566
- }
2567
- function printRegistrationResults(results) {
2568
- for (const r of results) {
2569
- const icon = r.action === "registered" ? "\u2713" : r.action === "error" ? "\u2717" : "\u2022";
2570
- process.stdout.write(`${icon} ${r.client}: ${r.detail}
2571
-
2572
- `);
2573
- }
2574
- }
2575
- async function runInstall(positionals, options, flags) {
2576
- const skipConfirm = flags.has("yes");
2577
- process.stdout.write("Installing native messaging host\u2026\n");
2578
- try {
2579
- await installNativeHost({ ids: positionals, corpus: options.corpus, force: flags.has("force") });
2580
- } catch (err) {
2581
- process.stderr.write(`
2582
- Native host install failed: ${err instanceof Error ? err.message : String(err)}
2583
- `);
2584
- process.stderr.write("Continuing to register MCP clients anyway \u2014 the server itself doesn't need a browser.\n");
2585
- }
2586
- process.stdout.write("\nInstalling the MCP server runtime\u2026\n");
2587
- const runtime = await installRuntime();
2588
- process.stdout.write(`Installed to ${runtime.binDir} (running on ${runtime.nodePath})
2589
- `);
2590
- process.stdout.write("\nRegistering MCP clients\u2026\n\n");
2591
- const confirm = skipConfirm ? async () => true : promptConfirm;
2592
- const results = await registerClients({ serve: runtime.serve, confirm });
2593
- printRegistrationResults(results);
2594
- process.stdout.write(
2595
- "Next step: fully quit and reopen your MCP client (and your browser, if you\nuse the extension). Reloading a window is not enough \u2014 the config is read\nonce at startup.\n\n"
2596
- );
2597
- process.stdout.write("Then run `llmnesia-mcp doctor` to check what's wired up.\n");
2598
- return 0;
2599
- }
2600
- async function runUninstall(flags) {
2601
- const skipConfirm = flags.has("yes");
2602
- if (!skipConfirm) {
2603
- const ok = await promptConfirm(
2604
- "This removes the native-messaging host and MCP client registrations. Your corpus (conversation data) is never deleted by this command."
2605
- );
2606
- if (!ok) {
2607
- process.stdout.write("Cancelled.\n");
2608
- return 0;
2609
- }
2610
- }
2611
- const hostResult = await uninstallNativeHost();
2612
- process.stdout.write(`Removed: ${hostResult.removed.length > 0 ? hostResult.removed.join(", ") : "(nothing to remove)"}
2613
- `);
2614
- const removedRuntime = await uninstallRuntime();
2615
- process.stdout.write(`Removed runtime: ${removedRuntime ?? "(none installed)"}
2616
36
 
2617
- `);
2618
- const results = await unregisterClients();
2619
- printRegistrationResults(results);
2620
- if (hostResult.corpusRoot) {
2621
- process.stdout.write(
2622
- `Your corpus was NOT deleted \u2014 it's still at ${hostResult.corpusRoot}
2623
- Delete it yourself if you want your data gone: rm -rf "${hostResult.corpusRoot}"
2624
- `
2625
- );
2626
- }
2627
- return 0;
2628
- }
2629
- async function main() {
2630
- const { command, positionals, options, flags } = parseArgs(process.argv.slice(2));
2631
- if (flags.has("version")) {
37
+ // src/bootstrap.ts
38
+ async function bootstrap() {
39
+ const argv = process.argv.slice(2);
40
+ if (argv.includes("--version") || argv.includes("-v")) {
2632
41
  process.stdout.write(`${VERSION}
2633
42
  `);
2634
43
  return 0;
2635
44
  }
2636
- if (flags.has("help")) {
2637
- process.stdout.write(USAGE);
2638
- return 0;
2639
- }
2640
- const root = resolveCorpusDir(options.corpus);
2641
- const corpus = new Corpus(root);
2642
- switch (command) {
2643
- case void 0:
2644
- case "help":
2645
- process.stdout.write(USAGE);
2646
- return 0;
2647
- case "install":
2648
- return runInstall(positionals, options, flags);
2649
- case "uninstall":
2650
- return runUninstall(flags);
2651
- case "doctor": {
2652
- const report = await runDoctor();
2653
- process.stdout.write(`${formatDoctorReport(report)}
2654
- `);
2655
- return report.allOk ? 0 : 1;
2656
- }
2657
- case "serve": {
2658
- const { runServe } = await import("./mcp.js");
2659
- await runServe();
2660
- return 0;
2661
- }
2662
- case "init": {
2663
- await corpus.init();
2664
- process.stdout.write(`Initialized corpus at ${root}
2665
- `);
2666
- return 0;
2667
- }
2668
- case "ingest": {
2669
- if (positionals.length === 0) {
2670
- process.stderr.write("ingest: expected at least one file path\n");
2671
- return 2;
2672
- }
2673
- await corpus.init();
2674
- let created = 0;
2675
- let updated = 0;
2676
- let skipped = 0;
2677
- let conversations = 0;
2678
- let malformed = 0;
2679
- for (const file of positionals) {
2680
- const report = await ingestFile(corpus, file);
2681
- created += report.created;
2682
- updated += report.updated;
2683
- skipped += report.skipped;
2684
- conversations += report.conversations;
2685
- malformed += report.malformedLines;
2686
- }
2687
- await corpus.touchIngestMeta();
2688
- process.stdout.write(
2689
- `Ingested ${conversations} conversation(s): ${created} created, ${updated} updated, ${skipped} unchanged` + (malformed > 0 ? `, ${malformed} malformed line(s) skipped` : "") + `
2690
- `
2691
- );
2692
- return 0;
2693
- }
2694
- case "drain": {
2695
- const index = await openSearchIndex(corpus);
2696
- try {
2697
- const report = await drainInbox(corpus, index, {
2698
- onFileError: (name, error) => process.stderr.write(` ! ${name}: ${error instanceof Error ? error.message : String(error)}
2699
- `)
2700
- });
2701
- process.stdout.write(
2702
- `Drained ${report.files} inbox file(s): ${report.conversations} conversation(s) \u2014 ${report.created} created, ${report.updated} updated, ${report.skipped} unchanged` + (report.failed > 0 ? `, ${report.failed} file(s) failed` : "") + `
2703
- `
2704
- );
2705
- } finally {
2706
- index.close();
2707
- }
2708
- return 0;
2709
- }
2710
- case "watch": {
2711
- process.stdout.write(`Watching ${corpus.paths.inboxDir} for new deltas (Ctrl+C to stop)\u2026
2712
- `);
2713
- const handle = await watchInbox(corpus, (s) => {
2714
- process.stdout.write(
2715
- `Ingested ${s.files} file(s): ${s.created} created, ${s.updated} updated, ${s.skipped} unchanged
2716
- `
2717
- );
2718
- });
2719
- await new Promise((resolve4) => {
2720
- const stop = () => {
2721
- void handle.close().then(resolve4);
2722
- };
2723
- process.once("SIGINT", stop);
2724
- process.once("SIGTERM", stop);
2725
- });
2726
- return 0;
2727
- }
2728
- case "stats": {
2729
- const stats = await corpus.stats();
2730
- const platforms = Object.entries(stats.byPlatform).sort((a, b) => b[1] - a[1]).map(([p, n]) => ` ${p}: ${n}`).join("\n");
2731
- process.stdout.write(
2732
- `Corpus: ${root}
2733
- conversations: ${stats.conversationCount}
2734
- messages: ${stats.messageCount}
2735
- ` + (platforms ? ` by platform:
2736
- ${platforms}
2737
- ` : "")
2738
- );
2739
- return 0;
2740
- }
2741
- case "reindex": {
2742
- await corpus.init();
2743
- await deleteIndexDb(corpus.paths.indexDbFile);
2744
- const index = new SearchIndex(corpus.paths.indexDbFile);
2745
- try {
2746
- const { conversations } = await index.rebuildFrom(corpus);
2747
- process.stdout.write(`Rebuilt index: ${conversations} conversation(s)
2748
- `);
2749
- } finally {
2750
- index.close();
2751
- }
2752
- return 0;
2753
- }
2754
- case "search": {
2755
- const query = positionals.join(" ").trim();
2756
- if (!query) {
2757
- process.stderr.write("search: expected a query\n");
2758
- return 2;
2759
- }
2760
- const filters = {
2761
- platform: options.platform || void 0,
2762
- title: options.title || void 0,
2763
- dateFrom: parseDate(options.from),
2764
- dateTo: parseDate(options.to),
2765
- limit: options.limit ? Number(options.limit) : void 0
2766
- };
2767
- const index = await openSearchIndex(corpus);
2768
- try {
2769
- const hits = index.search(query, filters);
2770
- if (hits.length === 0) {
2771
- process.stdout.write("No matches.\n");
2772
- return 0;
2773
- }
2774
- for (const hit of hits) {
2775
- const when = new Date(hit.createdAt).toISOString().slice(0, 10);
2776
- const where = hit.matchRole === "title" ? "title" : `${hit.matchRole} #${hit.matchMsgIndex}`;
2777
- process.stdout.write(
2778
- `${hit.pinned ? "\u2605 " : ""}${hit.title} [${hit.platform} \xB7 ${when} \xB7 score ${hit.score.toFixed(2)}]
2779
- ${hit.docId}
2780
- ${collapse(hit.snippet)} (${where})
2781
-
2782
- `
2783
- );
2784
- }
2785
- } finally {
2786
- index.close();
2787
- }
2788
- return 0;
2789
- }
2790
- default:
2791
- process.stderr.write(`Unknown command: ${command}
2792
-
2793
- ${USAGE}`);
2794
- return 2;
45
+ if (!supportsNodeVersion(process.versions.node)) {
46
+ process.stderr.write(unsupportedNodeMessage(process.versions.node));
47
+ return 1;
2795
48
  }
49
+ const { main } = await import("./cli-CNIF4XT3.js");
50
+ return main();
2796
51
  }
2797
- function collapse(text) {
2798
- return text.replace(/\s+/g, " ").trim();
2799
- }
2800
- main().then((code) => {
52
+ bootstrap().then((code) => {
2801
53
  process.exitCode = code;
2802
54
  }).catch((err) => {
2803
55
  process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
2804
56
  `);
2805
57
  process.exitCode = 1;
2806
58
  });
2807
- /*! Bundled license information:
2808
-
2809
- chokidar/esm/index.js:
2810
- (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
2811
- */
2812
- //# sourceMappingURL=cli.js.map