process-shim.spec.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * The worker's process shim: the layout-derived environment and the Node 22
  3. * `getBuiltinModule` face, which must answer the loader's module proxies for
  4. * builtin ids and undefined for everything else — never an image resolution.
  5. */
  6. import { afterEach, describe, expect, it } from 'vitest'
  7. import { installProcessGlobal } from '../../src/node/globals/process.ts'
  8. import { setActiveModuleLoader, WorkerModuleLoader } from '../../src/module-system/module-loader.ts'
  9. import { MemoryVfs } from '../../src/storage/memory.ts'
  10. import { spawnSync } from '../../src/node/builtin_modules/implemented/child_process.ts'
  11. const realProcess = globalThis.process
  12. afterEach(() => {
  13. ;(globalThis as { process: unknown }).process = realProcess
  14. })
  15. describe('process shim', () => {
  16. it('publishes cwd, env, and version zero for the loader probe', () => {
  17. const shim = installProcessGlobal({ cwd: '/dsh', env: { DSH_HOME: '/dsh/home' } })
  18. expect(shim.cwd()).toBe('/dsh')
  19. expect(shim.env.DSH_HOME).toBe('/dsh/home')
  20. expect(shim.title).toBe('dsh-webworker')
  21. // "0.0.0" keeps the vendored Loader off Node internals so the worker owns
  22. // the module seam.
  23. expect(shim.versions.node).toBe('0.0.0')
  24. })
  25. it('exposes an executable identity without enabling Node programs', () => {
  26. const shim = installProcessGlobal({ cwd: '/dsh', env: {} })
  27. expect(shim.execPath).toBe('/dsh/bin/node')
  28. expect(spawnSync(shim.execPath, ['--eval', 'throw new Error("must not execute")']).error?.code).toBe('ENOENT')
  29. })
  30. it('answers getBuiltinModule from the module proxies and undefined otherwise', () => {
  31. const fs = { marker: 'fs-proxy' }
  32. // The table holds factories, and a builtin must keep one identity across
  33. // requires (`instanceof`, `Buffer.isBuffer`), so this one answers with the
  34. // same object every time.
  35. const factory = (): unknown => fs
  36. const vfs = new MemoryVfs()
  37. vfs.seedDirectory('/dsh')
  38. const loader = new WorkerModuleLoader({
  39. vfs,
  40. root: '/dsh',
  41. staticModules: { 'node:fs': factory, 'fs': factory },
  42. })
  43. setActiveModuleLoader(loader)
  44. const shim = installProcessGlobal({ cwd: '/dsh', env: {} })
  45. // The shim calls the factory: a caller receives the module, never the thunk.
  46. expect(shim.getBuiltinModule('fs')).toBe(fs)
  47. expect(shim.getBuiltinModule('node:fs')).toBe(fs)
  48. expect(shim.getBuiltinModule('no-such-builtin')).toBeUndefined()
  49. })
  50. })