register.mjs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { existsSync, rmSync } from 'node:fs'
  2. import { registerHooks } from 'node:module'
  3. import { join } from 'node:path'
  4. const openerUrl = new URL('./open.mjs', import.meta.url).href
  5. const exitMarker = join(process.cwd(), `.dsh-browser-open-${process.pid}`)
  6. const markerPoll = setInterval(() => {
  7. if (!existsSync(exitMarker)) return
  8. rmSync(exitMarker, { force: true })
  9. process.exit(0)
  10. }, 25)
  11. markerPoll.unref()
  12. registerHooks({
  13. resolve(specifier, context, nextResolve) {
  14. if (specifier === 'open') return { shortCircuit: true, url: openerUrl }
  15. return nextResolve(specifier, context)
  16. },
  17. })
  18. // The SSH case has no opener helper to stop the long-lived Web process.
  19. if (process.env.DSH_BROWSER_OPEN_TEST_EXIT_ON_READY === '1') {
  20. const originalLog = console.log
  21. console.log = (...args) => {
  22. originalLog(...args)
  23. if (typeof args[0] === 'string' && args[0].startsWith('dsh web: ')) {
  24. setTimeout(() => process.exit(0), 250)
  25. }
  26. }
  27. }
  28. if (process.env.DSH_BROWSER_OPEN_TEST_EXIT_ON_FAILURE === '1') {
  29. const originalError = console.error
  30. console.error = (...args) => {
  31. originalError(...args)
  32. if (typeof args[0] === 'string' && args[0].startsWith('web-app: could not open the default browser because ')) {
  33. setTimeout(() => process.exit(0), 0)
  34. }
  35. }
  36. }