@optave/codegraph 2.3.1-dev.1aeea34 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,160 @@
1
+ import fs from 'node:fs';
2
+ import https from 'node:https';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ const CACHE_PATH =
7
+ process.env.CODEGRAPH_UPDATE_CACHE_PATH ||
8
+ path.join(os.homedir(), '.codegraph', 'update-check.json');
9
+
10
+ const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
11
+ const FETCH_TIMEOUT_MS = 3000;
12
+ const REGISTRY_URL = 'https://registry.npmjs.org/@optave/codegraph/latest';
13
+
14
+ /**
15
+ * Minimal semver comparison. Returns -1, 0, or 1.
16
+ * Only handles numeric x.y.z (no pre-release tags).
17
+ */
18
+ export function semverCompare(a, b) {
19
+ const pa = a.split('.').map(Number);
20
+ const pb = b.split('.').map(Number);
21
+ for (let i = 0; i < 3; i++) {
22
+ const na = pa[i] || 0;
23
+ const nb = pb[i] || 0;
24
+ if (na < nb) return -1;
25
+ if (na > nb) return 1;
26
+ }
27
+ return 0;
28
+ }
29
+
30
+ /**
31
+ * Load the cached update-check result from disk.
32
+ * Returns null on missing or corrupt file.
33
+ */
34
+ function loadCache(cachePath = CACHE_PATH) {
35
+ try {
36
+ const raw = fs.readFileSync(cachePath, 'utf-8');
37
+ const data = JSON.parse(raw);
38
+ if (!data || typeof data.lastCheckedAt !== 'number' || typeof data.latestVersion !== 'string') {
39
+ return null;
40
+ }
41
+ return data;
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Persist the cache to disk (atomic write via temp + rename).
49
+ */
50
+ function saveCache(cache, cachePath = CACHE_PATH) {
51
+ const dir = path.dirname(cachePath);
52
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
53
+
54
+ const tmp = `${cachePath}.tmp.${process.pid}`;
55
+ fs.writeFileSync(tmp, JSON.stringify(cache), 'utf-8');
56
+ fs.renameSync(tmp, cachePath);
57
+ }
58
+
59
+ /**
60
+ * Fetch the latest version string from the npm registry.
61
+ * Returns the version string or null on failure.
62
+ */
63
+ function fetchLatestVersion() {
64
+ return new Promise((resolve) => {
65
+ const req = https.get(
66
+ REGISTRY_URL,
67
+ { timeout: FETCH_TIMEOUT_MS, headers: { Accept: 'application/json' } },
68
+ (res) => {
69
+ if (res.statusCode !== 200) {
70
+ res.resume();
71
+ resolve(null);
72
+ return;
73
+ }
74
+ let body = '';
75
+ res.setEncoding('utf-8');
76
+ res.on('data', (chunk) => {
77
+ body += chunk;
78
+ });
79
+ res.on('end', () => {
80
+ try {
81
+ const data = JSON.parse(body);
82
+ resolve(typeof data.version === 'string' ? data.version : null);
83
+ } catch {
84
+ resolve(null);
85
+ }
86
+ });
87
+ },
88
+ );
89
+ req.on('error', () => resolve(null));
90
+ req.on('timeout', () => {
91
+ req.destroy();
92
+ resolve(null);
93
+ });
94
+ });
95
+ }
96
+
97
+ /**
98
+ * Check whether a newer version of codegraph is available.
99
+ *
100
+ * Returns `{ current, latest }` if an update is available, `null` otherwise.
101
+ * Silently returns null on any error — never affects CLI operation.
102
+ *
103
+ * Options:
104
+ * cachePath — override cache file location (for testing)
105
+ * _fetchLatest — override the fetch function (for testing)
106
+ */
107
+ export async function checkForUpdates(currentVersion, options = {}) {
108
+ // Suppress in non-interactive / CI contexts
109
+ if (process.env.CI) return null;
110
+ if (process.env.NO_UPDATE_CHECK) return null;
111
+ if (!process.stderr.isTTY) return null;
112
+ if (currentVersion.includes('-')) return null;
113
+
114
+ const cachePath = options.cachePath || CACHE_PATH;
115
+ const fetchFn = options._fetchLatest || fetchLatestVersion;
116
+
117
+ try {
118
+ const cache = loadCache(cachePath);
119
+
120
+ // Cache is fresh — use it
121
+ if (cache && Date.now() - cache.lastCheckedAt < CACHE_TTL_MS) {
122
+ if (semverCompare(currentVersion, cache.latestVersion) < 0) {
123
+ return { current: currentVersion, latest: cache.latestVersion };
124
+ }
125
+ return null;
126
+ }
127
+
128
+ // Cache is stale or missing — fetch
129
+ const latest = await fetchFn();
130
+ if (!latest) return null;
131
+
132
+ // Update cache regardless of result
133
+ saveCache({ lastCheckedAt: Date.now(), latestVersion: latest }, cachePath);
134
+
135
+ if (semverCompare(currentVersion, latest) < 0) {
136
+ return { current: currentVersion, latest };
137
+ }
138
+ return null;
139
+ } catch {
140
+ return null;
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Print a visible update notification box to stderr.
146
+ */
147
+ export function printUpdateNotification(current, latest) {
148
+ const msg1 = `Update available: ${current} → ${latest}`;
149
+ const msg2 = 'Run `npm i -g @optave/codegraph` to update';
150
+ const width = Math.max(msg1.length, msg2.length) + 4;
151
+
152
+ const top = `┌${'─'.repeat(width)}┐`;
153
+ const bot = `└${'─'.repeat(width)}┘`;
154
+ const pad1 = ' '.repeat(width - msg1.length - 2);
155
+ const pad2 = ' '.repeat(width - msg2.length - 2);
156
+ const line1 = `│ ${msg1}${pad1}│`;
157
+ const line2 = `│ ${msg2}${pad2}│`;
158
+
159
+ process.stderr.write(`\n${top}\n${line1}\n${line2}\n${bot}\n\n`);
160
+ }
package/src/watcher.js CHANGED
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { readFileSafe } from './builder.js';
4
4
  import { EXTENSIONS, IGNORE_DIRS, normalizePath } from './constants.js';
5
- import { initSchema, openDb } from './db.js';
5
+ import { closeDb, initSchema, openDb } from './db.js';
6
6
  import { appendJournalEntries } from './journal.js';
7
7
  import { info, warn } from './logger.js';
8
8
  import { createParseTreeCache, getActiveEngine, parseFileIncremental } from './parser.js';
@@ -261,7 +261,7 @@ export async function watchProject(rootDir, opts = {}) {
261
261
  }
262
262
  }
263
263
  if (cache) cache.clear();
264
- db.close();
264
+ closeDb(db);
265
265
  process.exit(0);
266
266
  });
267
267
  }