path-opener.spec.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /** Cross-platform native path opener behavior. */
  2. type ExecFileCallback = (
  3. error: (Error & { code?: string | number }) | null,
  4. stdout: string,
  5. stderr: string,
  6. ) => void
  7. type ExecFileMock = (
  8. command: string,
  9. args: readonly string[],
  10. options: { encoding: string; signal: AbortSignal; windowsHide: boolean },
  11. callback: ExecFileCallback,
  12. ) => void
  13. const { execFileMock } = vi.hoisted(() => ({ execFileMock: vi.fn<ExecFileMock>() }))
  14. vi.mock('node:child_process', () => ({ execFile: execFileMock }))
  15. import { release as osRelease } from 'node:os'
  16. import { describe, expect, it, vi } from 'vitest'
  17. import { canOpenNativePath, nativeFileManager, revealNativePath, openNativePath, openNativeTextFile, type PathOpenerRunner } from '../src/index.ts'
  18. const signal = () => new AbortController().signal
  19. describe('native path opener', () => {
  20. it('opens with macOS open(1)', async () => {
  21. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  22. await openNativePath('/Users/test/file.txt', signal(), { platform: 'darwin', run })
  23. expect(run).toHaveBeenCalledWith('open', ['/Users/test/file.txt'], expect.any(AbortSignal))
  24. })
  25. it('bypasses macOS file associations for text documents', async () => {
  26. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  27. await openNativeTextFile('/Users/test/settings.yaml', signal(), { platform: 'darwin', run })
  28. expect(run).toHaveBeenCalledWith('open', ['-t', '/Users/test/settings.yaml'], expect.any(AbortSignal))
  29. })
  30. it('uses the Linux desktop association for text documents', async () => {
  31. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  32. await openNativeTextFile('/tmp/settings.yaml', signal(), {
  33. platform: 'linux', osRelease: '6.8.0-generic', env: {}, run,
  34. })
  35. expect(run).toHaveBeenCalledWith('xdg-open', ['/tmp/settings.yaml'], expect.any(AbortSignal))
  36. })
  37. it.each([
  38. ['distribution marker', { WSL_DISTRO_NAME: 'Ubuntu' }, '6.8.0-generic'],
  39. ['interop marker', { WSL_INTEROP: '/run/WSL/123_interop' }, '6.8.0-generic'],
  40. ['kernel release', {}, '5.15.153.1-microsoft-standard-WSL2'],
  41. ])('hands WSL text documents to the Windows desktop from the %s', async (_label, env, osRelease) => {
  42. const requestSignal = signal()
  43. const run = vi.fn<PathOpenerRunner>(async command => command === 'wslpath'
  44. ? { stdout: '\\\\wsl.localhost\\Ubuntu\\home\\test user\\settings.yaml\r\n', stderr: '' }
  45. : { stdout: '', stderr: '' })
  46. await openNativeTextFile('/home/test user/settings.yaml', requestSignal, {
  47. platform: 'linux', osRelease, env, run,
  48. })
  49. expect(run.mock.calls).toEqual([
  50. ['wslpath', ['-w', '/home/test user/settings.yaml'], requestSignal],
  51. [
  52. 'powershell.exe',
  53. [
  54. '-NoProfile',
  55. '-Command',
  56. "Invoke-Item -LiteralPath '\\\\wsl.localhost\\Ubuntu\\home\\test user\\settings.yaml'",
  57. ],
  58. requestSignal,
  59. ],
  60. ])
  61. })
  62. it('rejects an empty WSL path translation before invoking Windows', async () => {
  63. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '\r\n', stderr: '' }))
  64. await expect(openNativeTextFile('/home/test/settings.yaml', signal(), {
  65. platform: 'linux', osRelease: '6.8.0-generic', env: { WSL_DISTRO_NAME: 'Ubuntu' }, run,
  66. })).rejects.toThrow('wslpath returned no Windows path')
  67. expect(run).toHaveBeenCalledOnce()
  68. })
  69. it('does not invoke Windows when the request aborts during WSL path translation', async () => {
  70. const abort = new AbortController()
  71. const run = vi.fn<PathOpenerRunner>(async () => {
  72. abort.abort(new Error('closed'))
  73. return { stdout: '\\\\wsl.localhost\\Ubuntu\\home\\test\\settings.yaml\n', stderr: '' }
  74. })
  75. await expect(openNativeTextFile('/home/test/settings.yaml', abort.signal, {
  76. platform: 'linux', osRelease: '6.8.0-generic', env: { WSL_DISTRO_NAME: 'Ubuntu' }, run,
  77. })).rejects.toThrow('closed')
  78. expect(run).toHaveBeenCalledOnce()
  79. })
  80. it('opens with Windows Invoke-Item and escapes single quotes', async () => {
  81. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  82. await openNativePath("C:\\work\\o'reilly.txt", signal(), { platform: 'win32', run })
  83. expect(run).toHaveBeenCalledWith(
  84. 'powershell.exe',
  85. ['-NoProfile', '-Command', "Invoke-Item -LiteralPath 'C:\\work\\o''reilly.txt'"],
  86. expect.any(AbortSignal),
  87. )
  88. })
  89. it('uses the Windows desktop association for text documents', async () => {
  90. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  91. await openNativeTextFile('C:\\work\\settings.yaml', signal(), { platform: 'win32', run })
  92. expect(run).toHaveBeenCalledWith(
  93. 'powershell.exe',
  94. ['-NoProfile', '-Command', "Invoke-Item -LiteralPath 'C:\\work\\settings.yaml'"],
  95. expect.any(AbortSignal),
  96. )
  97. })
  98. it('opens with Linux xdg-open', async () => {
  99. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  100. await openNativePath('/tmp/a.txt', signal(), {
  101. platform: 'linux', osRelease: '6.8.0-generic',
  102. env: { WSL_DISTRO_NAME: '', WSL_INTEROP: '' }, run,
  103. })
  104. expect(run).toHaveBeenCalledWith('xdg-open', ['/tmp/a.txt'], expect.any(AbortSignal))
  105. })
  106. it('rejects unsupported platforms', async () => {
  107. await expect(openNativePath('/x', signal(), { platform: 'freebsd' as NodeJS.Platform }))
  108. .rejects.toThrow('unsupported on freebsd')
  109. })
  110. it('uses the current process platform when no platform override is supplied', async () => {
  111. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  112. await openNativePath('/tmp/platform-default.txt', signal(), {
  113. osRelease: '6.8.0-generic', env: {}, run,
  114. })
  115. const expected = process.platform === 'win32'
  116. ? 'powershell.exe'
  117. : process.platform === 'linux'
  118. ? 'xdg-open'
  119. : 'open'
  120. expect(run.mock.calls[0]?.[0]).toBe(expected)
  121. })
  122. it('samples ambient WSL markers and kernel release when no fact overrides are supplied', async () => {
  123. const ambientWsl = [process.env.WSL_DISTRO_NAME, process.env.WSL_INTEROP]
  124. .some(value => value !== undefined && value !== '')
  125. || osRelease().toLowerCase().includes('microsoft')
  126. const run = vi.fn<PathOpenerRunner>(async command => command === 'wslpath'
  127. ? { stdout: 'C:\\settings.yaml\n', stderr: '' }
  128. : { stdout: '', stderr: '' })
  129. await openNativePath('/tmp/ambient-facts.yaml', signal(), { platform: 'linux', run })
  130. expect(run.mock.calls[0]?.[0]).toBe(ambientWsl ? 'wslpath' : 'xdg-open')
  131. })
  132. it('runs the default command adapter without a shell and preserves command failures', async () => {
  133. execFileMock.mockImplementationOnce((_command, _args, _options, callback) => {
  134. callback(null, '', '')
  135. })
  136. await openNativePath('/tmp/default.txt', signal(), { platform: 'darwin' })
  137. const [command, args, options] = execFileMock.mock.calls[0]!
  138. expect(command).toBe('open')
  139. expect(args).toEqual(['/tmp/default.txt'])
  140. expect(options.encoding).toBe('utf8')
  141. expect(options.windowsHide).toBe(true)
  142. expect(options.signal).toBeInstanceOf(AbortSignal)
  143. const commandError = Object.assign(new Error('open failed'), { code: 1 })
  144. execFileMock.mockImplementationOnce((_command, _args, _options, callback) => {
  145. callback(commandError, 'partial output', 'failure details')
  146. })
  147. await expect(openNativePath('/tmp/missing.txt', signal(), { platform: 'darwin' })).rejects.toMatchObject({
  148. message: 'open failed', cause: commandError, code: 1,
  149. stdout: 'partial output', stderr: 'failure details',
  150. })
  151. })
  152. })
  153. describe('browser-renderable documents', () => {
  154. const LS_PLIST = `{
  155. LSHandlers = (
  156. {
  157. LSHandlerPreferredVersions = {
  158. LSHandlerRoleAll = "-";
  159. };
  160. LSHandlerRoleAll = "com.google.chrome";
  161. LSHandlerURLScheme = https;
  162. }
  163. );
  164. }`
  165. it('opens a page with the default browser rather than the .html handler on darwin', async () => {
  166. const calls: { command: string; args: readonly string[] }[] = []
  167. const run = async (command: string, args: readonly string[]) => {
  168. calls.push({ command, args })
  169. return { stdout: command === 'defaults' ? LS_PLIST : '', stderr: '' }
  170. }
  171. await openNativePath('/w/page.html', new AbortController().signal, { platform: 'darwin', run })
  172. // A developer who bound .html to an editor still gets a rendered page.
  173. expect(calls.map(c => [c.command, ...c.args])).toEqual([
  174. ['defaults', 'read', 'com.apple.LaunchServices/com.apple.launchservices.secure'],
  175. ['open', '-b', 'com.google.chrome', '/w/page.html'],
  176. ])
  177. })
  178. it('leaves every other document to the default application', async () => {
  179. const calls: string[][] = []
  180. const run = async (command: string, args: readonly string[]) => {
  181. calls.push([command, ...args])
  182. return { stdout: '', stderr: '' }
  183. }
  184. await openNativePath('/w/report.md', new AbortController().signal, { platform: 'darwin', run })
  185. // No LaunchServices read at all: markdown is not a browser document.
  186. expect(calls).toEqual([['open', '/w/report.md']])
  187. })
  188. it('falls back to the default application when no browser can be named', async () => {
  189. // LaunchServices has no https record (a fresh account), so the system's
  190. // own content-type choice is the best answer available.
  191. const calls: string[][] = []
  192. const run = async (command: string, args: readonly string[]) => {
  193. calls.push([command, ...args])
  194. if (command === 'defaults') throw new Error('domain not found')
  195. return { stdout: '', stderr: '' }
  196. }
  197. await openNativePath('/w/page.html', new AbortController().signal, { platform: 'darwin', run })
  198. expect(calls).toEqual([
  199. ['defaults', 'read', 'com.apple.LaunchServices/com.apple.launchservices.secure'],
  200. ['open', '/w/page.html'],
  201. ])
  202. // A record without an https handler is the same answer.
  203. const bare: string[][] = []
  204. await openNativePath('/w/page.html', new AbortController().signal, {
  205. platform: 'darwin',
  206. run: async (command, args) => {
  207. bare.push([command, ...args])
  208. return { stdout: '{ LSHandlers = ( ); }', stderr: '' }
  209. },
  210. })
  211. expect(bare[1]).toEqual(['open', '/w/page.html'])
  212. })
  213. it('honors $BROWSER on linux and leaves windows to its association', async () => {
  214. const linux: string[][] = []
  215. await openNativePath('/w/page.html', new AbortController().signal, {
  216. platform: 'linux',
  217. osRelease: '6.8.0-generic',
  218. env: { BROWSER: 'firefox' },
  219. run: async (command, args) => { linux.push([command, ...args]); return { stdout: '', stderr: '' } },
  220. })
  221. expect(linux).toEqual([['firefox', '/w/page.html']])
  222. // Unset $BROWSER: xdg-open's association is the fallback.
  223. const bare: string[][] = []
  224. await openNativePath('/w/page.html', new AbortController().signal, {
  225. platform: 'linux',
  226. osRelease: '6.8.0-generic',
  227. env: {},
  228. run: async (command, args) => { bare.push([command, ...args]); return { stdout: '', stderr: '' } },
  229. })
  230. expect(bare).toEqual([['xdg-open', '/w/page.html']])
  231. // Windows names no browser without the UserChoice registry.
  232. const win: string[][] = []
  233. await openNativePath('C:\\w\\page.html', new AbortController().signal, {
  234. platform: 'win32',
  235. run: async (command, args) => { win.push([command, ...args]); return { stdout: '', stderr: '' } },
  236. })
  237. expect(win[0]?.[0]).toBe('powershell.exe')
  238. })
  239. it('hands browser-renderable WSL paths to the Windows desktop', async () => {
  240. const calls: string[][] = []
  241. await openNativePath('/home/test/page.html', new AbortController().signal, {
  242. platform: 'linux',
  243. osRelease: '5.15.153.1-microsoft-standard-WSL2',
  244. env: { BROWSER: 'firefox' },
  245. run: async (command, args) => {
  246. calls.push([command, ...args])
  247. return {
  248. stdout: command === 'wslpath' ? 'C:\\workspace\\page.html\n' : '',
  249. stderr: '',
  250. }
  251. },
  252. })
  253. expect(calls).toEqual([
  254. ['wslpath', '-w', '/home/test/page.html'],
  255. [
  256. 'powershell.exe',
  257. '-NoProfile',
  258. '-Command',
  259. "Invoke-Item -LiteralPath 'C:\\workspace\\page.html'",
  260. ],
  261. ])
  262. })
  263. })
  264. describe('canOpenNativePath', () => {
  265. it('always answers yes where the desktop is part of the platform', () => {
  266. expect(canOpenNativePath({ platform: 'darwin', env: {} })).toBe(true)
  267. expect(canOpenNativePath({ platform: 'win32', env: {} })).toBe(true)
  268. })
  269. it('requires a display server or WSL interop on linux', () => {
  270. const linux = { platform: 'linux' as const, osRelease: '6.8.0-generic' }
  271. // Headless is the case the capability exists for: `xdg-open` would spawn
  272. // into nothing, so a surface should show the path as text instead.
  273. expect(canOpenNativePath({ ...linux, env: {} })).toBe(false)
  274. expect(canOpenNativePath({ ...linux, env: { DISPLAY: ':0' } })).toBe(true)
  275. expect(canOpenNativePath({ ...linux, env: { WAYLAND_DISPLAY: 'wayland-0' } })).toBe(true)
  276. expect(canOpenNativePath({
  277. platform: 'linux', osRelease: '5.15.153.1-microsoft-standard-WSL2', env: {},
  278. })).toBe(true)
  279. })
  280. it('answers no on a platform the opener does not support', () => {
  281. expect(canOpenNativePath({ platform: 'freebsd', env: {} })).toBe(false)
  282. })
  283. it('samples the ambient environment when no override is supplied', () => {
  284. const env = process.env
  285. const marked = (value: string | undefined): boolean => value !== undefined && value !== ''
  286. const expected = marked(env.WSL_DISTRO_NAME) || marked(env.WSL_INTEROP)
  287. || marked(env.DISPLAY) || marked(env.WAYLAND_DISPLAY)
  288. expect(canOpenNativePath({ platform: 'linux', osRelease: '6.8.0-generic' })).toBe(expected)
  289. })
  290. it('samples the ambient platform when none is named', () => {
  291. // The internals are a test seam; a deployment calls this with nothing and
  292. // must get the answer for the host it is actually running on.
  293. expect(canOpenNativePath()).toBe(canOpenNativePath({ platform: process.platform }))
  294. })
  295. })
  296. describe('native file manager', () => {
  297. it.each([
  298. ['darwin', 'finder', '/tmp/my report.txt', 'open', ['-R', '/tmp/my report.txt']],
  299. ['win32', 'explorer', 'C:\\work\\my report.txt', 'explorer.exe', ['/select,', 'file:///C:/work/my%20report.txt']],
  300. ['linux', 'directory', '/tmp/a $b; report.txt', 'xdg-open', ['/tmp']],
  301. ] as const)('reveals through %s without opening the file association', async (platform, manager, path, command, args) => {
  302. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  303. const internals = { platform, env: {}, osRelease: 'generic', run }
  304. expect(nativeFileManager(internals)).toBe(manager)
  305. await revealNativePath(path, signal(), internals)
  306. expect(run).toHaveBeenCalledExactlyOnceWith(command, args, expect.any(AbortSignal))
  307. })
  308. it('selects a translated WSL path in Explorer and never starts a Linux file manager', async () => {
  309. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: 'C:\\work\\报告.txt\r\n', stderr: '' }))
  310. const internals = { platform: 'linux' as const, env: { WSL_DISTRO_NAME: 'Ubuntu' }, run }
  311. expect(nativeFileManager(internals)).toBe('explorer')
  312. await revealNativePath('/mnt/c/work/报告.txt', signal(), internals)
  313. expect(run.mock.calls.map(([cmd, args]) => [cmd, args])).toEqual([
  314. ['wslpath', ['-w', '/mnt/c/work/报告.txt']], ['explorer.exe', ['/select,', 'file:///C:/work/%E6%8A%A5%E5%91%8A.txt']],
  315. ])
  316. })
  317. it('refuses empty WSL translations and cancelled translation without launching Explorer', async () => {
  318. const abort = new AbortController()
  319. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  320. const internals = { platform: 'linux' as const, env: {}, osRelease: 'microsoft', run }
  321. await expect(revealNativePath('/file', signal(), internals)).rejects.toThrow('no Windows path')
  322. run.mockImplementationOnce(async () => { abort.abort(new Error('stopped')); return { stdout: 'C:\\file', stderr: '' } })
  323. await expect(revealNativePath('/file', abort.signal, internals)).rejects.toThrow('stopped')
  324. expect(run.mock.calls.every(([cmd]) => cmd === 'wslpath')).toBe(true)
  325. })
  326. it('rejects unsupported platforms, cancellation, and launcher errors', async () => {
  327. const run = vi.fn<PathOpenerRunner>().mockRejectedValue(new Error('desktop failed'))
  328. expect(nativeFileManager({ platform: 'aix' })).toBeNull()
  329. await expect(revealNativePath('/file', signal(), { platform: 'aix', run })).rejects.toThrow('unsupported')
  330. await expect(revealNativePath('/file', AbortSignal.abort(new Error('cancelled')), { run })).rejects.toThrow('cancelled')
  331. expect(run).not.toHaveBeenCalled()
  332. await expect(revealNativePath('/file', signal(), { platform: 'darwin', run })).rejects.toThrow('desktop failed')
  333. expect(nativeFileManager()).toBe(process.platform === 'darwin' ? 'finder' : process.platform === 'win32' ? 'explorer' : 'directory')
  334. })
  335. })
  336. it('uses the native runner for a file-manager handoff when none is injected', async () => {
  337. execFileMock.mockImplementation((_command, _args, _options, callback) => { callback(null, '', '') })
  338. await revealNativePath('/tmp/report.txt', signal())
  339. expect(execFileMock).toHaveBeenCalled()
  340. })
  341. it.each(['win32', 'linux'] as const)('accepts Explorer delegate exit 1 through the native runner on %s', async (platform) => {
  342. execFileMock.mockImplementation((command, _args, _options, callback) => {
  343. if (command === 'wslpath') callback(null, 'C:\\work\\report.txt', '')
  344. else callback(Object.assign(new Error('delegated'), { code: 1 }), '', '')
  345. })
  346. await expect(revealNativePath(platform === 'win32' ? 'C:\\work\\report.txt' : '/mnt/c/work/report.txt', signal(),
  347. { platform, env: { WSL_DISTRO_NAME: 'Ubuntu' } })).resolves.toBeUndefined()
  348. })
  349. it.each([2, 'ENOENT', undefined])('preserves Explorer failure %s', async (code) => {
  350. const failure = Object.assign(new Error('launch failed'), code === undefined ? {} : { code })
  351. execFileMock.mockImplementation((_command, _args, _options, callback) => { callback(failure, '', '') })
  352. await expect(revealNativePath('C:\\file.txt', signal(), { platform: 'win32' })).rejects.toMatchObject({ code })
  353. })
  354. it('preserves cancellation even when Explorer returns delegate exit 1', async () => {
  355. const abort = new AbortController()
  356. const reason = new Error('cancelled')
  357. const run = vi.fn<PathOpenerRunner>(async () => {
  358. abort.abort(reason)
  359. throw Object.assign(new Error('delegated'), { code: 1 })
  360. })
  361. await expect(revealNativePath('C:\\file.txt', abort.signal, { platform: 'win32', run })).rejects.toBe(reason)
  362. })
  363. it.each([
  364. ['C:\\my files\\报告,#%.txt', 'file:///C:/my%20files/%E6%8A%A5%E5%91%8A%2C%23%25.txt'],
  365. ['\\\\server\\share\\a,b.txt', 'file://server/share/a%2Cb.txt'],
  366. ])('preserves special characters in the Explorer target %s', async (path, target) => {
  367. const run = vi.fn<PathOpenerRunner>().mockResolvedValue({ stdout: '', stderr: '' })
  368. await revealNativePath(path, signal(), { platform: 'win32', run })
  369. expect(run).toHaveBeenCalledWith('explorer.exe', ['/select,', target], expect.any(AbortSignal))
  370. })