super-nvm 0.0.0-stage → 1.0.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,802 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.NvmCore = exports.NATIVE_CURRENT_LINK = exports.NATIVE_VERSIONS_DIR = exports.SUPER_NVM_DIR = void 0;
37
+ const child_process_1 = require("child_process");
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ const https = __importStar(require("https"));
41
+ exports.SUPER_NVM_DIR = path.join(process.env.LOCALAPPDATA || process.env.USERPROFILE || 'C:\\', 'SuperNVM');
42
+ exports.NATIVE_VERSIONS_DIR = path.join(exports.SUPER_NVM_DIR, 'versions');
43
+ exports.NATIVE_CURRENT_LINK = path.join(exports.SUPER_NVM_DIR, 'current');
44
+ class NvmCore {
45
+ nvmExecutable = 'nvm';
46
+ constructor() {
47
+ this.findNvmBinary();
48
+ try {
49
+ if (!fs.existsSync(exports.NATIVE_VERSIONS_DIR)) {
50
+ fs.mkdirSync(exports.NATIVE_VERSIONS_DIR, { recursive: true });
51
+ }
52
+ }
53
+ catch { }
54
+ }
55
+ findNvmBinary() {
56
+ const defaultPaths = [
57
+ path.join(process.env.LOCALAPPDATA || '', 'Author Software', 'nvm', 'nvm.exe'),
58
+ path.join(process.env.APPDATA || '', 'nvm', 'nvm.exe'),
59
+ path.join(process.env.NVM_HOME || '', 'nvm.exe'),
60
+ 'C:\\Program Files\\nodejs\\nvm.exe'
61
+ ];
62
+ for (const p of defaultPaths) {
63
+ if (p && fs.existsSync(p)) {
64
+ this.nvmExecutable = `"${p}"`;
65
+ return this.nvmExecutable;
66
+ }
67
+ }
68
+ this.nvmExecutable = 'nvm';
69
+ return this.nvmExecutable;
70
+ }
71
+ isNvmAvailable() {
72
+ const raw = this.nvmExecutable.replace(/^"|"$/g, '');
73
+ if (fs.existsSync(raw)) {
74
+ return true;
75
+ }
76
+ try {
77
+ const { execSync } = require('child_process');
78
+ execSync('where nvm', { stdio: 'ignore' });
79
+ return true;
80
+ }
81
+ catch {
82
+ return false;
83
+ }
84
+ }
85
+ getSpawnTarget() {
86
+ const raw = this.nvmExecutable.replace(/^"|"$/g, '');
87
+ if (fs.existsSync(raw)) {
88
+ return { cmd: raw, useShell: false };
89
+ }
90
+ return { cmd: `"${raw}"`, useShell: true };
91
+ }
92
+ async execCmd(cmd) {
93
+ return new Promise((resolve, reject) => {
94
+ (0, child_process_1.exec)(cmd, { windowsHide: true, env: process.env }, (error, stdout, stderr) => {
95
+ if (error) {
96
+ // Some commands like nvm list might exit 0 or emit to stderr
97
+ const output = (stdout || '') + (stderr || '');
98
+ if (output.trim()) {
99
+ return resolve(output);
100
+ }
101
+ return reject(error);
102
+ }
103
+ resolve(stdout || stderr || '');
104
+ });
105
+ });
106
+ }
107
+ async getInstalledVersions() {
108
+ const list = [];
109
+ const seen = new Set();
110
+ // 1. Check NVM if available
111
+ if (this.isNvmAvailable()) {
112
+ try {
113
+ const output = await this.execCmd(`${this.nvmExecutable} list`);
114
+ const nvmVersions = this.parseInstalledVersions(output);
115
+ for (const v of nvmVersions) {
116
+ list.push(v);
117
+ seen.add(v.version);
118
+ }
119
+ }
120
+ catch (err) {
121
+ console.error('Error getting installed versions from NVM:', err);
122
+ }
123
+ }
124
+ // 2. Check Super NVM Native versions
125
+ if (fs.existsSync(exports.NATIVE_VERSIONS_DIR)) {
126
+ try {
127
+ const entries = fs.readdirSync(exports.NATIVE_VERSIONS_DIR, { withFileTypes: true });
128
+ for (const entry of entries) {
129
+ if (entry.isDirectory() && entry.name.startsWith('v')) {
130
+ const verStr = entry.name.replace(/^v/, '');
131
+ if (!seen.has(verStr)) {
132
+ let isCurrent = false;
133
+ if (fs.existsSync(exports.NATIVE_CURRENT_LINK)) {
134
+ try {
135
+ const target = fs.readlinkSync(exports.NATIVE_CURRENT_LINK);
136
+ if (target.includes(entry.name)) {
137
+ isCurrent = true;
138
+ }
139
+ }
140
+ catch { }
141
+ }
142
+ list.push({
143
+ version: verStr,
144
+ isCurrent,
145
+ isDefault: isCurrent,
146
+ raw: verStr + ' (Super NVM Native)'
147
+ });
148
+ seen.add(verStr);
149
+ }
150
+ }
151
+ }
152
+ }
153
+ catch { }
154
+ }
155
+ return list;
156
+ }
157
+ parseInstalledVersions(output) {
158
+ const versions = [];
159
+ const lines = output.split('\n');
160
+ for (let rawLine of lines) {
161
+ let line = rawLine.trim();
162
+ if (!line)
163
+ continue;
164
+ // Skip header lines or warning lines
165
+ if (line.startsWith('No installations recognized') || line.startsWith('Installed Versions:')) {
166
+ continue;
167
+ }
168
+ const isCurrent = line.startsWith('*');
169
+ const isDefault = line.toLowerCase().includes('default') || isCurrent;
170
+ // Clean string, e.g. "* 24.22.1 (default)" or " 14.21.3" or "* 20.9.0 (Currently using 64-bit executable)"
171
+ let clean = line.replace(/^\*\s*/, '').trim();
172
+ const parts = clean.split(/\s+/);
173
+ const versionStr = parts[0]?.replace(/^v/, '');
174
+ if (versionStr && /^\d+(\.\d+)?(\.\d+)?/.test(versionStr)) {
175
+ versions.push({
176
+ version: versionStr,
177
+ isCurrent,
178
+ isDefault,
179
+ raw: rawLine.trim()
180
+ });
181
+ }
182
+ }
183
+ return versions;
184
+ }
185
+ async getCurrentNodeVersion() {
186
+ try {
187
+ const output = await this.execCmd('node -v');
188
+ const match = output.trim().match(/v?(\d+\.\d+\.\d+)/);
189
+ return match ? match[1] : null;
190
+ }
191
+ catch {
192
+ return null;
193
+ }
194
+ }
195
+ async getNvmInfo() {
196
+ const installed = await this.getInstalledVersions();
197
+ const currentNode = await this.getCurrentNodeVersion();
198
+ const hasNvm = this.isNvmAvailable();
199
+ let nvmVer = hasNvm ? '2.0.1' : '1.0.0 (Native)';
200
+ let operatingMode = hasNvm ? 'nvm (shim)' : 'Super NVM (Native)';
201
+ let nvmPath = hasNvm ? '' : exports.SUPER_NVM_DIR;
202
+ let installsPath = hasNvm ? '' : exports.NATIVE_VERSIONS_DIR;
203
+ if (hasNvm) {
204
+ try {
205
+ const verOut = await this.execCmd(`${this.nvmExecutable} --version`);
206
+ const vMatch = verOut.match(/(\d+\.\d+\.\d+)/);
207
+ if (vMatch)
208
+ nvmVer = vMatch[1];
209
+ }
210
+ catch { }
211
+ try {
212
+ const envOut = await this.execCmd(`${this.nvmExecutable} env`);
213
+ if (envOut.includes('Operating Mode')) {
214
+ const modeMatch = envOut.match(/Operating Mode\s*:\s*(\w+)/);
215
+ if (modeMatch)
216
+ operatingMode = modeMatch[1];
217
+ }
218
+ if (envOut.includes('Path')) {
219
+ const pathMatch = envOut.match(/Path\s*:\s*([^\r\n]+)/);
220
+ if (pathMatch)
221
+ nvmPath = pathMatch[1].trim();
222
+ }
223
+ if (envOut.includes('Installs')) {
224
+ const insMatch = envOut.match(/Path\s*:\s*([^\r\n]+)/);
225
+ if (insMatch)
226
+ installsPath = insMatch[1].trim();
227
+ }
228
+ }
229
+ catch { }
230
+ }
231
+ // Determine strictly ONE active version (source of truth is marked active version)
232
+ const markedActive = installed.find(v => v.isCurrent)?.version;
233
+ const activeVersion = markedActive || installed.find(v => v.version === currentNode)?.version || currentNode || null;
234
+ const defaultVer = markedActive || installed.find(v => v.isDefault)?.version || activeVersion;
235
+ // Guarantee that EXACTLY one version is marked isCurrent
236
+ const enhancedInstalled = installed.map(v => {
237
+ const isAct = Boolean(activeVersion && v.version === activeVersion);
238
+ return {
239
+ ...v,
240
+ isCurrent: isAct,
241
+ isDefault: Boolean(defaultVer && v.version === defaultVer)
242
+ };
243
+ });
244
+ return {
245
+ nvmVersion: nvmVer,
246
+ currentVersion: activeVersion,
247
+ defaultVersion: defaultVer,
248
+ operatingMode,
249
+ nvmPath,
250
+ installsPath,
251
+ installedVersions: enhancedInstalled,
252
+ isNvmInstalled: true
253
+ };
254
+ }
255
+ async use(version) {
256
+ const cleanVer = version.replace(/^v/, '');
257
+ const nativeTarget = path.join(exports.NATIVE_VERSIONS_DIR, 'v' + cleanVer);
258
+ // If native version exists, switch via junction
259
+ if (fs.existsSync(nativeTarget)) {
260
+ try {
261
+ if (fs.existsSync(exports.NATIVE_CURRENT_LINK)) {
262
+ try {
263
+ fs.unlinkSync(exports.NATIVE_CURRENT_LINK);
264
+ }
265
+ catch {
266
+ fs.rmSync(exports.NATIVE_CURRENT_LINK, { recursive: true, force: true });
267
+ }
268
+ }
269
+ fs.symlinkSync(nativeTarget, exports.NATIVE_CURRENT_LINK, 'junction');
270
+ this.ensureInPath(exports.NATIVE_CURRENT_LINK);
271
+ return {
272
+ success: true,
273
+ message: `Now using Node.js v${cleanVer} (Super NVM Native)`
274
+ };
275
+ }
276
+ catch (err) {
277
+ return {
278
+ success: false,
279
+ message: `Failed to link Node.js v${cleanVer}: ${err.message}`
280
+ };
281
+ }
282
+ }
283
+ // Otherwise use NVM if available
284
+ if (this.isNvmAvailable()) {
285
+ try {
286
+ const output = await this.execCmd(`${this.nvmExecutable} use ${cleanVer}`);
287
+ const success = !output.toLowerCase().includes('failed') && !output.toLowerCase().includes('error');
288
+ return {
289
+ success,
290
+ message: output.trim() || `Switched to Node.js v${cleanVer}`
291
+ };
292
+ }
293
+ catch (err) {
294
+ return {
295
+ success: false,
296
+ message: err.message || `Failed to switch to Node.js v${version}`
297
+ };
298
+ }
299
+ }
300
+ return {
301
+ success: false,
302
+ message: `Node.js v${cleanVer} is not installed.`
303
+ };
304
+ }
305
+ ensureInPath(dir) {
306
+ const currentPath = process.env.PATH || '';
307
+ if (!currentPath.toLowerCase().includes(dir.toLowerCase())) {
308
+ try {
309
+ process.env.PATH = `${dir};${currentPath}`;
310
+ const psCmd = `
311
+ $curr = [Environment]::GetEnvironmentVariable('Path', 'User')
312
+ if ($curr -notlike '*${dir}*') {
313
+ [Environment]::SetEnvironmentVariable('Path', "$curr;${dir}", 'User')
314
+ }
315
+ `;
316
+ (0, child_process_1.exec)(`powershell -NoProfile -Command "${psCmd.replace(/\r?\n/g, ' ')}"`, { windowsHide: true });
317
+ }
318
+ catch { }
319
+ }
320
+ }
321
+ install(version, onData, onClose) {
322
+ const cleanVer = version.replace(/^v/, '');
323
+ if (this.isNvmAvailable()) {
324
+ const target = this.getSpawnTarget();
325
+ const child = (0, child_process_1.spawn)(target.cmd, ['install', cleanVer], {
326
+ shell: target.useShell,
327
+ windowsHide: true,
328
+ env: process.env
329
+ });
330
+ child.stdout.on('data', (d) => onData(d.toString()));
331
+ child.stderr.on('data', (d) => onData(d.toString()));
332
+ child.on('close', (code) => onClose(code));
333
+ child.on('error', (err) => {
334
+ onData(`Error: ${err.message}\n`);
335
+ onClose(1);
336
+ });
337
+ return child;
338
+ }
339
+ // Native standalone installation
340
+ this.installNatively(cleanVer, onData, onClose);
341
+ return null;
342
+ }
343
+ async installNatively(version, onData, onClose) {
344
+ onData(`\n[Super NVM Native Engine] Installing Node.js v${version}...\n`);
345
+ const zipUrl = `https://nodejs.org/dist/v${version}/node-v${version}-win-x64.zip`;
346
+ const tempZip = path.join(process.env.TEMP || '.', `node-v${version}-win-x64.zip`);
347
+ const targetDir = path.join(exports.NATIVE_VERSIONS_DIR, `v${version}`);
348
+ if (fs.existsSync(targetDir)) {
349
+ onData(`[Super NVM] Node.js v${version} is already installed.\n`);
350
+ onClose(0);
351
+ return;
352
+ }
353
+ onData(`[Super NVM] Downloading from nodejs.org...\n`);
354
+ try {
355
+ await this.downloadFile(zipUrl, tempZip, (pct, mb, totalMb) => {
356
+ onData(`[Download] ${pct}% (${mb} MB / ${totalMb} MB)\r`);
357
+ });
358
+ onData(`\n[Super NVM] Download complete. Extracting package...\n`);
359
+ if (!fs.existsSync(exports.NATIVE_VERSIONS_DIR)) {
360
+ fs.mkdirSync(exports.NATIVE_VERSIONS_DIR, { recursive: true });
361
+ }
362
+ const extractCmd = `tar -xf "${tempZip}" -C "${exports.NATIVE_VERSIONS_DIR}"`;
363
+ await this.execCmd(extractCmd).catch(async () => {
364
+ await this.execCmd(`powershell -NoProfile -Command "Expand-Archive -Path '${tempZip}' -DestinationPath '${exports.NATIVE_VERSIONS_DIR}' -Force"`);
365
+ });
366
+ const extractedFolderName = `node-v${version}-win-x64`;
367
+ const extractedPath = path.join(exports.NATIVE_VERSIONS_DIR, extractedFolderName);
368
+ if (fs.existsSync(extractedPath)) {
369
+ if (fs.existsSync(targetDir)) {
370
+ fs.rmSync(targetDir, { recursive: true, force: true });
371
+ }
372
+ fs.renameSync(extractedPath, targetDir);
373
+ }
374
+ try {
375
+ fs.unlinkSync(tempZip);
376
+ }
377
+ catch { }
378
+ onData(`[Super NVM] Successfully installed Node.js v${version}!\n`);
379
+ onClose(0);
380
+ }
381
+ catch (err) {
382
+ onData(`\n[Super NVM Error] Failed to install Node.js: ${err.message}\n`);
383
+ onClose(1);
384
+ }
385
+ }
386
+ downloadFile(url, dest, onProgress) {
387
+ return new Promise((resolve, reject) => {
388
+ const file = fs.createWriteStream(dest);
389
+ const req = https.get(url, (res) => {
390
+ if (res.statusCode === 301 || res.statusCode === 302) {
391
+ const redirect = res.headers.location;
392
+ if (redirect) {
393
+ file.close();
394
+ return this.downloadFile(redirect, dest, onProgress).then(resolve).catch(reject);
395
+ }
396
+ }
397
+ if (res.statusCode !== 200) {
398
+ file.close();
399
+ try {
400
+ fs.unlinkSync(dest);
401
+ }
402
+ catch { }
403
+ return reject(new Error(`Server returned HTTP ${res.statusCode}`));
404
+ }
405
+ const totalBytes = parseInt(res.headers['content-length'] || '0', 10);
406
+ let downloadedBytes = 0;
407
+ res.on('data', (chunk) => {
408
+ downloadedBytes += chunk.length;
409
+ if (totalBytes > 0) {
410
+ const pct = Math.round((downloadedBytes / totalBytes) * 100);
411
+ const mb = (downloadedBytes / (1024 * 1024)).toFixed(1);
412
+ const totalMb = (totalBytes / (1024 * 1024)).toFixed(1);
413
+ onProgress(pct, mb, totalMb);
414
+ }
415
+ });
416
+ res.pipe(file);
417
+ file.on('finish', () => {
418
+ file.close();
419
+ resolve();
420
+ });
421
+ });
422
+ req.on('error', (err) => {
423
+ file.close();
424
+ try {
425
+ fs.unlinkSync(dest);
426
+ }
427
+ catch { }
428
+ reject(err);
429
+ });
430
+ });
431
+ }
432
+ uninstall(version, onData, onClose) {
433
+ const cleanVer = version.replace(/^v/, '');
434
+ const nativeTarget = path.join(exports.NATIVE_VERSIONS_DIR, 'v' + cleanVer);
435
+ if (fs.existsSync(nativeTarget)) {
436
+ onData(`[Super NVM] Uninstalling native Node.js v${cleanVer}...\n`);
437
+ try {
438
+ fs.rmSync(nativeTarget, { recursive: true, force: true });
439
+ onData(`[Super NVM] Node.js v${cleanVer} uninstalled successfully.\n`);
440
+ onClose(0);
441
+ }
442
+ catch (e) {
443
+ onData(`Error removing version: ${e.message}\n`);
444
+ onClose(1);
445
+ }
446
+ return null;
447
+ }
448
+ if (this.isNvmAvailable()) {
449
+ const target = this.getSpawnTarget();
450
+ const child = (0, child_process_1.spawn)(target.cmd, ['uninstall', cleanVer], {
451
+ shell: target.useShell,
452
+ windowsHide: true,
453
+ env: process.env
454
+ });
455
+ child.stdout.on('data', (d) => onData(d.toString()));
456
+ child.stderr.on('data', (d) => onData(d.toString()));
457
+ child.on('close', (code) => onClose(code));
458
+ child.on('error', (err) => {
459
+ onData(`Error: ${err.message}\n`);
460
+ onClose(1);
461
+ });
462
+ return child;
463
+ }
464
+ onData(`Node.js v${cleanVer} is not installed.\n`);
465
+ onClose(1);
466
+ return null;
467
+ }
468
+ async fetchRemoteReleases(installedVersions = []) {
469
+ return new Promise((resolve) => {
470
+ const req = https.get('https://nodejs.org/dist/index.json', { headers: { 'User-Agent': 'Super-NVM-Client' }, timeout: 6000 }, (res) => {
471
+ let data = '';
472
+ res.on('data', (chunk) => (data += chunk));
473
+ res.on('end', () => {
474
+ try {
475
+ const list = JSON.parse(data);
476
+ const mapped = list.map((item) => {
477
+ const ver = item.version.replace(/^v/, '');
478
+ return {
479
+ version: ver,
480
+ date: item.date,
481
+ lts: item.lts,
482
+ npm: item.npm,
483
+ security: item.security || false,
484
+ isInstalled: installedVersions.includes(ver)
485
+ };
486
+ });
487
+ resolve(mapped);
488
+ }
489
+ catch (e) {
490
+ resolve(this.fallbackReleases(installedVersions));
491
+ }
492
+ });
493
+ });
494
+ req.on('error', () => {
495
+ resolve(this.fallbackReleases(installedVersions));
496
+ });
497
+ req.on('timeout', () => {
498
+ req.destroy();
499
+ resolve(this.fallbackReleases(installedVersions));
500
+ });
501
+ });
502
+ }
503
+ async fallbackReleases(installedVersions) {
504
+ try {
505
+ const out = await this.execCmd(`${this.nvmExecutable} list releases --limit=25`);
506
+ const lines = out.split('\n');
507
+ const list = [];
508
+ for (let line of lines) {
509
+ const trimmed = line.trim();
510
+ if (!trimmed || trimmed.startsWith('Version') || trimmed.startsWith('---') || trimmed.includes('listed')) {
511
+ continue;
512
+ }
513
+ const parts = trimmed.split(/\s+/);
514
+ if (parts[0] && parts[0].startsWith('v')) {
515
+ const ver = parts[0].replace(/^v/, '');
516
+ list.push({
517
+ version: ver,
518
+ date: parts[1] || '',
519
+ lts: false,
520
+ security: trimmed.includes('security release'),
521
+ isInstalled: installedVersions.includes(ver)
522
+ });
523
+ }
524
+ }
525
+ return list;
526
+ }
527
+ catch {
528
+ return [];
529
+ }
530
+ }
531
+ detectProjectVersion(projectDir) {
532
+ if (!projectDir || !fs.existsSync(projectDir)) {
533
+ return { source: null, requiredVersion: null, rawSpec: null, matchesCurrent: true };
534
+ }
535
+ // Check .nvmrc
536
+ const nvmrcPath = path.join(projectDir, '.nvmrc');
537
+ if (fs.existsSync(nvmrcPath)) {
538
+ const content = fs.readFileSync(nvmrcPath, 'utf8').trim();
539
+ const ver = content.replace(/^v/, '').trim();
540
+ return {
541
+ source: '.nvmrc',
542
+ requiredVersion: ver,
543
+ rawSpec: content,
544
+ matchesCurrent: false // Will be compared against current
545
+ };
546
+ }
547
+ // Check .node-version
548
+ const nodeVerPath = path.join(projectDir, '.node-version');
549
+ if (fs.existsSync(nodeVerPath)) {
550
+ const content = fs.readFileSync(nodeVerPath, 'utf8').trim();
551
+ const ver = content.replace(/^v/, '').trim();
552
+ return {
553
+ source: '.node-version',
554
+ requiredVersion: ver,
555
+ rawSpec: content,
556
+ matchesCurrent: false
557
+ };
558
+ }
559
+ // Check package.json engines.node
560
+ const pkgPath = path.join(projectDir, 'package.json');
561
+ if (fs.existsSync(pkgPath)) {
562
+ try {
563
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
564
+ if (pkg.engines && pkg.engines.node) {
565
+ const spec = pkg.engines.node.trim();
566
+ const clean = spec.replace(/[\^~>=<\s]/g, '');
567
+ return {
568
+ source: 'package.json',
569
+ requiredVersion: clean,
570
+ rawSpec: spec,
571
+ matchesCurrent: false
572
+ };
573
+ }
574
+ }
575
+ catch { }
576
+ }
577
+ return { source: null, requiredVersion: null, rawSpec: null, matchesCurrent: true };
578
+ }
579
+ pinProjectVersion(version, projectDir) {
580
+ if (!projectDir || !fs.existsSync(projectDir))
581
+ return false;
582
+ try {
583
+ const cleanVer = version.replace(/^v/, '').trim();
584
+ fs.writeFileSync(path.join(projectDir, '.nvmrc'), `v${cleanVer}\n`, 'utf8');
585
+ return true;
586
+ }
587
+ catch (e) {
588
+ console.error('Failed to pin version:', e);
589
+ return false;
590
+ }
591
+ }
592
+ getInstallsDirectory() {
593
+ const candidates = [
594
+ path.join(process.env.LOCALAPPDATA || '', 'Author Software', 'nvm', 'installs'),
595
+ path.join(process.env.APPDATA || '', 'nvm'),
596
+ path.join(process.env.NVM_HOME || '', 'installs')
597
+ ];
598
+ for (const c of candidates) {
599
+ if (fs.existsSync(c))
600
+ return c;
601
+ }
602
+ return candidates[0];
603
+ }
604
+ getCacheDirectory() {
605
+ const candidates = [
606
+ path.join(process.env.LOCALAPPDATA || '', 'Author Software', 'nvm', '.cache'),
607
+ path.join(process.env.APPDATA || '', 'nvm', '.cache')
608
+ ];
609
+ for (const c of candidates) {
610
+ if (fs.existsSync(c))
611
+ return c;
612
+ }
613
+ return candidates[0];
614
+ }
615
+ async getGlobalPackages(version) {
616
+ const packages = [];
617
+ const ignored = new Set(['npm', 'corepack', '.verify', '.bin']);
618
+ try {
619
+ let nodeModulesPath = '';
620
+ if (version) {
621
+ const cleanVer = version.replace(/^v/, '');
622
+ const installsDir = this.getInstallsDirectory();
623
+ const vDir = path.join(installsDir, `v${cleanVer}`, 'node_modules');
624
+ const altDir = path.join(installsDir, cleanVer, 'node_modules');
625
+ if (fs.existsSync(vDir))
626
+ nodeModulesPath = vDir;
627
+ else if (fs.existsSync(altDir))
628
+ nodeModulesPath = altDir;
629
+ }
630
+ if (nodeModulesPath && fs.existsSync(nodeModulesPath)) {
631
+ const entries = fs.readdirSync(nodeModulesPath, { withFileTypes: true });
632
+ for (const entry of entries) {
633
+ if (entry.name.startsWith('@') && entry.isDirectory()) {
634
+ const scopeDir = path.join(nodeModulesPath, entry.name);
635
+ const subEntries = fs.readdirSync(scopeDir, { withFileTypes: true });
636
+ for (const sub of subEntries) {
637
+ if (sub.isDirectory() && !ignored.has(sub.name)) {
638
+ const pkgName = `${entry.name}/${sub.name}`;
639
+ let ver = 'installed';
640
+ try {
641
+ const pkgJson = JSON.parse(fs.readFileSync(path.join(scopeDir, sub.name, 'package.json'), 'utf8'));
642
+ ver = pkgJson.version || ver;
643
+ }
644
+ catch { }
645
+ packages.push({ name: pkgName, version: ver });
646
+ }
647
+ }
648
+ }
649
+ else if (entry.isDirectory() && !ignored.has(entry.name)) {
650
+ let ver = 'installed';
651
+ try {
652
+ const pkgJson = JSON.parse(fs.readFileSync(path.join(nodeModulesPath, entry.name, 'package.json'), 'utf8'));
653
+ ver = pkgJson.version || ver;
654
+ }
655
+ catch { }
656
+ packages.push({ name: entry.name, version: ver });
657
+ }
658
+ }
659
+ return packages;
660
+ }
661
+ // Fallback to npm list -g --depth=0 --json
662
+ const jsonOut = await this.execCmd('npm list -g --depth=0 --json');
663
+ const parsed = JSON.parse(jsonOut);
664
+ if (parsed.dependencies) {
665
+ for (const [name, info] of Object.entries(parsed.dependencies)) {
666
+ if (!ignored.has(name)) {
667
+ packages.push({ name, version: info.version || 'installed' });
668
+ }
669
+ }
670
+ }
671
+ }
672
+ catch { }
673
+ return packages;
674
+ }
675
+ migrateGlobalPackages(packages, onData, onClose) {
676
+ if (!packages || packages.length === 0) {
677
+ onData('No packages selected for migration.\n');
678
+ onClose(0);
679
+ return;
680
+ }
681
+ onData(`[Super NVM] Installing global packages: ${packages.join(', ')}...\n`);
682
+ const child = (0, child_process_1.spawn)('npm.cmd', ['install', '-g', ...packages], {
683
+ shell: true,
684
+ windowsHide: true,
685
+ env: process.env
686
+ });
687
+ child.stdout.on('data', (d) => onData(d.toString()));
688
+ child.stderr.on('data', (d) => onData(d.toString()));
689
+ child.on('close', (code) => onClose(code ?? 0));
690
+ child.on('error', (err) => {
691
+ onData(`Migration error: ${err.message}\n`);
692
+ onClose(1);
693
+ });
694
+ return child;
695
+ }
696
+ formatBytes(bytes) {
697
+ if (bytes <= 0)
698
+ return '0 MB';
699
+ const mb = bytes / (1024 * 1024);
700
+ if (mb >= 1024) {
701
+ return `${(mb / 1024).toFixed(2)} GB`;
702
+ }
703
+ return `${mb.toFixed(1)} MB`;
704
+ }
705
+ calculateDirSize(dirPath) {
706
+ let size = 0;
707
+ if (!fs.existsSync(dirPath))
708
+ return 0;
709
+ try {
710
+ const items = fs.readdirSync(dirPath, { withFileTypes: true });
711
+ for (const item of items) {
712
+ const full = path.join(dirPath, item.name);
713
+ try {
714
+ if (item.isDirectory()) {
715
+ size += this.calculateDirSize(full);
716
+ }
717
+ else if (item.isFile()) {
718
+ size += fs.statSync(full).size;
719
+ }
720
+ }
721
+ catch { }
722
+ }
723
+ }
724
+ catch { }
725
+ return size;
726
+ }
727
+ async getStorageInfo() {
728
+ const installed = await this.getInstalledVersions();
729
+ const installsDir = this.getInstallsDirectory();
730
+ const cacheDir = this.getCacheDirectory();
731
+ const versionDetails = [];
732
+ let totalBytes = 0;
733
+ for (const v of installed) {
734
+ const clean = v.version.replace(/^v/, '');
735
+ let vPath = path.join(installsDir, `v${clean}`);
736
+ if (!fs.existsSync(vPath))
737
+ vPath = path.join(installsDir, clean);
738
+ const sz = this.calculateDirSize(vPath);
739
+ totalBytes += sz;
740
+ const pkgs = await this.getGlobalPackages(v.version);
741
+ versionDetails.push({
742
+ version: v.version,
743
+ sizeBytes: sz,
744
+ formattedSize: this.formatBytes(sz),
745
+ packageCount: pkgs.length
746
+ });
747
+ }
748
+ const cacheBytes = this.calculateDirSize(cacheDir);
749
+ totalBytes += cacheBytes;
750
+ return {
751
+ versions: versionDetails,
752
+ cacheSizeBytes: cacheBytes,
753
+ formattedCacheSize: this.formatBytes(cacheBytes),
754
+ totalSizeBytes: totalBytes,
755
+ formattedTotalSize: this.formatBytes(totalBytes)
756
+ };
757
+ }
758
+ async cleanCache() {
759
+ const cacheDir = this.getCacheDirectory();
760
+ let freedBytes = 0;
761
+ try {
762
+ if (fs.existsSync(cacheDir)) {
763
+ freedBytes = this.calculateDirSize(cacheDir);
764
+ try {
765
+ fs.rmSync(cacheDir, { recursive: true, force: true });
766
+ fs.mkdirSync(cacheDir, { recursive: true });
767
+ }
768
+ catch {
769
+ // Fallback if directory lock exists: delete individual files inside
770
+ const entries = fs.readdirSync(cacheDir);
771
+ for (const e of entries) {
772
+ try {
773
+ fs.rmSync(path.join(cacheDir, e), { recursive: true, force: true });
774
+ }
775
+ catch { }
776
+ }
777
+ }
778
+ }
779
+ // Also invoke nvm cache remove if available
780
+ try {
781
+ await this.execCmd(`${this.nvmExecutable} cache remove --all`);
782
+ }
783
+ catch { }
784
+ return {
785
+ success: true,
786
+ freedBytes,
787
+ message: freedBytes > 0
788
+ ? `Successfully cleaned cache, freed ${this.formatBytes(freedBytes)}`
789
+ : 'NVM cache is clean (0 MB freed)'
790
+ };
791
+ }
792
+ catch (err) {
793
+ return {
794
+ success: false,
795
+ freedBytes: 0,
796
+ message: `Failed to clean cache: ${err.message}`
797
+ };
798
+ }
799
+ }
800
+ }
801
+ exports.NvmCore = NvmCore;
802
+ //# sourceMappingURL=nvm.js.map