chvm 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,125 @@
1
+ # نتایج تست‌های اولیه (TDD Phase 1)
2
+
3
+ ## ✅ تست‌ها با موفقیت نوشته و اجرا شدند!
4
+
5
+ ### آمار کلی
6
+
7
+ ```
8
+ Test Suites: 14 total (13 failed, 1 passed)
9
+ Tests: 136 total (113 failed, 23 passed)
10
+ Time: ~1 second
11
+ ```
12
+
13
+ ### توزیع تست‌ها
14
+
15
+ #### تست‌های E2E (End-to-End)
16
+ - `help.test.js` - 4 تست
17
+ - `platform-check.test.js` - 3 تست
18
+ - `ls.test.js` - 4 تست
19
+ - `update.test.js` - 5 تست
20
+ - `install.test.js` - 11 تست
21
+ - `open.test.js` - 8 تست
22
+ - `uninstall.test.js` - 9 تست
23
+
24
+ **مجموع E2E: ~44 تست**
25
+
26
+ #### تست‌های Unit
27
+ - `storage.test.js` - 12 تست
28
+ - `mapping.test.js` - ~15 تست
29
+ - `downloader.test.js` - ~12 تست
30
+ - `installer.test.js` - ~10 تست
31
+ - `platform-check.test.js` - 3 تست
32
+ - `logger.test.js` - ~8 تست
33
+ - `lock.test.js` - ~10 تست
34
+
35
+ **مجموع Unit: ~70 تست**
36
+
37
+ ### تست‌های Pass شده (23)
38
+
39
+ این تست‌ها قبلاً پیاده‌سازی شده‌اند:
40
+
41
+ 1. ✅ `getChvmHome` - بازگشت مسیر CHVM_HOME
42
+ 2. ✅ `checkPlatform` - بررسی پلتفرم macOS ARM
43
+ 3. ✅ `getPlatformInfo` - اطلاعات پلتفرم
44
+ 4. ✅ `isMacOSArm` - تشخیص Apple Silicon
45
+
46
+ ### تست‌های Fail شده (113)
47
+
48
+ این تست‌ها منتظر پیاده‌سازی هستند:
49
+
50
+ 🔴 همه با خطای `"Not implemented yet - TDD stub"` fail می‌شوند
51
+
52
+ این **کاملاً طبیعی** است در TDD!
53
+
54
+ ## مراحل بعدی
55
+
56
+ ### Phase 2: پیاده‌سازی (Red-Green-Refactor)
57
+
58
+ 1. **storage.js** - مدیریت فایل‌های JSON
59
+ - ❌ 10 تست fail
60
+
61
+ 2. **logger.js** - سیستم لاگ
62
+ - ❌ 8 تست fail
63
+
64
+ 3. **lock.js** - قفل‌گذاری فایل
65
+ - ❌ 10 تست fail
66
+
67
+ 4. **mapping.js** - تبدیل revision به version
68
+ - ❌ 15 تست fail
69
+
70
+ 5. **downloader.js** - دانلود استریمی
71
+ - ❌ 12 تست fail
72
+
73
+ 6. **installer.js** - نصب atomic
74
+ - ❌ 10 تست fail
75
+
76
+ 7. **commands/** - دستورات CLI
77
+ - ❌ ~40 تست fail
78
+
79
+ 8. **cli.js** - Entry point
80
+ - ❌ ~8 تست fail
81
+
82
+ ### چگونه شروع کنیم؟
83
+
84
+ ```bash
85
+ # 1. فقط تست‌های storage را اجرا کن
86
+ npx jest tests/unit/storage.test.js --watch
87
+
88
+ # 2. فایل src/lib/storage.js را پیاده‌سازی کن
89
+
90
+ # 3. منتظر بمان تا تست‌ها green شوند
91
+
92
+ # 4. Refactor کن (اگر نیاز بود)
93
+
94
+ # 5. به ماژول بعدی برو
95
+ ```
96
+
97
+ ### ترتیب پیشنهادی
98
+
99
+ 1. ✅ `platform-check.js` (پیاده‌سازی شده)
100
+ 2. ⏳ `storage.js` (بعدی - پایه‌ای‌ترین)
101
+ 3. ⏳ `logger.js`
102
+ 4. ⏳ `lock.js`
103
+ 5. ⏳ `mapping.js`
104
+ 6. ⏳ `downloader.js`
105
+ 7. ⏳ `installer.js`
106
+ 8. ⏳ `commands/*`
107
+ 9. ⏳ `cli.js`
108
+
109
+ ## نتیجه‌گیری
110
+
111
+ ✅ **تست‌ها آماده‌اند!**
112
+ ✅ **ساختار پروژه کامل است!**
113
+ ✅ **TDD به درستی راه‌اندازی شد!**
114
+
115
+ 🎯 **هدف**: همه 136 تست باید Green شوند!
116
+
117
+ ---
118
+
119
+ **Ready to implement? Let's go! 🚀**
120
+
121
+ ```bash
122
+ npm run test:watch
123
+ ```
124
+
125
+
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "chvm",
3
+ "version": "1.0.0",
4
+ "description": "Chrome Version Manager - Manage and run multiple Chromium versions on macOS ARM",
5
+ "type": "module",
6
+ "main": "./src/cli.js",
7
+ "bin": {
8
+ "chvm": "./src/cli.js"
9
+ },
10
+ "scripts": {
11
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest",
12
+ "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch",
13
+ "test:e2e": "NODE_OPTIONS=--experimental-vm-modules jest --testMatch='**/tests/e2e/**/*.test.js'",
14
+ "test:unit": "NODE_OPTIONS=--experimental-vm-modules jest --testMatch='**/tests/unit/**/*.test.js'",
15
+ "test:coverage": "NODE_OPTIONS=--experimental-vm-modules jest --coverage"
16
+ },
17
+ "keywords": [
18
+ "chrome",
19
+ "chromium",
20
+ "version-manager",
21
+ "macos",
22
+ "arm",
23
+ "cli"
24
+ ],
25
+ "author": "",
26
+ "license": "MIT",
27
+ "engines": {
28
+ "node": ">=18.0.0"
29
+ },
30
+ "dependencies": {
31
+ "chalk": "^5.3.0",
32
+ "commander": "^11.1.0",
33
+ "ora": "^7.0.1",
34
+ "cli-progress": "^3.12.0",
35
+ "proper-lockfile": "^4.1.2"
36
+ },
37
+ "devDependencies": {
38
+ "@jest/globals": "^29.7.0",
39
+ "jest": "^29.7.0"
40
+ }
41
+ }
42
+
43
+
package/src/cli.js ADDED
@@ -0,0 +1,408 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * CHVM - Chrome Version Manager
5
+ * Entry point for CLI
6
+ */
7
+
8
+ import { Command } from 'commander';
9
+ import chalk from 'chalk';
10
+ import { checkPlatform } from './lib/platform-check.js';
11
+ import { getChvmHome, ensureChvmDir, readAvailableVersions, writeAvailableVersions, readInstalledVersions, addInstalledVersion, removeInstalledVersion } from './lib/storage.js';
12
+ import { createLogger } from './lib/logger.js';
13
+ import { fetchRevisions, fetchVersionMapping, mergeRevisionsWithVersions, resolveVersion, buildAvailableVersions } from './lib/mapping.js';
14
+ import { getDownloadUrl, fetchRevisionMetadata, downloadWithProgress } from './lib/downloader.js';
15
+ import { atomicInstall, extractZip, verifyAppBundle, calculateDirectorySize } from './lib/installer.js';
16
+ import { withLock } from './lib/lock.js';
17
+ import ora from 'ora';
18
+ import { exec } from 'child_process';
19
+ import { promisify } from 'util';
20
+ import fs from 'fs/promises';
21
+ import { existsSync } from 'fs';
22
+ import { join } from 'path';
23
+
24
+ const execAsync = promisify(exec);
25
+
26
+ const program = new Command();
27
+
28
+ program
29
+ .name('chvm')
30
+ .description('Chrome Version Manager - Manage multiple Chromium versions on macOS ARM')
31
+ .version('1.0.0');
32
+
33
+ // Help command (default)
34
+ program
35
+ .command('help', { isDefault: false })
36
+ .description('Show help information')
37
+ .action(() => {
38
+ program.outputHelp();
39
+ });
40
+
41
+ // ls command
42
+ program
43
+ .command('ls')
44
+ .description('List available and installed Chromium versions')
45
+ .option('--json', 'Output in JSON format')
46
+ .action(async (options) => {
47
+ try {
48
+ checkPlatform();
49
+ const chvmHome = getChvmHome();
50
+ await ensureChvmDir(chvmHome);
51
+
52
+ const available = await readAvailableVersions(chvmHome);
53
+ const installed = await readInstalledVersions(chvmHome);
54
+
55
+ if (options.json) {
56
+ console.log(JSON.stringify({ available, installed }, null, 2));
57
+ } else {
58
+ if (available.length === 0) {
59
+ console.log(chalk.yellow('No versions available. Run "chvm update" first.'));
60
+ return;
61
+ }
62
+
63
+ console.log(chalk.bold('\nAvailable Chromium Versions:\n'));
64
+ console.log(chalk.gray('VERSION\tREVISION\tCHANNEL\tSTATUS'));
65
+ console.log(chalk.gray('─'.repeat(60)));
66
+
67
+ const printedMajors = new Set();
68
+ for (const item of available) {
69
+ if(!item.version){
70
+ continue
71
+ }
72
+ const major = item.version.split('.')[0];
73
+ if(printedMajors.has(major)){
74
+ continue
75
+ }
76
+ printedMajors.add(major);
77
+
78
+ const displayVersion = item.version || chalk.gray(`[${item.revision}]`);
79
+ // Check both version and revision for installed status
80
+ const installKey = item.version || item.revision;
81
+ const isInstalled = installed[installKey];
82
+ const status = isInstalled ? chalk.green('* installed') : '';
83
+ console.log(`${displayVersion}\t${item.revision}\t${item.channel}\t${status}`);
84
+ }
85
+ console.log();
86
+ }
87
+ } catch (error) {
88
+ console.error(chalk.red(`Error: ${error.message}`));
89
+ process.exit(1);
90
+ }
91
+ });
92
+
93
+ // update command
94
+ program
95
+ .command('update')
96
+ .description('Update the list of available Chromium versions')
97
+ .option('--force', 'Force update, bypass cache')
98
+ .action(async (options) => {
99
+ try {
100
+ checkPlatform();
101
+ const chvmHome = getChvmHome();
102
+ await ensureChvmDir(chvmHome);
103
+
104
+ const logger = createLogger({ chvmHome, level: 'info' });
105
+ const spinner = ora('Fetching available Chromium versions...').start();
106
+
107
+ try {
108
+ const available = await buildAvailableVersions();
109
+
110
+ if (available.length === 0) {
111
+ spinner.warn(chalk.yellow('No versions found with matching revisions. Try again later.'));
112
+ } else {
113
+ await writeAvailableVersions(chvmHome, available);
114
+ spinner.succeed(chalk.green(`Updated! ${available.length} versions available.`));
115
+ }
116
+ } catch (error) {
117
+ spinner.fail(chalk.red(`Failed to update: ${error.message}`));
118
+ throw error;
119
+ }
120
+ } catch (error) {
121
+ console.error(chalk.red(`Error: ${error.message}`));
122
+ process.exit(1);
123
+ }
124
+ });
125
+
126
+ // install command
127
+ program
128
+ .command('install <version>')
129
+ .alias('i')
130
+ .description('Install a specific Chromium version')
131
+ .option('--no-cache', 'Skip cache and download fresh')
132
+ .option('--quiet', 'Minimal output')
133
+ .action(async (version, options) => {
134
+ try {
135
+ checkPlatform();
136
+ const chvmHome = getChvmHome();
137
+ await ensureChvmDir(chvmHome);
138
+
139
+ const logger = createLogger({ chvmHome, level: options.quiet ? 'error' : 'info' });
140
+
141
+ await withLock(chvmHome, async () => {
142
+ const available = await readAvailableVersions(chvmHome);
143
+
144
+ if (available.length === 0) {
145
+ throw new Error('No versions available. Please run "chvm update" first.');
146
+ }
147
+
148
+ const resolved = resolveVersion(version, available);
149
+
150
+ if (!resolved) {
151
+ throw new Error(`Version "${version}" not found. Run "chvm ls" to see available versions.`);
152
+ }
153
+
154
+ const displayVersion = resolved.version || `Revision ${resolved.revision}`;
155
+ console.log(chalk.blue(`Resolving '${version}' -> ${displayVersion} (revision: ${resolved.revision})`));
156
+
157
+ // Check if already installed
158
+ const installed = await readInstalledVersions(chvmHome);
159
+ const installKey = resolved.version || resolved.revision;
160
+ if (installed[installKey]) {
161
+ console.log(chalk.yellow(`Version ${displayVersion} is already installed.`));
162
+ return;
163
+ }
164
+
165
+ const spinner = ora('Fetching revision metadata...').start();
166
+
167
+ const metadata = await fetchRevisionMetadata(resolved.revision);
168
+ const chromeMacZip = metadata.items.find(item => item.name.includes('chrome-mac.zip'));
169
+
170
+
171
+ if (!chromeMacZip) {
172
+ throw new Error('chrome-mac.zip not found in revision');
173
+ }
174
+
175
+ spinner.text = `Downloading Chromium ${displayVersion}...`;
176
+
177
+ const tmpZip = join(chvmHome, 'tmp', `chrome-${resolved.revision}.zip`);
178
+ await fs.mkdir(join(chvmHome, 'tmp'), { recursive: true });
179
+
180
+ await downloadWithProgress(chromeMacZip.mediaLink, tmpZip, (progress) => {
181
+ spinner.text = `Downloading: ${progress.percentage}% (${Math.round(progress.downloaded / 1024 / 1024)}MB / ${Math.round(progress.total / 1024 / 1024)}MB)`;
182
+ });
183
+
184
+ spinner.text = 'Extracting...';
185
+
186
+ const finalPath = join(chvmHome, 'installs', `${installKey}.app`);
187
+
188
+ await atomicInstall(async (tmpDir) => {
189
+ const extractPath = join(tmpDir, 'extracted');
190
+
191
+ spinner.text = 'Extracting zip...';
192
+ await extractZip(tmpZip, extractPath, (progress) => {
193
+ spinner.text = `Extracting: ${progress.extractedFiles} files...`;
194
+ });
195
+
196
+ spinner.text = 'Looking for app bundle...';
197
+
198
+ // Find the .app bundle
199
+ const files = await fs.readdir(extractPath);
200
+ console.log('Extracted files:', files.slice(0, 10).join(', ')); // Debug
201
+
202
+ const appBundle = files.find(f => f.endsWith('.app'));
203
+
204
+ if (!appBundle) {
205
+ // Maybe it's in a subdirectory like chrome-mac/
206
+ const chromeMacDir = join(extractPath, 'chrome-mac');
207
+ if (existsSync(chromeMacDir)) {
208
+ const subFiles = await fs.readdir(chromeMacDir);
209
+ const subAppBundle = subFiles.find(f => f.endsWith('.app'));
210
+ if (subAppBundle) {
211
+ return join(chromeMacDir, subAppBundle);
212
+ }
213
+ }
214
+ throw new Error('App bundle not found in extracted files');
215
+ }
216
+
217
+ return join(extractPath, appBundle);
218
+ }, finalPath, chvmHome);
219
+
220
+ // Cleanup tmp zip
221
+ await fs.unlink(tmpZip).catch(() => {});
222
+
223
+ spinner.text = 'Verifying installation...';
224
+ const isValid = await verifyAppBundle(finalPath);
225
+
226
+ if (!isValid) {
227
+ throw new Error('Installation verification failed: Invalid app bundle structure');
228
+ }
229
+
230
+ const size = await calculateDirectorySize(finalPath);
231
+
232
+ await addInstalledVersion(chvmHome, {
233
+ version: installKey,
234
+ revision: resolved.revision,
235
+ path: finalPath,
236
+ size
237
+ });
238
+
239
+ spinner.succeed(chalk.green(`Installed ${displayVersion} to ${finalPath}`));
240
+ logger.info(`Installed version ${displayVersion}`);
241
+
242
+ }, { timeout: 600000 }); // 10 minute timeout
243
+
244
+ } catch (error) {
245
+ console.error(chalk.red(`Error: ${error.message}`));
246
+ process.exit(1);
247
+ }
248
+ });
249
+
250
+ // open command
251
+ program
252
+ .command('open <version>')
253
+ .description('Open a specific Chromium version')
254
+ .option('--disable-cors', 'Disable CORS (useful for development)')
255
+ .action(async (version, options) => {
256
+ try {
257
+ checkPlatform();
258
+ const chvmHome = getChvmHome();
259
+ await ensureChvmDir(chvmHome);
260
+
261
+ const installed = await readInstalledVersions(chvmHome);
262
+ const available = await readAvailableVersions(chvmHome);
263
+
264
+ let versionToOpen = null;
265
+
266
+ // Try to find in installed (check both version and revision)
267
+ if (installed[version]) {
268
+ versionToOpen = { version, ...installed[version] };
269
+ } else {
270
+ // Try to resolve and install
271
+ const resolved = resolveVersion(version, available);
272
+ if (!resolved) {
273
+ throw new Error(`Version "${version}" not found. Run "chvm ls" to see available versions.`);
274
+ }
275
+
276
+ const installKey = resolved.version || resolved.revision;
277
+ const displayVersion = resolved.version || `Revision ${resolved.revision}`;
278
+
279
+ if (!installed[installKey]) {
280
+ console.log(chalk.blue(`${displayVersion} not installed. Installing...`));
281
+ // Use revision for install if no version
282
+ await execAsync(`node ${process.argv[1]} install ${resolved.revision}`);
283
+
284
+ // Reload installed versions
285
+ const reloaded = await readInstalledVersions(chvmHome);
286
+ versionToOpen = { version: installKey, ...reloaded[installKey] };
287
+ } else {
288
+ versionToOpen = { version: installKey, ...installed[installKey] };
289
+ }
290
+ }
291
+
292
+ if (!versionToOpen) {
293
+ throw new Error('Failed to prepare version for opening');
294
+ }
295
+
296
+ if (options.disableCors) {
297
+ console.log(chalk.yellow('⚠️ WARNING: Running with --disable-web-security. This is insecure and should only be used for development.'));
298
+ }
299
+
300
+ // Prepare profile directory
301
+ const profileDir = join(chvmHome, 'profiles', versionToOpen.version);
302
+ await fs.mkdir(profileDir, { recursive: true });
303
+
304
+ // Find executable
305
+ const appPath = versionToOpen.path;
306
+ const execPath = join(appPath, 'Contents', 'MacOS', 'Chromium');
307
+
308
+ if (!existsSync(execPath)) {
309
+ throw new Error(`Chromium executable not found at ${execPath}`);
310
+ }
311
+
312
+ const args = [
313
+ `--user-data-dir=${profileDir}`
314
+ ];
315
+
316
+ if (options.disableCors) {
317
+ args.push('--disable-web-security');
318
+ args.push(`--user-data-dir=${join(chvmHome, 'tmp', versionToOpen.version)}`);
319
+ }
320
+
321
+ console.log(chalk.green(`Opening Chromium ${versionToOpen.version}...`));
322
+
323
+ // Use open command on macOS
324
+ const command = `open -a "${appPath}" --args ${args.join(' ')}`;
325
+
326
+ exec(command, (error) => {
327
+ if (error) {
328
+ console.error(chalk.red(`Failed to open: ${error.message}`));
329
+ process.exit(1);
330
+ }
331
+ });
332
+
333
+ } catch (error) {
334
+ console.error(chalk.red(`Error: ${error.message}`));
335
+ process.exit(1);
336
+ }
337
+ });
338
+
339
+ // uninstall command
340
+ program
341
+ .command('uninstall <version>')
342
+ .description('Uninstall a specific Chromium version')
343
+ .option('--force', 'Force uninstall even if running')
344
+ .action(async (version, options) => {
345
+ try {
346
+ checkPlatform();
347
+ const chvmHome = getChvmHome();
348
+ await ensureChvmDir(chvmHome);
349
+
350
+ await withLock(chvmHome, async () => {
351
+ const installed = await readInstalledVersions(chvmHome);
352
+ const available = await readAvailableVersions(chvmHome);
353
+
354
+ // Try to resolve version
355
+ let versionToUninstall = version;
356
+
357
+ if (!installed[version]) {
358
+ const resolved = resolveVersion(version, available);
359
+ if (resolved && installed[resolved.version]) {
360
+ versionToUninstall = resolved.version;
361
+ } else {
362
+ throw new Error(`Version "${version}" is not installed.`);
363
+ }
364
+ }
365
+
366
+ const versionInfo = installed[versionToUninstall];
367
+ const spinner = ora(`Uninstalling ${versionToUninstall}...`).start();
368
+
369
+ // Remove app directory
370
+ if (existsSync(versionInfo.path)) {
371
+ await fs.rm(versionInfo.path, { recursive: true, force: true });
372
+ spinner.text = 'Removed app bundle...';
373
+ }
374
+
375
+ // Remove profile directory
376
+ const profileDir = join(chvmHome, 'profiles', versionToUninstall);
377
+ if (existsSync(profileDir)) {
378
+ await fs.rm(profileDir, { recursive: true, force: true });
379
+ spinner.text = 'Removed profile...';
380
+ }
381
+
382
+ // Remove tmp directories
383
+ const tmpDir = join(chvmHome, 'tmp', versionToUninstall);
384
+ if (existsSync(tmpDir)) {
385
+ await fs.rm(tmpDir, { recursive: true, force: true });
386
+ }
387
+
388
+ // Remove from installed.json
389
+ await removeInstalledVersion(chvmHome, versionToUninstall);
390
+
391
+ spinner.succeed(chalk.green(`Uninstalled ${versionToUninstall}`));
392
+ });
393
+
394
+ } catch (error) {
395
+ console.error(chalk.red(`Error: ${error.message}`));
396
+ process.exit(1);
397
+ }
398
+ });
399
+
400
+ // Show help if no command provided
401
+ if (process.argv.length === 2) {
402
+ program.outputHelp();
403
+ process.exit(0);
404
+ }
405
+
406
+ program.parse();
407
+
408
+
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Downloader module - Streaming download with progress
3
+ */
4
+
5
+ import fs from 'fs';
6
+ import { pipeline } from 'stream/promises';
7
+ import { createWriteStream, existsSync, statSync } from 'fs';
8
+
9
+ export function getDownloadUrl(revision) {
10
+ return `https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Mac_Arm%2F${revision}%2Fchrome-mac.zip?alt=media`;
11
+ }
12
+
13
+ export async function fetchRevisionMetadata(revision) {
14
+ const url = `https://www.googleapis.com/storage/v1/b/chromium-browser-snapshots/o?delimiter=/&prefix=Mac_Arm/${revision}/&fields=items(kind,mediaLink,metadata,name,size,updated),kind,prefixes,nextPageToken`;
15
+
16
+ const response = await fetch(url);
17
+
18
+ if (!response.ok) {
19
+ throw new Error(`Failed to fetch metadata for revision ${revision}: ${response.statusText}`);
20
+ }
21
+
22
+ const data = await response.json();
23
+
24
+ if (!data.items || data.items.length === 0) {
25
+ throw new Error(`No files found for revision ${revision}`);
26
+ }
27
+
28
+ return data;
29
+ }
30
+
31
+ export async function downloadWithProgress(url, outputPath, onProgress) {
32
+ const response = await fetch(url);
33
+
34
+ if (!response.ok) {
35
+ throw new Error(`Failed to download: ${response.statusText}`);
36
+ }
37
+
38
+ const totalSize = parseInt(response.headers.get('content-length') || '0', 10);
39
+ let downloadedSize = 0;
40
+
41
+ const fileStream = createWriteStream(outputPath);
42
+
43
+ if (!response.body) {
44
+ throw new Error('Response body is null');
45
+ }
46
+
47
+ const reader = response.body.getReader();
48
+
49
+ try {
50
+ while (true) {
51
+ const { done, value } = await reader.read();
52
+
53
+ if (done) break;
54
+
55
+ fileStream.write(value);
56
+ downloadedSize += value.length;
57
+
58
+ if (onProgress && totalSize > 0) {
59
+ const progress = {
60
+ downloaded: downloadedSize,
61
+ total: totalSize,
62
+ percentage: Math.round((downloadedSize / totalSize) * 100)
63
+ };
64
+ onProgress(progress);
65
+ }
66
+ }
67
+
68
+ fileStream.end();
69
+
70
+ // Wait for file stream to finish
71
+ await new Promise((resolve, reject) => {
72
+ fileStream.on('finish', resolve);
73
+ fileStream.on('error', reject);
74
+ });
75
+
76
+ } catch (error) {
77
+ fileStream.close();
78
+ throw error;
79
+ }
80
+ }
81
+
82
+ export async function retryFetch(fetchFn, options = {}) {
83
+ const { retries = 3, delay = 1000, backoff = 2 } = options;
84
+
85
+ let lastError;
86
+
87
+ for (let attempt = 0; attempt <= retries; attempt++) {
88
+ try {
89
+ return await fetchFn();
90
+ } catch (error) {
91
+ lastError = error;
92
+
93
+ if (attempt < retries) {
94
+ const waitTime = delay * Math.pow(backoff, attempt);
95
+ await new Promise(resolve => setTimeout(resolve, waitTime));
96
+ }
97
+ }
98
+ }
99
+
100
+ throw lastError;
101
+ }
102
+
103
+ export async function streamDownload(url) {
104
+ const response = await fetch(url);
105
+
106
+ if (!response.ok) {
107
+ throw new Error(`Failed to download: ${response.statusText}`);
108
+ }
109
+
110
+ return response.body;
111
+ }
112
+
113
+ export async function validateDownload(filePath, options = {}) {
114
+ const { expectedSize } = options;
115
+
116
+ if (!existsSync(filePath)) {
117
+ throw new Error('Downloaded file does not exist');
118
+ }
119
+
120
+ const stats = statSync(filePath);
121
+
122
+ if (expectedSize && stats.size !== expectedSize) {
123
+ throw new Error(`File size mismatch: expected ${expectedSize}, got ${stats.size}`);
124
+ }
125
+
126
+ return {
127
+ valid: true,
128
+ size: stats.size
129
+ };
130
+ }
131
+
132
+