@myrialabs/clopen 0.3.20 → 0.3.22

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.
Files changed (40) hide show
  1. package/backend/engine/adapters/claude/environment.ts +0 -17
  2. package/backend/engine/adapters/claude/error-handler.ts +0 -4
  3. package/backend/engine/adapters/claude/models.ts +43 -0
  4. package/backend/engine/install-recipes.ts +69 -117
  5. package/backend/engine/version-check.ts +145 -0
  6. package/backend/files/file-operations.test.ts +75 -0
  7. package/backend/files/file-operations.ts +10 -56
  8. package/backend/files/image-processing.test.ts +52 -0
  9. package/backend/files/image-processing.ts +11 -1
  10. package/backend/files/path-browsing.ts +141 -139
  11. package/backend/git/git-parser.ts +11 -0
  12. package/backend/git/git-service.ts +65 -9
  13. package/backend/http/files-upload.test.ts +174 -0
  14. package/backend/http/files-upload.ts +27 -7
  15. package/backend/http/upload-temp-cleanup.ts +53 -0
  16. package/backend/index.ts +31 -12
  17. package/backend/mcp/remote-server.test.ts +150 -0
  18. package/backend/mcp/remote-server.ts +68 -0
  19. package/backend/terminal/pty-session-manager.ts +18 -11
  20. package/backend/ws/chat/stream.ts +17 -6
  21. package/backend/ws/files/index.ts +5 -0
  22. package/backend/ws/files/reveal.ts +61 -0
  23. package/backend/ws/files/search.test.ts +115 -0
  24. package/backend/ws/files/search.ts +77 -26
  25. package/backend/ws/files/write.ts +3 -1
  26. package/backend/ws/git/branch-name.ts +170 -0
  27. package/backend/ws/git/branch.ts +15 -2
  28. package/backend/ws/git/commit-message.ts +8 -2
  29. package/backend/ws/git/index.ts +3 -1
  30. package/backend/ws/system-tools/status.ts +14 -0
  31. package/backend/ws/user/crud.ts +8 -4
  32. package/dist/assets/main-Ba19ADkk.js +377 -0
  33. package/dist/assets/main-CwCZzMVm.css +1 -0
  34. package/dist/index.html +2 -2
  35. package/package.json +3 -1
  36. package/shared/constants/git.ts +5 -0
  37. package/shared/types/git.ts +13 -0
  38. package/shared/types/stores/settings.ts +17 -0
  39. package/dist/assets/main-72Z_L-nD.js +0 -362
  40. package/dist/assets/main-ClADBkFf.css +0 -1
@@ -8,7 +8,6 @@
8
8
  */
9
9
 
10
10
  import { join } from 'path';
11
- import { isWindows, findGitBash } from '../../../terminal/shell-utils.js';
12
11
  import { engineQueries } from '../../../database/queries';
13
12
  import { debug } from '$shared/utils/logger';
14
13
  import { getCleanSpawnEnv, getClopenDir } from '../../../utils/index.js';
@@ -104,22 +103,6 @@ async function _doSetup(): Promise<void> {
104
103
  debug.warn('engine', '⚠️ Claude Code: Could not read active account (DB may not be ready)');
105
104
  }
106
105
 
107
- // Setup Git Bash on Windows
108
- if (isWindows) {
109
- const existingPath = process.env.CLAUDE_CODE_GIT_BASH_PATH;
110
- if (existingPath) {
111
- overrides['CLAUDE_CODE_GIT_BASH_PATH'] = existingPath;
112
- } else {
113
- const gitBashPath = await findGitBash();
114
- if (gitBashPath) {
115
- overrides['CLAUDE_CODE_GIT_BASH_PATH'] = gitBashPath;
116
- debug.log('engine', '✅ Claude Code: Git Bash configured at:', gitBashPath);
117
- } else {
118
- debug.warn('engine', '⚠️ Claude Code: Git Bash not found - may have limited functionality on Windows');
119
- }
120
- }
121
- }
122
-
123
106
  // Terminal environment variables
124
107
  overrides['FORCE_COLOR'] = '1';
125
108
  overrides['COLORTERM'] = 'truecolor';
@@ -17,10 +17,6 @@ export function handleStreamError(error: unknown): void {
17
17
  throw new Error('Unexpected conversation limit reached. This should not happen with unlimited turns enabled.');
18
18
  }
19
19
 
20
- if (error.message.includes('git-bash') || error.message.includes('requires git-bash')) {
21
- throw new Error('Claude Code requires git-bash on Windows. Please ensure Git is installed and accessible.');
22
- }
23
-
24
20
  if (error.message.includes('ENOENT') || error.message.includes('spawn claude-code')) {
25
21
  throw new Error('Claude Agent SDK not found. Please install it with: npm install @anthropic-ai/claude-agent-sdk');
26
22
  }
@@ -9,6 +9,49 @@
9
9
  import type { EngineModel } from '$shared/types/unified';
10
10
 
11
11
  export const CLAUDE_CODE_MODELS: EngineModel[] = [
12
+ {
13
+ engine: {
14
+ type: 'claude-code',
15
+ provider: 'anthropic',
16
+ model: {
17
+ id: 'claude-fable-5',
18
+ name: 'Claude Fable 5',
19
+ },
20
+ account: {
21
+ id: 0,
22
+ name: '',
23
+ },
24
+ },
25
+ limit: {
26
+ input: 1_000_000,
27
+ output: 128_000,
28
+ },
29
+ modalities: {
30
+ input: {
31
+ text: true,
32
+ image: true,
33
+ audio: false,
34
+ video: false,
35
+ pdf: true,
36
+ },
37
+ output: {
38
+ text: true,
39
+ image: false,
40
+ audio: false,
41
+ video: false,
42
+ pdf: false,
43
+ },
44
+ },
45
+ capabilities: {
46
+ reasoning: true,
47
+ tools: true,
48
+ structuredOutput: true,
49
+ },
50
+ cost: {
51
+ input: 10,
52
+ output: 50,
53
+ },
54
+ },
12
55
  {
13
56
  engine: {
14
57
  type: 'claude-code',
@@ -108,8 +108,6 @@ function detectMacPkgMgr(): 'brew' | null {
108
108
  * Google Chrome via the distro package manager and skip this scan.
109
109
  */
110
110
  export function resolveClopenChromePath(): string | null {
111
- if (process.platform !== 'darwin' && process.platform !== 'win32') return null;
112
-
113
111
  const cacheDir = join(getClopenDir(), 'bin', 'chrome');
114
112
  if (!existsSync(cacheDir)) return null;
115
113
 
@@ -127,12 +125,18 @@ export function resolveClopenChromePath(): string | null {
127
125
  );
128
126
  if (existsSync(candidate)) return candidate;
129
127
  }
130
- } else {
128
+ } else if (process.platform === 'win32') {
131
129
  const winDirs = ['chrome-win64', 'chrome-win'];
132
130
  for (const dir of winDirs) {
133
131
  const candidate = join(buildDir, dir, 'chrome.exe');
134
132
  if (existsSync(candidate)) return candidate;
135
133
  }
134
+ } else {
135
+ const linuxDirs = ['chrome-linux64', 'chrome-linux'];
136
+ for (const dir of linuxDirs) {
137
+ const candidate = join(buildDir, dir, 'chrome');
138
+ if (existsSync(candidate)) return candidate;
139
+ }
136
140
  }
137
141
  }
138
142
  } catch {
@@ -339,64 +343,33 @@ function attachCurlRequirement(base: Recipe, toolLabel: string): boolean {
339
343
  }
340
344
 
341
345
  async function resolveClaudeRecipe(): Promise<Recipe> {
342
- const base: Recipe = {
346
+ return {
343
347
  tool: 'claude',
344
- autoInstallable: false,
348
+ autoInstallable: true,
345
349
  missingPrereqs: [],
346
- manualInstructions: []
350
+ manualInstructions: [{
351
+ label: 'bun',
352
+ command: 'bun add -g @anthropic-ai/claude-code',
353
+ docs: 'https://code.claude.com/docs/en/setup'
354
+ }],
355
+ command: ['bun', 'add', '-g', '@anthropic-ai/claude-code'],
356
+ displayCommand: 'bun add -g @anthropic-ai/claude-code'
347
357
  };
348
-
349
- if (process.platform === 'win32') {
350
- base.autoInstallable = true;
351
- base.shell = { program: 'powershell.exe', args: ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command'] };
352
- base.command = ['irm https://claude.ai/install.ps1 | iex'];
353
- base.displayCommand = 'irm https://claude.ai/install.ps1 | iex';
354
- base.manualInstructions.push({
355
- label: 'PowerShell',
356
- command: 'irm https://claude.ai/install.ps1 | iex',
357
- docs: 'https://docs.claude.com/en/docs/claude-code/overview'
358
- });
359
- return base;
360
- }
361
-
362
- // macOS / Linux
363
- base.manualInstructions.push({
364
- label: 'curl + bash',
365
- command: 'curl -fsSL https://claude.ai/install.sh | bash',
366
- docs: 'https://docs.claude.com/en/docs/claude-code/overview'
367
- });
368
- if (!attachCurlRequirement(base, 'Claude Code')) return base;
369
-
370
- base.autoInstallable = true;
371
- base.shell = { program: 'bash', args: ['-c'] };
372
- base.command = ['curl -fsSL https://claude.ai/install.sh | bash'];
373
- base.displayCommand = 'curl -fsSL https://claude.ai/install.sh | bash';
374
- return base;
375
358
  }
376
359
 
377
360
  async function resolveOpenCodeRecipe(): Promise<Recipe> {
378
361
  const base: Recipe = {
379
362
  tool: 'opencode',
380
- autoInstallable: false,
363
+ autoInstallable: true,
381
364
  missingPrereqs: [],
382
365
  manualInstructions: [{
383
- label: 'curl + bash',
384
- command: 'curl -fsSL https://opencode.ai/install | bash',
385
- docs: 'https://opencode.ai'
386
- }]
366
+ label: 'bun',
367
+ command: 'bun add -g opencode-ai',
368
+ docs: 'https://opencode.ai/docs'
369
+ }],
370
+ command: ['bun', 'add', '-g', 'opencode-ai'],
371
+ displayCommand: 'bun add -g opencode-ai'
387
372
  };
388
-
389
- if (process.platform === 'win32') {
390
- base.unavailableReason = 'OpenCode install script is not available on Windows via PowerShell. Use WSL or the manual instructions.';
391
- return base;
392
- }
393
-
394
- if (!attachCurlRequirement(base, 'OpenCode')) return base;
395
-
396
- base.autoInstallable = true;
397
- base.shell = { program: 'bash', args: ['-c'] };
398
- base.command = ['curl -fsSL https://opencode.ai/install | bash'];
399
- base.displayCommand = 'curl -fsSL https://opencode.ai/install | bash';
400
373
  return base;
401
374
  }
402
375
 
@@ -417,60 +390,30 @@ async function resolveCopilotRecipe(): Promise<Recipe> {
417
390
  }
418
391
 
419
392
  async function resolveQwenRecipe(): Promise<Recipe> {
420
- const manualInstructions: ManualInstruction[] = [{
421
- label: 'bun',
422
- command: 'bun add -g @qwen-code/qwen-code',
423
- docs: 'https://github.com/QwenLM/qwen-code'
424
- }];
425
-
426
- // Qwen Code CLI ships bundled with `@qwen-code/sdk` from v0.1.1+ so the
427
- // SDK path doesn't need a standalone install. We still expose this recipe
428
- // for users who prefer the standalone CLI for `qwen-oauth` / shell use.
429
- if (!resolveBinary('bun')) {
430
- return {
431
- tool: 'qwen',
432
- autoInstallable: false,
433
- unavailableReason: 'Bun is required to install the Qwen Code CLI. Install Bun first (https://bun.sh).',
434
- missingPrereqs: [],
435
- manualInstructions
436
- };
437
- }
438
-
439
393
  return {
440
394
  tool: 'qwen',
441
395
  autoInstallable: true,
442
396
  missingPrereqs: [],
443
- manualInstructions,
397
+ manualInstructions: [{
398
+ label: 'bun',
399
+ command: 'bun add -g @qwen-code/qwen-code',
400
+ docs: 'https://qwen.ai/qwencode'
401
+ }],
444
402
  command: ['bun', 'add', '-g', '@qwen-code/qwen-code'],
445
403
  displayCommand: 'bun add -g @qwen-code/qwen-code'
446
404
  };
447
405
  }
448
406
 
449
407
  async function resolveCodexRecipe(): Promise<Recipe> {
450
- const manualInstructions: ManualInstruction[] = [{
451
- label: 'bun',
452
- command: 'bun add -g @openai/codex',
453
- docs: 'https://developers.openai.com/codex'
454
- }];
455
-
456
- // Codex CLI is installed via `bun add -g`. Bun must be on PATH for the
457
- // auto-installer to work; otherwise we fall back to the manual instructions
458
- // (the user installs Bun first via the existing Bun recipe / website).
459
- if (!resolveBinary('bun')) {
460
- return {
461
- tool: 'codex',
462
- autoInstallable: false,
463
- unavailableReason: 'Bun is required to install the Codex CLI. Install Bun first (https://bun.sh).',
464
- missingPrereqs: [],
465
- manualInstructions
466
- };
467
- }
468
-
469
408
  return {
470
409
  tool: 'codex',
471
410
  autoInstallable: true,
472
411
  missingPrereqs: [],
473
- manualInstructions,
412
+ manualInstructions: [{
413
+ label: 'bun',
414
+ command: 'bun add -g @openai/codex',
415
+ docs: 'https://developers.openai.com/codex/quickstart'
416
+ }],
474
417
  command: ['bun', 'add', '-g', '@openai/codex'],
475
418
  displayCommand: 'bun add -g @openai/codex'
476
419
  };
@@ -530,6 +473,9 @@ interface LinuxChromeStrategy {
530
473
  async function resolveLinuxChromeRecipe(): Promise<Recipe> {
531
474
  const mgr = detectLinuxPkgMgr();
532
475
  const arch = process.arch;
476
+ const cacheDir = join(getClopenDir(), 'bin');
477
+ const pptrArgs = ['bun', 'x', '@puppeteer/browsers', 'install', 'chrome@stable', '--path', cacheDir];
478
+ const pptrDisplay = `bun x @puppeteer/browsers install chrome@stable --path "${cacheDir}"`;
533
479
 
534
480
  const manual: ManualInstruction[] = [];
535
481
  const strategy = pickLinuxChromeStrategy(mgr, arch);
@@ -541,37 +487,43 @@ async function resolveLinuxChromeRecipe(): Promise<Recipe> {
541
487
  docs: CHROME_LINUX_DOCS
542
488
  });
543
489
  }
490
+ manual.push({
491
+ label: 'Puppeteer browsers CLI',
492
+ command: pptrDisplay,
493
+ docs: PPTR_CHROME_DOCS
494
+ });
544
495
 
545
- const base: Recipe = {
496
+ // Try Google Chrome via system package manager (x64, apt/dnf/zypper, requires root).
497
+ if (strategy) {
498
+ const elevated = await isElevated();
499
+ if (elevated) {
500
+ const base: Recipe = {
501
+ tool: 'chrome',
502
+ autoInstallable: false,
503
+ missingPrereqs: [],
504
+ manualInstructions: manual
505
+ };
506
+ if (!strategy.requiresCurl || attachCurlRequirement(base, 'Google Chrome')) {
507
+ base.autoInstallable = true;
508
+ base.shell = { program: 'sh', args: ['-c'] };
509
+ base.command = [strategy.installCommand];
510
+ base.displayCommand = strategy.manualCommand;
511
+ if (strategy.env) base.env = strategy.env;
512
+ return base;
513
+ }
514
+ // curl unavailable for system install — fall through to puppeteer
515
+ }
516
+ }
517
+
518
+ // Fallback: puppeteer Chrome for Testing (no root needed, all distros and arm64).
519
+ return {
546
520
  tool: 'chrome',
547
- autoInstallable: false,
521
+ autoInstallable: true,
548
522
  missingPrereqs: [],
549
- manualInstructions: manual
523
+ manualInstructions: manual,
524
+ command: pptrArgs,
525
+ displayCommand: pptrDisplay
550
526
  };
551
-
552
- if (!strategy) {
553
- base.unavailableReason = arch !== 'x64'
554
- ? `Google Chrome is only published for Linux x86_64. No Chrome build exists for ${arch}. Download Chrome manually from google.com/chrome.`
555
- : `Google Chrome is only available via apt, dnf, or zypper on Linux${mgr ? ` (this system uses ${mgr})` : ' — no supported package manager was detected'}. Download Chrome manually from google.com/chrome.`;
556
- return base;
557
- }
558
-
559
- if (strategy.requiresCurl && !attachCurlRequirement(base, 'Google Chrome')) {
560
- return base;
561
- }
562
-
563
- const elevated = await isElevated();
564
- if (!elevated) {
565
- base.unavailableReason = `Installing Google Chrome via ${strategy.pkgMgrLabel} requires root. Run clopen as root, or install Chrome manually with the command below and retry.`;
566
- return base;
567
- }
568
-
569
- base.autoInstallable = true;
570
- base.shell = { program: 'sh', args: ['-c'] };
571
- base.command = [strategy.installCommand];
572
- base.displayCommand = strategy.manualCommand;
573
- if (strategy.env) base.env = strategy.env;
574
- return base;
575
527
  }
576
528
 
577
529
  function pickLinuxChromeStrategy(
@@ -0,0 +1,145 @@
1
+ import type { ToolId } from './install-recipes';
2
+
3
+ export interface UpdateCheckResult {
4
+ latestVersion: string | null;
5
+ /** true = newer available, false = already latest, null = could not determine */
6
+ hasUpdate: boolean | null;
7
+ }
8
+
9
+ type VersionSource =
10
+ | { type: 'npm'; pkg: string }
11
+ | { type: 'homebrew-formula'; formula: string }
12
+ | { type: 'github-release'; repo: string }
13
+ | { type: 'chrome-for-testing' };
14
+
15
+ const SOURCES: Record<ToolId, VersionSource> = {
16
+ claude: { type: 'npm', pkg: '@anthropic-ai/claude-code' },
17
+ opencode: { type: 'npm', pkg: 'opencode-ai' },
18
+ copilot: { type: 'npm', pkg: '@github/copilot' },
19
+ codex: { type: 'npm', pkg: '@openai/codex' },
20
+ qwen: { type: 'npm', pkg: '@qwen-code/qwen-code' },
21
+ git: { type: 'homebrew-formula', formula: 'git' },
22
+ chrome: { type: 'chrome-for-testing' },
23
+ };
24
+
25
+ // ─── version helpers ──────────────────────────────────────────────────────────
26
+
27
+ function extractVersion(str: string): string | null {
28
+ const m = str.match(/(\d+(?:\.\d+)+)/);
29
+ return m ? m[1] : null;
30
+ }
31
+
32
+ function versionGt(a: string, b: string): boolean {
33
+ const av = a.split('.').map(Number);
34
+ const bv = b.split('.').map(Number);
35
+ const len = Math.max(av.length, bv.length);
36
+ for (let i = 0; i < len; i++) {
37
+ if ((av[i] ?? 0) > (bv[i] ?? 0)) return true;
38
+ if ((av[i] ?? 0) < (bv[i] ?? 0)) return false;
39
+ }
40
+ return false;
41
+ }
42
+
43
+ // ─── fetchers ─────────────────────────────────────────────────────────────────
44
+
45
+ async function fetchNpmLatest(pkg: string): Promise<string | null> {
46
+ try {
47
+ const res = await fetch(`https://registry.npmjs.org/${encodeURIComponent(pkg)}/latest`, {
48
+ headers: { Accept: 'application/json' },
49
+ signal: AbortSignal.timeout(10_000)
50
+ });
51
+ if (!res.ok) return null;
52
+ const json = await res.json() as { version?: unknown };
53
+ return typeof json.version === 'string' ? json.version : null;
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Homebrew formula API — no auth, no rate limit, tracks upstream releases
61
+ * tightly. Used as the primary source for git since the GitHub API has a
62
+ * low unauthenticated rate limit.
63
+ */
64
+ async function fetchHomebrewLatest(formula: string): Promise<string | null> {
65
+ try {
66
+ const res = await fetch(`https://formulae.brew.sh/api/formula/${encodeURIComponent(formula)}.json`, {
67
+ headers: { Accept: 'application/json' },
68
+ signal: AbortSignal.timeout(10_000)
69
+ });
70
+ if (!res.ok) return null;
71
+ const json = await res.json() as { versions?: { stable?: unknown } };
72
+ const v = json.versions?.stable;
73
+ return typeof v === 'string' ? v : null;
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+
79
+ async function fetchGitHubLatest(repo: string): Promise<string | null> {
80
+ try {
81
+ const res = await fetch(`https://api.github.com/repos/${repo}/releases/latest`, {
82
+ headers: {
83
+ Accept: 'application/vnd.github+json',
84
+ 'X-GitHub-Api-Version': '2022-11-28',
85
+ 'User-Agent': 'clopen-version-checker'
86
+ },
87
+ signal: AbortSignal.timeout(10_000)
88
+ });
89
+ if (!res.ok) return null;
90
+ const json = await res.json() as { tag_name?: unknown };
91
+ const tag = json.tag_name;
92
+ if (typeof tag !== 'string') return null;
93
+ return tag.startsWith('v') ? tag.slice(1) : tag;
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+
99
+ async function fetchChromeLatest(): Promise<string | null> {
100
+ try {
101
+ const res = await fetch(
102
+ 'https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions.json',
103
+ { signal: AbortSignal.timeout(10_000) }
104
+ );
105
+ if (!res.ok) return null;
106
+ const json = await res.json() as { channels?: { Stable?: { version?: unknown } } };
107
+ const v = json.channels?.Stable?.version;
108
+ return typeof v === 'string' ? v : null;
109
+ } catch {
110
+ return null;
111
+ }
112
+ }
113
+
114
+ // ─── public API ───────────────────────────────────────────────────────────────
115
+
116
+ export async function checkToolUpdate(
117
+ tool: ToolId,
118
+ installedVersion: string | null
119
+ ): Promise<UpdateCheckResult> {
120
+ const source = SOURCES[tool];
121
+
122
+ let latestVersion: string | null;
123
+ switch (source.type) {
124
+ case 'npm':
125
+ latestVersion = await fetchNpmLatest(source.pkg);
126
+ break;
127
+ case 'homebrew-formula':
128
+ latestVersion = await fetchHomebrewLatest(source.formula);
129
+ break;
130
+ case 'github-release':
131
+ latestVersion = await fetchGitHubLatest(source.repo);
132
+ break;
133
+ case 'chrome-for-testing':
134
+ latestVersion = await fetchChromeLatest();
135
+ break;
136
+ }
137
+
138
+ if (!latestVersion) return { latestVersion: null, hasUpdate: null };
139
+ if (!installedVersion) return { latestVersion, hasUpdate: null };
140
+
141
+ const current = extractVersion(installedVersion);
142
+ if (!current) return { latestVersion, hasUpdate: null };
143
+
144
+ return { latestVersion, hasUpdate: versionGt(latestVersion, current) };
145
+ }
@@ -0,0 +1,75 @@
1
+ import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
2
+ import { rm, mkdir, stat } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { tmpdir } from 'node:os';
5
+
6
+ // Stub settingsQueries so the module under test never touches a real database.
7
+ await mock.module('../database/queries', () => ({
8
+ settingsQueries: {
9
+ get: () => null,
10
+ getAll: () => [],
11
+ set: () => {},
12
+ delete: () => {}
13
+ }
14
+ }));
15
+
16
+ const { deleteOperation, renameOperation, createDirectoryOperation } = await import('./file-operations');
17
+
18
+ // Shell-special name that would break cmd /c or rm -f via argument injection.
19
+ const SPECIAL_NAME = 'foo & bar.txt';
20
+
21
+ describe('file-operations — shell-special filenames', () => {
22
+ let testDir: string;
23
+
24
+ beforeEach(async () => {
25
+ testDir = join(tmpdir(), `clopen-file-ops-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
26
+ await mkdir(testDir, { recursive: true });
27
+ });
28
+
29
+ afterEach(async () => {
30
+ await rm(testDir, { recursive: true, force: true });
31
+ });
32
+
33
+ test('deleteOperation removes a file whose name contains shell metacharacters', async () => {
34
+ const filePath = join(testDir, SPECIAL_NAME);
35
+ await Bun.write(filePath, 'contents');
36
+
37
+ await expect(deleteOperation(filePath)).resolves.toMatchObject({ message: 'File deleted successfully' });
38
+ await expect(stat(filePath)).rejects.toThrow();
39
+ });
40
+
41
+ test('deleteOperation removes an empty directory', async () => {
42
+ const dirPath = join(testDir, 'empty-dir');
43
+ await mkdir(dirPath, { recursive: true });
44
+
45
+ await expect(deleteOperation(dirPath)).resolves.toMatchObject({ message: 'Directory deleted successfully' });
46
+ await expect(stat(dirPath)).rejects.toThrow();
47
+ });
48
+
49
+ test('deleteOperation force-removes a non-empty directory', async () => {
50
+ const dirPath = join(testDir, 'non-empty-dir');
51
+ await mkdir(dirPath, { recursive: true });
52
+ await Bun.write(join(dirPath, 'child.txt'), 'contents');
53
+
54
+ await expect(deleteOperation(dirPath, true)).resolves.toMatchObject({ message: 'Directory deleted successfully' });
55
+ await expect(stat(dirPath)).rejects.toThrow();
56
+ });
57
+
58
+ test('renameOperation renames a file whose name contains shell metacharacters', async () => {
59
+ const src = join(testDir, SPECIAL_NAME);
60
+ const dest = join(testDir, 'safe-name.txt');
61
+ await Bun.write(src, 'contents');
62
+
63
+ await expect(renameOperation(src, dest)).resolves.toMatchObject({ message: 'File/directory renamed successfully' });
64
+ await expect(stat(dest)).resolves.toBeTruthy();
65
+ await expect(stat(src)).rejects.toThrow();
66
+ });
67
+
68
+ test('createDirectoryOperation creates a directory whose name contains shell metacharacters', async () => {
69
+ const dirPath = join(testDir, 'dir & name');
70
+
71
+ await expect(createDirectoryOperation(dirPath)).resolves.toMatchObject({ message: 'Directory created successfully' });
72
+ const s = await stat(dirPath);
73
+ expect(s.isDirectory()).toBe(true);
74
+ });
75
+ });
@@ -1,46 +1,18 @@
1
1
  import { dirname, extname, join } from 'path';
2
- import { stat as fsStat } from 'node:fs/promises';
2
+ import { mkdir as fsMkdir, readdir as fsReaddir, rename as fsRename, rmdir as fsRmdir, stat as fsStat, unlink as fsUnlink, rm as fsRm } from 'node:fs/promises';
3
3
 
4
4
  import { debug } from '$shared/utils/logger';
5
5
  import { validateFileSize } from './file-size-limit';
6
6
 
7
- // Import Bun native functions and create wrappers for better API compatibility
8
- const { spawn } = Bun;
9
-
10
- // Bun-compatible readdir implementation (cross-platform)
7
+ // Cross-platform readdir using fs.promises
11
8
  async function readdir(path: string): Promise<string[]> {
12
- let proc;
13
- if (process.platform === 'win32') {
14
- proc = Bun.spawn(['cmd', '/c', 'dir', '/b', '/a', path], { stdout: 'pipe', stderr: 'ignore' });
15
- } else {
16
- proc = Bun.spawn(['ls', '-1A', path], { stdout: 'pipe', stderr: 'ignore' });
17
- }
18
- const result = await new Response(proc.stdout).text();
19
- // Split and clean up, removing \r characters for Windows compatibility
20
- return result.trim().split(/\r?\n/).map(line => line.trim()).filter(Boolean);
9
+ const entries = await fsReaddir(path, { withFileTypes: true });
10
+ return entries.map(e => e.name);
21
11
  }
22
12
 
23
13
  async function mkdir(path: string, options?: { recursive?: boolean }) {
24
- // Pure Bun approach: create directory by writing a temp file
25
14
  try {
26
- const tempFile = join(path, '.bun_mkdir_temp');
27
- await Bun.write(tempFile, '');
28
- // Clean up the temp file
29
- try {
30
- if (process.platform === 'win32') {
31
- await spawn(['cmd', '/c', 'del', '/f', '/q', tempFile.replace(/\//g, '\\')], {
32
- stdout: 'ignore',
33
- stderr: 'ignore'
34
- }).exited;
35
- } else {
36
- await spawn(['rm', '-f', tempFile], {
37
- stdout: 'ignore',
38
- stderr: 'ignore'
39
- }).exited;
40
- }
41
- } catch {
42
- // Ignore cleanup errors
43
- }
15
+ await fsMkdir(path, { recursive: options?.recursive ?? false });
44
16
  } catch (error) {
45
17
  throw new Error(`Failed to create directory ${path}: ${error}`);
46
18
  }
@@ -79,37 +51,19 @@ async function copyDirectory(src: string, dest: string) {
79
51
  }
80
52
 
81
53
  async function rename(oldPath: string, newPath: string) {
82
- if (process.platform === 'win32') {
83
- const proc = spawn(['cmd', '/c', 'move', oldPath.replace(/\//g, '\\'), newPath.replace(/\//g, '\\')], { stdout: 'ignore', stderr: 'ignore' });
84
- await proc.exited;
85
- } else {
86
- const proc = spawn(['mv', oldPath, newPath], { stdout: 'ignore', stderr: 'ignore' });
87
- await proc.exited;
88
- }
54
+ await fsRename(oldPath, newPath);
89
55
  }
90
56
 
91
57
  async function unlink(path: string) {
92
- if (process.platform === 'win32') {
93
- const proc = spawn(['cmd', '/c', 'del', '/f', '/q', path.replace(/\//g, '\\')], { stdout: 'ignore', stderr: 'ignore' });
94
- await proc.exited;
95
- } else {
96
- const proc = spawn(['rm', '-f', path], { stdout: 'ignore', stderr: 'ignore' });
97
- await proc.exited;
98
- }
58
+ await fsUnlink(path);
99
59
  }
100
60
 
101
61
  async function rm(path: string, options?: { recursive?: boolean }) {
102
- if (process.platform === 'win32') {
103
- const proc = spawn(['cmd', '/c', 'rmdir', '/s', '/q', path.replace(/\//g, '\\')], { stdout: 'ignore', stderr: 'ignore' });
104
- await proc.exited;
105
- } else {
106
- const proc = spawn(['rm', '-rf', path], { stdout: 'ignore', stderr: 'ignore' });
107
- await proc.exited;
108
- }
62
+ await fsRm(path, { recursive: options?.recursive ?? false, force: true });
109
63
  }
110
64
 
111
- async function rmdir(path: string, options?: { recursive?: boolean }) {
112
- return rm(path, options);
65
+ async function rmdir(path: string) {
66
+ await fsRmdir(path);
113
67
  }
114
68
 
115
69
  export async function writeFileOperation(filePath: string, content: string, baseModified?: string) {