1
0

native-path-opener.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. type ExecFileCallback = (
  2. error: (Error & { code?: string | number }) | null,
  3. stdout: string,
  4. stderr: string,
  5. ) => void
  6. type ExecFileMock = (
  7. command: string,
  8. args: readonly string[],
  9. options: { encoding: string; signal: AbortSignal; windowsHide: boolean },
  10. callback: ExecFileCallback,
  11. ) => void
  12. const { execFileMock } = vi.hoisted(() => ({ execFileMock: vi.fn<ExecFileMock>() }))
  13. vi.mock('node:child_process', () => ({ execFile: execFileMock }))
  14. import { release as osRelease } from 'node:os'
  15. import { describe, expect, it, vi } from 'vitest'
  16. import { canOpenNativePath, openNativePath, openNativeTextFile, type PathOpenerRunner } from '../src/native-path-opener.ts'
  17. const signal = () => new AbortController().signal
  18. describe('native path opener', () => {
  19. it('opens with macOS open(1)', async () => {
  20. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  21. await openNativePath('/Users/test/file.txt', signal(), { platform: 'darwin', run })
  22. expect(run).toHaveBeenCalledWith('open', ['/Users/test/file.txt'], expect.any(AbortSignal))
  23. })
  24. it('bypasses macOS file associations for text documents', async () => {
  25. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  26. await openNativeTextFile('/Users/test/settings.yaml', signal(), { platform: 'darwin', run })
  27. expect(run).toHaveBeenCalledWith('open', ['-t', '/Users/test/settings.yaml'], expect.any(AbortSignal))
  28. })
  29. it('uses the Linux desktop association for text documents', async () => {
  30. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  31. await openNativeTextFile('/tmp/settings.yaml', signal(), {
  32. platform: 'linux', osRelease: '6.8.0-generic', env: {}, run,
  33. })
  34. expect(run).toHaveBeenCalledWith('xdg-open', ['/tmp/settings.yaml'], expect.any(AbortSignal))
  35. })
  36. it.each([
  37. ['distribution marker', { WSL_DISTRO_NAME: 'Ubuntu' }, '6.8.0-generic'],
  38. ['interop marker', { WSL_INTEROP: '/run/WSL/123_interop' }, '6.8.0-generic'],
  39. ['kernel release', {}, '5.15.153.1-microsoft-standard-WSL2'],
  40. ])('hands WSL text documents to the Windows desktop from the %s', async (_label, env, osRelease) => {
  41. const requestSignal = signal()
  42. const run = vi.fn<PathOpenerRunner>(async command => command === 'wslpath'
  43. ? { stdout: '\\\\wsl.localhost\\Ubuntu\\home\\test user\\settings.yaml\r\n', stderr: '' }
  44. : { stdout: '', stderr: '' })
  45. await openNativeTextFile('/home/test user/settings.yaml', requestSignal, {
  46. platform: 'linux', osRelease, env, run,
  47. })
  48. expect(run.mock.calls).toEqual([
  49. ['wslpath', ['-w', '/home/test user/settings.yaml'], requestSignal],
  50. [
  51. 'powershell.exe',
  52. [
  53. '-NoProfile',
  54. '-Command',
  55. "Invoke-Item -LiteralPath '\\\\wsl.localhost\\Ubuntu\\home\\test user\\settings.yaml'",
  56. ],
  57. requestSignal,
  58. ],
  59. ])
  60. })
  61. it('rejects an empty WSL path translation before invoking Windows', async () => {
  62. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '\r\n', stderr: '' }))
  63. await expect(openNativeTextFile('/home/test/settings.yaml', signal(), {
  64. platform: 'linux', osRelease: '6.8.0-generic', env: { WSL_DISTRO_NAME: 'Ubuntu' }, run,
  65. })).rejects.toThrow('wslpath returned no Windows path')
  66. expect(run).toHaveBeenCalledOnce()
  67. })
  68. it('does not invoke Windows when the request aborts during WSL path translation', async () => {
  69. const abort = new AbortController()
  70. const run = vi.fn<PathOpenerRunner>(async () => {
  71. abort.abort(new Error('closed'))
  72. return { stdout: '\\\\wsl.localhost\\Ubuntu\\home\\test\\settings.yaml\n', stderr: '' }
  73. })
  74. await expect(openNativeTextFile('/home/test/settings.yaml', abort.signal, {
  75. platform: 'linux', osRelease: '6.8.0-generic', env: { WSL_DISTRO_NAME: 'Ubuntu' }, run,
  76. })).rejects.toThrow('closed')
  77. expect(run).toHaveBeenCalledOnce()
  78. })
  79. it('opens with Windows Invoke-Item and escapes single quotes', async () => {
  80. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  81. await openNativePath("C:\\work\\o'reilly.txt", signal(), { platform: 'win32', run })
  82. expect(run).toHaveBeenCalledWith(
  83. 'powershell.exe',
  84. ['-NoProfile', '-Command', "Invoke-Item -LiteralPath 'C:\\work\\o''reilly.txt'"],
  85. expect.any(AbortSignal),
  86. )
  87. })
  88. it('uses the Windows desktop association for text documents', async () => {
  89. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  90. await openNativeTextFile('C:\\work\\settings.yaml', signal(), { platform: 'win32', run })
  91. expect(run).toHaveBeenCalledWith(
  92. 'powershell.exe',
  93. ['-NoProfile', '-Command', "Invoke-Item -LiteralPath 'C:\\work\\settings.yaml'"],
  94. expect.any(AbortSignal),
  95. )
  96. })
  97. it('opens with Linux xdg-open', async () => {
  98. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  99. await openNativePath('/tmp/a.txt', signal(), {
  100. platform: 'linux', osRelease: '6.8.0-generic',
  101. env: { WSL_DISTRO_NAME: '', WSL_INTEROP: '' }, run,
  102. })
  103. expect(run).toHaveBeenCalledWith('xdg-open', ['/tmp/a.txt'], expect.any(AbortSignal))
  104. })
  105. it('rejects unsupported platforms', async () => {
  106. await expect(openNativePath('/x', signal(), { platform: 'freebsd' as NodeJS.Platform }))
  107. .rejects.toThrow('unsupported on freebsd')
  108. })
  109. it('uses the current process platform when no platform override is supplied', async () => {
  110. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  111. await openNativePath('/tmp/platform-default.txt', signal(), {
  112. osRelease: '6.8.0-generic', env: {}, run,
  113. })
  114. const expected = process.platform === 'win32'
  115. ? 'powershell.exe'
  116. : process.platform === 'linux'
  117. ? 'xdg-open'
  118. : 'open'
  119. expect(run.mock.calls[0]?.[0]).toBe(expected)
  120. })
  121. it('samples ambient WSL markers and kernel release when no fact overrides are supplied', async () => {
  122. const ambientWsl = [process.env.WSL_DISTRO_NAME, process.env.WSL_INTEROP]
  123. .some(value => value !== undefined && value !== '')
  124. || osRelease().toLowerCase().includes('microsoft')
  125. const run = vi.fn<PathOpenerRunner>(async command => command === 'wslpath'
  126. ? { stdout: 'C:\\settings.yaml\n', stderr: '' }
  127. : { stdout: '', stderr: '' })
  128. await openNativePath('/tmp/ambient-facts.yaml', signal(), { platform: 'linux', run })
  129. expect(run.mock.calls[0]?.[0]).toBe(ambientWsl ? 'wslpath' : 'xdg-open')
  130. })
  131. it('runs the default command adapter without a shell and preserves command failures', async () => {
  132. execFileMock.mockImplementationOnce((_command, _args, _options, callback) => {
  133. callback(null, '', '')
  134. })
  135. await openNativePath('/tmp/default.txt', signal(), { platform: 'darwin' })
  136. const [command, args, options] = execFileMock.mock.calls[0]!
  137. expect(command).toBe('open')
  138. expect(args).toEqual(['/tmp/default.txt'])
  139. expect(options.encoding).toBe('utf8')
  140. expect(options.windowsHide).toBe(true)
  141. expect(options.signal).toBeInstanceOf(AbortSignal)
  142. const commandError = Object.assign(new Error('open failed'), { code: 1 })
  143. execFileMock.mockImplementationOnce((_command, _args, _options, callback) => {
  144. callback(commandError, 'partial output', 'failure details')
  145. })
  146. await expect(openNativePath('/tmp/missing.txt', signal(), { platform: 'darwin' })).rejects.toMatchObject({
  147. message: 'open failed', cause: commandError, code: 1,
  148. stdout: 'partial output', stderr: 'failure details',
  149. })
  150. })
  151. })
  152. describe('browser-renderable documents', () => {
  153. const LS_PLIST = `{
  154. LSHandlers = (
  155. {
  156. LSHandlerPreferredVersions = {
  157. LSHandlerRoleAll = "-";
  158. };
  159. LSHandlerRoleAll = "com.google.chrome";
  160. LSHandlerURLScheme = https;
  161. }
  162. );
  163. }`
  164. it('opens a page with the default browser rather than the .html handler on darwin', async () => {
  165. const calls: { command: string; args: readonly string[] }[] = []
  166. const run = async (command: string, args: readonly string[]) => {
  167. calls.push({ command, args })
  168. return { stdout: command === 'defaults' ? LS_PLIST : '', stderr: '' }
  169. }
  170. await openNativePath('/w/page.html', new AbortController().signal, { platform: 'darwin', run })
  171. // A developer who bound .html to an editor still gets a rendered page.
  172. expect(calls.map(c => [c.command, ...c.args])).toEqual([
  173. ['defaults', 'read', 'com.apple.LaunchServices/com.apple.launchservices.secure'],
  174. ['open', '-b', 'com.google.chrome', '/w/page.html'],
  175. ])
  176. })
  177. it('leaves every other document to the default application', async () => {
  178. const calls: string[][] = []
  179. const run = async (command: string, args: readonly string[]) => {
  180. calls.push([command, ...args])
  181. return { stdout: '', stderr: '' }
  182. }
  183. await openNativePath('/w/report.md', new AbortController().signal, { platform: 'darwin', run })
  184. // No LaunchServices read at all: markdown is not a browser document.
  185. expect(calls).toEqual([['open', '/w/report.md']])
  186. })
  187. it('falls back to the default application when no browser can be named', async () => {
  188. // LaunchServices has no https record (a fresh account), so the system's
  189. // own content-type choice is the best answer available.
  190. const calls: string[][] = []
  191. const run = async (command: string, args: readonly string[]) => {
  192. calls.push([command, ...args])
  193. if (command === 'defaults') throw new Error('domain not found')
  194. return { stdout: '', stderr: '' }
  195. }
  196. await openNativePath('/w/page.html', new AbortController().signal, { platform: 'darwin', run })
  197. expect(calls).toEqual([
  198. ['defaults', 'read', 'com.apple.LaunchServices/com.apple.launchservices.secure'],
  199. ['open', '/w/page.html'],
  200. ])
  201. // A record without an https handler is the same answer.
  202. const bare: string[][] = []
  203. await openNativePath('/w/page.html', new AbortController().signal, {
  204. platform: 'darwin',
  205. run: async (command, args) => {
  206. bare.push([command, ...args])
  207. return { stdout: '{ LSHandlers = ( ); }', stderr: '' }
  208. },
  209. })
  210. expect(bare[1]).toEqual(['open', '/w/page.html'])
  211. })
  212. it('honors $BROWSER on linux and leaves windows to its association', async () => {
  213. const linux: string[][] = []
  214. await openNativePath('/w/page.html', new AbortController().signal, {
  215. platform: 'linux',
  216. osRelease: '6.8.0-generic',
  217. env: { BROWSER: 'firefox' },
  218. run: async (command, args) => { linux.push([command, ...args]); return { stdout: '', stderr: '' } },
  219. })
  220. expect(linux).toEqual([['firefox', '/w/page.html']])
  221. // Unset $BROWSER: xdg-open's association is the fallback.
  222. const bare: string[][] = []
  223. await openNativePath('/w/page.html', new AbortController().signal, {
  224. platform: 'linux',
  225. osRelease: '6.8.0-generic',
  226. env: {},
  227. run: async (command, args) => { bare.push([command, ...args]); return { stdout: '', stderr: '' } },
  228. })
  229. expect(bare).toEqual([['xdg-open', '/w/page.html']])
  230. // Windows names no browser without the UserChoice registry.
  231. const win: string[][] = []
  232. await openNativePath('C:\\w\\page.html', new AbortController().signal, {
  233. platform: 'win32',
  234. run: async (command, args) => { win.push([command, ...args]); return { stdout: '', stderr: '' } },
  235. })
  236. expect(win[0]?.[0]).toBe('powershell.exe')
  237. })
  238. it('hands browser-renderable WSL paths to the Windows desktop', async () => {
  239. const calls: string[][] = []
  240. await openNativePath('/home/test/page.html', new AbortController().signal, {
  241. platform: 'linux',
  242. osRelease: '5.15.153.1-microsoft-standard-WSL2',
  243. env: { BROWSER: 'firefox' },
  244. run: async (command, args) => {
  245. calls.push([command, ...args])
  246. return {
  247. stdout: command === 'wslpath' ? 'C:\\workspace\\page.html\n' : '',
  248. stderr: '',
  249. }
  250. },
  251. })
  252. expect(calls).toEqual([
  253. ['wslpath', '-w', '/home/test/page.html'],
  254. [
  255. 'powershell.exe',
  256. '-NoProfile',
  257. '-Command',
  258. "Invoke-Item -LiteralPath 'C:\\workspace\\page.html'",
  259. ],
  260. ])
  261. })
  262. })
  263. describe('canOpenNativePath', () => {
  264. it('always answers yes where the desktop is part of the platform', () => {
  265. expect(canOpenNativePath({ platform: 'darwin', env: {} })).toBe(true)
  266. expect(canOpenNativePath({ platform: 'win32', env: {} })).toBe(true)
  267. })
  268. it('requires a display server or WSL interop on linux', () => {
  269. const linux = { platform: 'linux' as const, osRelease: '6.8.0-generic' }
  270. // Headless is the case the capability exists for: `xdg-open` would spawn
  271. // into nothing, so a surface should show the path as text instead.
  272. expect(canOpenNativePath({ ...linux, env: {} })).toBe(false)
  273. expect(canOpenNativePath({ ...linux, env: { DISPLAY: ':0' } })).toBe(true)
  274. expect(canOpenNativePath({ ...linux, env: { WAYLAND_DISPLAY: 'wayland-0' } })).toBe(true)
  275. expect(canOpenNativePath({
  276. platform: 'linux', osRelease: '5.15.153.1-microsoft-standard-WSL2', env: {},
  277. })).toBe(true)
  278. })
  279. it('answers no on a platform the opener does not support', () => {
  280. expect(canOpenNativePath({ platform: 'freebsd', env: {} })).toBe(false)
  281. })
  282. it('samples the ambient environment when no override is supplied', () => {
  283. const env = process.env
  284. const marked = (value: string | undefined): boolean => value !== undefined && value !== ''
  285. const expected = marked(env.WSL_DISTRO_NAME) || marked(env.WSL_INTEROP)
  286. || marked(env.DISPLAY) || marked(env.WAYLAND_DISPLAY)
  287. expect(canOpenNativePath({ platform: 'linux', osRelease: '6.8.0-generic' })).toBe(expected)
  288. })
  289. })