|
1 | | -import openImpl from 'open' |
| 1 | +import { spawn } from 'node:child_process' |
| 2 | +import fs from 'node:fs' |
| 3 | +import process from 'node:process' |
2 | 4 |
|
3 | | -export interface OpenOptions { |
4 | | - /** |
5 | | - * Resolve only after the launched app exits. |
6 | | - * |
7 | | - * @default false |
8 | | - */ |
9 | | - wait?: boolean |
| 5 | +/** |
| 6 | + * Launches `command` detached from the current process and resolves once |
| 7 | + * the OS has accepted the spawn (not once the launched app exits) — the |
| 8 | + * same "fire and forget" behavior `open`'s default (`wait: false`) gave us. |
| 9 | + */ |
| 10 | +function spawnDetached(command: string, args: string[]): Promise<void> { |
| 11 | + return new Promise((resolve, reject) => { |
| 12 | + const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: true }) |
| 13 | + child.once('error', reject) |
| 14 | + child.once('spawn', () => { |
| 15 | + child.unref() |
| 16 | + resolve() |
| 17 | + }) |
| 18 | + }) |
| 19 | +} |
| 20 | + |
| 21 | +function isWsl(): boolean { |
| 22 | + if (process.platform !== 'linux') |
| 23 | + return false |
| 24 | + try { |
| 25 | + return fs.readFileSync('/proc/version', 'utf-8').toLowerCase().includes('microsoft') |
| 26 | + } |
| 27 | + catch { |
| 28 | + return false |
| 29 | + } |
10 | 30 | } |
11 | 31 |
|
12 | 32 | /** |
13 | 33 | * Open a URL, file, or other target in its default OS handler |
14 | 34 | * (browser for URLs, Finder/Explorer for paths, etc.). |
15 | 35 | */ |
16 | | -export async function open(target: string, options?: OpenOptions): Promise<void> { |
17 | | - await openImpl(target, options) |
| 36 | +export async function open(target: string): Promise<void> { |
| 37 | + if (process.platform === 'darwin') |
| 38 | + return spawnDetached('open', [target]) |
| 39 | + |
| 40 | + if (process.platform === 'win32') { |
| 41 | + // `start` is a cmd.exe builtin; the empty title argument keeps `target` |
| 42 | + // from being mistaken for a window title when it's itself quoted. |
| 43 | + return spawnDetached('cmd', ['/c', 'start', '""', target]) |
| 44 | + } |
| 45 | + |
| 46 | + if (isWsl()) { |
| 47 | + // `wslview` (from wslu) hands the target to the Windows shell the same |
| 48 | + // way an interactive user would; fall back to invoking `cmd.exe` |
| 49 | + // directly on WSL distros that don't have wslu installed. |
| 50 | + try { |
| 51 | + return await spawnDetached('wslview', [target]) |
| 52 | + } |
| 53 | + catch { |
| 54 | + return spawnDetached('cmd.exe', ['/c', 'start', '""', target]) |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return spawnDetached('xdg-open', [target]) |
18 | 59 | } |
0 commit comments