@seanhogg/builderforce-webcontainers-core 2026.10.8 → 2026.10.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/dist/build.d.ts +6 -0
  2. package/dist/build.d.ts.map +1 -1
  3. package/dist/build.js +9 -1
  4. package/dist/build.js.map +1 -1
  5. package/dist/buildHost.d.ts +3 -0
  6. package/dist/buildHost.d.ts.map +1 -1
  7. package/dist/buildHost.js +25 -12
  8. package/dist/buildHost.js.map +1 -1
  9. package/dist/compileComponent.d.ts.map +1 -1
  10. package/dist/compileComponent.js +4 -1
  11. package/dist/compileComponent.js.map +1 -1
  12. package/dist/compileScript.d.ts +12 -4
  13. package/dist/compileScript.d.ts.map +1 -1
  14. package/dist/compileScript.js +26 -13
  15. package/dist/compileScript.js.map +1 -1
  16. package/dist/components.d.ts +5 -0
  17. package/dist/components.d.ts.map +1 -1
  18. package/dist/components.js.map +1 -1
  19. package/dist/detectProject.d.ts +2 -0
  20. package/dist/detectProject.d.ts.map +1 -1
  21. package/dist/detectProject.js +13 -7
  22. package/dist/detectProject.js.map +1 -1
  23. package/dist/devServer.d.ts +38 -4
  24. package/dist/devServer.d.ts.map +1 -1
  25. package/dist/devServer.js +140 -24
  26. package/dist/devServer.js.map +1 -1
  27. package/dist/devStyles.d.ts +27 -0
  28. package/dist/devStyles.d.ts.map +1 -0
  29. package/dist/devStyles.js +52 -0
  30. package/dist/devStyles.js.map +1 -0
  31. package/dist/hot/client.d.ts +33 -0
  32. package/dist/hot/client.d.ts.map +1 -0
  33. package/dist/hot/client.js +46 -0
  34. package/dist/hot/client.js.map +1 -0
  35. package/dist/hot/moduleGraph.d.ts +39 -0
  36. package/dist/hot/moduleGraph.d.ts.map +1 -0
  37. package/dist/hot/moduleGraph.js +69 -0
  38. package/dist/hot/moduleGraph.js.map +1 -0
  39. package/dist/hot/planUpdate.d.ts +33 -0
  40. package/dist/hot/planUpdate.d.ts.map +1 -0
  41. package/dist/hot/planUpdate.js +43 -0
  42. package/dist/hot/planUpdate.js.map +1 -0
  43. package/dist/hot/reactRefresh.d.ts +45 -0
  44. package/dist/hot/reactRefresh.d.ts.map +1 -0
  45. package/dist/hot/reactRefresh.js +86 -0
  46. package/dist/hot/reactRefresh.js.map +1 -0
  47. package/dist/html.d.ts +2 -8
  48. package/dist/html.d.ts.map +1 -1
  49. package/dist/html.js +11 -17
  50. package/dist/html.js.map +1 -1
  51. package/dist/index.d.ts +19 -1
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +11 -1
  54. package/dist/index.js.map +1 -1
  55. package/dist/installer/tree.d.ts.map +1 -1
  56. package/dist/installer/tree.js +30 -5
  57. package/dist/installer/tree.js.map +1 -1
  58. package/dist/installer/wasmBuilds.d.ts +34 -0
  59. package/dist/installer/wasmBuilds.d.ts.map +1 -0
  60. package/dist/installer/wasmBuilds.js +41 -0
  61. package/dist/installer/wasmBuilds.js.map +1 -0
  62. package/dist/node/builtins.d.ts +6 -1
  63. package/dist/node/builtins.d.ts.map +1 -1
  64. package/dist/node/builtins.js +17 -10
  65. package/dist/node/builtins.js.map +1 -1
  66. package/dist/node/childProcess.d.ts +3 -3
  67. package/dist/node/childProcess.d.ts.map +1 -1
  68. package/dist/node/childProcess.js +68 -16
  69. package/dist/node/childProcess.js.map +1 -1
  70. package/dist/node/crypto.d.ts.map +1 -1
  71. package/dist/node/crypto.js +5 -4
  72. package/dist/node/crypto.js.map +1 -1
  73. package/dist/node/esm.d.ts +7 -0
  74. package/dist/node/esm.d.ts.map +1 -1
  75. package/dist/node/esm.js +28 -2
  76. package/dist/node/esm.js.map +1 -1
  77. package/dist/node/fs/index.d.ts +3 -0
  78. package/dist/node/fs/index.d.ts.map +1 -1
  79. package/dist/node/fs/index.js +22 -106
  80. package/dist/node/fs/index.js.map +1 -1
  81. package/dist/node/fs/stdinFd.d.ts +10 -0
  82. package/dist/node/fs/stdinFd.d.ts.map +1 -0
  83. package/dist/node/fs/stdinFd.js +40 -0
  84. package/dist/node/fs/stdinFd.js.map +1 -0
  85. package/dist/node/fs/streams.d.ts +24 -0
  86. package/dist/node/fs/streams.d.ts.map +1 -0
  87. package/dist/node/fs/streams.js +144 -0
  88. package/dist/node/fs/streams.js.map +1 -0
  89. package/dist/node/fs/sync.d.ts +2 -0
  90. package/dist/node/fs/sync.d.ts.map +1 -1
  91. package/dist/node/fs/sync.js +17 -0
  92. package/dist/node/fs/sync.js.map +1 -1
  93. package/dist/node/globalObject.d.ts +25 -0
  94. package/dist/node/globalObject.d.ts.map +1 -0
  95. package/dist/node/globalObject.js +83 -0
  96. package/dist/node/globalObject.js.map +1 -0
  97. package/dist/node/http/index.d.ts.map +1 -1
  98. package/dist/node/http/index.js +4 -3
  99. package/dist/node/http/index.js.map +1 -1
  100. package/dist/node/http/server.d.ts.map +1 -1
  101. package/dist/node/http/server.js +8 -5
  102. package/dist/node/http/server.js.map +1 -1
  103. package/dist/node/http/serverResponse.d.ts +3 -0
  104. package/dist/node/http/serverResponse.d.ts.map +1 -1
  105. package/dist/node/http/serverResponse.js +7 -0
  106. package/dist/node/http/serverResponse.js.map +1 -1
  107. package/dist/node/ipc.d.ts +26 -0
  108. package/dist/node/ipc.d.ts.map +1 -0
  109. package/dist/node/ipc.js +76 -0
  110. package/dist/node/ipc.js.map +1 -0
  111. package/dist/node/loader.d.ts +2 -0
  112. package/dist/node/loader.d.ts.map +1 -1
  113. package/dist/node/loader.js +79 -14
  114. package/dist/node/loader.js.map +1 -1
  115. package/dist/node/misc.d.ts.map +1 -1
  116. package/dist/node/misc.js +20 -6
  117. package/dist/node/misc.js.map +1 -1
  118. package/dist/node/process.d.ts +2 -5
  119. package/dist/node/process.d.ts.map +1 -1
  120. package/dist/node/process.js +16 -11
  121. package/dist/node/process.js.map +1 -1
  122. package/dist/node/processExit.d.ts +13 -0
  123. package/dist/node/processExit.d.ts.map +1 -0
  124. package/dist/node/processExit.js +25 -0
  125. package/dist/node/processExit.js.map +1 -0
  126. package/dist/node/program.d.ts.map +1 -1
  127. package/dist/node/program.js +6 -5
  128. package/dist/node/program.js.map +1 -1
  129. package/dist/node/runtime.d.ts +6 -1
  130. package/dist/node/runtime.d.ts.map +1 -1
  131. package/dist/node/runtime.js +23 -15
  132. package/dist/node/runtime.js.map +1 -1
  133. package/dist/node/stream/readable.d.ts +2 -1
  134. package/dist/node/stream/readable.d.ts.map +1 -1
  135. package/dist/node/stream/readable.js +2 -1
  136. package/dist/node/stream/readable.js.map +1 -1
  137. package/dist/node/urlqs.d.ts +1 -1
  138. package/dist/node/urlqs.d.ts.map +1 -1
  139. package/dist/node/urlqs.js +11 -2
  140. package/dist/node/urlqs.js.map +1 -1
  141. package/dist/node/wasi/abi.d.ts +82 -0
  142. package/dist/node/wasi/abi.d.ts.map +1 -0
  143. package/dist/node/wasi/abi.js +144 -0
  144. package/dist/node/wasi/abi.js.map +1 -0
  145. package/dist/node/wasi/files.d.ts +67 -0
  146. package/dist/node/wasi/files.d.ts.map +1 -0
  147. package/dist/node/wasi/files.js +319 -0
  148. package/dist/node/wasi/files.js.map +1 -0
  149. package/dist/node/wasi/index.d.ts +17 -0
  150. package/dist/node/wasi/index.d.ts.map +1 -0
  151. package/dist/node/wasi/index.js +129 -0
  152. package/dist/node/wasi/index.js.map +1 -0
  153. package/dist/node/workerThreads.d.ts +31 -0
  154. package/dist/node/workerThreads.d.ts.map +1 -0
  155. package/dist/node/workerThreads.js +165 -0
  156. package/dist/node/workerThreads.js.map +1 -0
  157. package/dist/node/zlib.d.ts.map +1 -1
  158. package/dist/node/zlib.js +23 -2
  159. package/dist/node/zlib.js.map +1 -1
  160. package/dist/shell/context.d.ts.map +1 -1
  161. package/dist/shell/context.js +2 -2
  162. package/dist/shell/context.js.map +1 -1
  163. package/dist/shell/devHandoff.d.ts +10 -4
  164. package/dist/shell/devHandoff.d.ts.map +1 -1
  165. package/dist/shell/devHandoff.js +7 -5
  166. package/dist/shell/devHandoff.js.map +1 -1
  167. package/dist/shell/exec.d.ts.map +1 -1
  168. package/dist/shell/exec.js +6 -5
  169. package/dist/shell/exec.js.map +1 -1
  170. package/dist/shell/npm.js +2 -2
  171. package/dist/shell/npm.js.map +1 -1
  172. package/dist/shell/program.js +5 -5
  173. package/dist/shell/program.js.map +1 -1
  174. package/dist/styleModules.d.ts +2 -5
  175. package/dist/styleModules.d.ts.map +1 -1
  176. package/dist/styleModules.js +23 -14
  177. package/dist/styleModules.js.map +1 -1
  178. package/dist/styles/compile.d.ts +18 -0
  179. package/dist/styles/compile.d.ts.map +1 -0
  180. package/dist/styles/compile.js +34 -0
  181. package/dist/styles/compile.js.map +1 -0
  182. package/dist/styles/compilers.d.ts +75 -0
  183. package/dist/styles/compilers.d.ts.map +1 -0
  184. package/dist/styles/compilers.js +77 -0
  185. package/dist/styles/compilers.js.map +1 -0
  186. package/dist/styles/cssModules.d.ts +40 -0
  187. package/dist/styles/cssModules.d.ts.map +1 -0
  188. package/dist/styles/cssModules.js +239 -0
  189. package/dist/styles/cssModules.js.map +1 -0
  190. package/dist/styles/imports.d.ts +37 -0
  191. package/dist/styles/imports.d.ts.map +1 -0
  192. package/dist/styles/imports.js +88 -0
  193. package/dist/styles/imports.js.map +1 -0
  194. package/dist/styles/languages.d.ts +13 -0
  195. package/dist/styles/languages.d.ts.map +1 -0
  196. package/dist/styles/languages.js +20 -0
  197. package/dist/styles/languages.js.map +1 -0
  198. package/dist/styles/packageStyles.d.ts +19 -0
  199. package/dist/styles/packageStyles.d.ts.map +1 -0
  200. package/dist/styles/packageStyles.js +32 -0
  201. package/dist/styles/packageStyles.js.map +1 -0
  202. package/dist/svelteCompiler.d.ts.map +1 -1
  203. package/dist/svelteCompiler.js +19 -2
  204. package/dist/svelteCompiler.js.map +1 -1
  205. package/dist/system/commands.d.ts +2 -0
  206. package/dist/system/commands.d.ts.map +1 -1
  207. package/dist/system/commands.js +18 -0
  208. package/dist/system/commands.js.map +1 -1
  209. package/dist/system/index.d.ts +3 -1
  210. package/dist/system/index.d.ts.map +1 -1
  211. package/dist/system/index.js +1 -0
  212. package/dist/system/index.js.map +1 -1
  213. package/dist/system/ipc.d.ts +33 -0
  214. package/dist/system/ipc.d.ts.map +1 -0
  215. package/dist/system/ipc.js +65 -0
  216. package/dist/system/ipc.js.map +1 -0
  217. package/dist/system/kernel.d.ts.map +1 -1
  218. package/dist/system/kernel.js +6 -3
  219. package/dist/system/kernel.js.map +1 -1
  220. package/dist/system/process.d.ts +3 -0
  221. package/dist/system/process.d.ts.map +1 -1
  222. package/dist/system/process.js +50 -26
  223. package/dist/system/process.js.map +1 -1
  224. package/dist/system/terminal.d.ts +10 -4
  225. package/dist/system/terminal.d.ts.map +1 -1
  226. package/dist/system/terminal.js +21 -13
  227. package/dist/system/terminal.js.map +1 -1
  228. package/dist/system/types.d.ts +29 -7
  229. package/dist/system/types.d.ts.map +1 -1
  230. package/dist/vueCompiler.d.ts.map +1 -1
  231. package/dist/vueCompiler.js +11 -8
  232. package/dist/vueCompiler.js.map +1 -1
  233. package/package.json +4 -1
  234. package/src/build.ts +13 -1
  235. package/src/buildHost.ts +23 -10
  236. package/src/compileComponent.ts +4 -1
  237. package/src/compileScript.ts +30 -11
  238. package/src/components.ts +5 -0
  239. package/src/detectProject.ts +13 -6
  240. package/src/devServer.ts +148 -23
  241. package/src/devStyles.ts +70 -0
  242. package/src/hot/client.ts +70 -0
  243. package/src/hot/moduleGraph.ts +90 -0
  244. package/src/hot/planUpdate.ts +66 -0
  245. package/src/hot/reactRefresh.ts +93 -0
  246. package/src/html.ts +13 -19
  247. package/src/index.ts +19 -1
  248. package/src/installer/tree.ts +32 -5
  249. package/src/installer/wasmBuilds.ts +60 -0
  250. package/src/node/builtins.ts +23 -12
  251. package/src/node/childProcess.ts +73 -20
  252. package/src/node/crypto.ts +5 -4
  253. package/src/node/esm.ts +26 -2
  254. package/src/node/fs/index.ts +26 -103
  255. package/src/node/fs/stdinFd.ts +44 -0
  256. package/src/node/fs/streams.ts +177 -0
  257. package/src/node/fs/sync.ts +15 -0
  258. package/src/node/globalObject.ts +82 -0
  259. package/src/node/http/index.ts +4 -3
  260. package/src/node/http/server.ts +8 -5
  261. package/src/node/http/serverResponse.ts +7 -0
  262. package/src/node/ipc.ts +91 -0
  263. package/src/node/loader.ts +78 -14
  264. package/src/node/misc.ts +19 -6
  265. package/src/node/process.ts +15 -8
  266. package/src/node/processExit.ts +21 -0
  267. package/src/node/program.ts +12 -9
  268. package/src/node/runtime.ts +27 -15
  269. package/src/node/stream/readable.ts +2 -1
  270. package/src/node/urlqs.ts +10 -2
  271. package/src/node/wasi/abi.ts +151 -0
  272. package/src/node/wasi/files.ts +350 -0
  273. package/src/node/wasi/index.ts +149 -0
  274. package/src/node/workerThreads.ts +198 -0
  275. package/src/node/zlib.ts +24 -2
  276. package/src/shell/context.ts +2 -2
  277. package/src/shell/devHandoff.ts +16 -9
  278. package/src/shell/exec.ts +6 -5
  279. package/src/shell/npm.ts +2 -2
  280. package/src/shell/program.ts +5 -5
  281. package/src/styleModules.ts +30 -14
  282. package/src/styles/compile.ts +43 -0
  283. package/src/styles/compilers.ts +143 -0
  284. package/src/styles/cssModules.ts +254 -0
  285. package/src/styles/imports.ts +125 -0
  286. package/src/styles/languages.ts +29 -0
  287. package/src/styles/packageStyles.ts +35 -0
  288. package/src/svelteCompiler.ts +20 -3
  289. package/src/system/commands.ts +17 -0
  290. package/src/system/index.ts +4 -0
  291. package/src/system/ipc.ts +89 -0
  292. package/src/system/kernel.ts +6 -3
  293. package/src/system/process.ts +57 -30
  294. package/src/system/terminal.ts +34 -12
  295. package/src/system/types.ts +31 -7
  296. package/src/vueCompiler.ts +11 -8
@@ -4,7 +4,8 @@
4
4
  * `path` and `process` close over that process's cwd, IO and event loop.
5
5
  */
6
6
  import type { VirtualFileSystem } from '../vfs.js';
7
- import type { ProgramIO, System } from '../system/types.js';
7
+ import type { ProgramIO, StdioChunk, System, ThreadInfo } from '../system/types.js';
8
+ import type { IpcEndpoint } from '../system/ipc.js';
8
9
  import type { EventLoop } from './loop.js';
9
10
  import type { NodeProcess } from './process.js';
10
11
  import { createEventsModule } from './events.js';
@@ -13,13 +14,16 @@ import { createPathModule } from './path.js';
13
14
  import { createUtilModule, types as utilTypes } from './util.js';
14
15
  import { createStreamModule } from './stream/index.js';
15
16
  import { createFsModule } from './fs/index.js';
17
+ import { createStdinRead } from './fs/stdinFd.js';
16
18
  import { constants as fsConstants } from './fs/stats.js';
17
19
  import { createCryptoModule } from './crypto.js';
18
20
  import { createQuerystringModule, createUrlModule } from './urlqs.js';
21
+ import { createWasiModule } from './wasi/index.js';
19
22
  import { createAssertModule } from './assert.js';
20
23
  import { createZlibModule } from './zlib.js';
21
24
  import { createHttpModule, createNetModule, createFetch } from './http/index.js';
22
25
  import { createChildProcessModule } from './childProcess.js';
26
+ import { createWorkerThreadsModule } from './workerThreads.js';
23
27
  import { createReadlineModule } from './readline.js';
24
28
  import { createAsyncHooksModule, createDiagnosticsChannelModule, createOsModule, createStringDecoderModule, createStubModules, createTimersModule, createTtyModule, createVmModule } from './misc.js';
25
29
 
@@ -31,6 +35,10 @@ export interface BuiltinDeps {
31
35
  system: System;
32
36
  io: ProgramIO;
33
37
  console: Console;
38
+ /** Set when this process is a worker thread (`worker_threads.isMainThread` false). */
39
+ thread?: ThreadInfo;
40
+ /** The process's channel to its parent: a worker thread's `parentPort`. */
41
+ ipc?: IpcEndpoint;
34
42
  }
35
43
 
36
44
  type Factory = (get: (name: string) => any) => unknown;
@@ -40,28 +48,30 @@ export function createBuiltins(deps: BuiltinDeps) {
40
48
  const env = () => proc.env as Record<string, string | undefined>;
41
49
  const stubs = createStubModules();
42
50
  const clientDeps = { system, loop };
51
+ /** What starting other processes needs: child_process and worker_threads alike. */
52
+ const spawnDeps = {
53
+ system,
54
+ loop,
55
+ cwd: () => proc.cwd() as string,
56
+ env,
57
+ stdout: (c: StdioChunk) => void proc.stdout.write(c),
58
+ stderr: (c: StdioChunk) => void proc.stderr.write(c),
59
+ };
43
60
 
44
61
  const factories: Record<string, Factory> = {
45
62
  assert: () => createAssertModule(false),
46
63
  'assert/strict': () => createAssertModule(true),
47
64
  async_hooks: () => createAsyncHooksModule(),
48
65
  buffer: () => createBufferModule(),
49
- child_process: () =>
50
- createChildProcessModule({
51
- system,
52
- loop,
53
- cwd: () => proc.cwd(),
54
- env,
55
- stdout: (c) => proc.stdout.write(c),
56
- stderr: (c) => proc.stderr.write(c),
57
- }),
66
+ child_process: () => createChildProcessModule(spawnDeps),
67
+ worker_threads: () => createWorkerThreadsModule({ ...spawnDeps, thread: deps.thread, ipc: deps.ipc }),
58
68
  console: () => Object.assign(Object.create(deps.console), { Console: function Console() { return deps.console; } }),
59
69
  constants: (get) => ({ ...fsConstants, ...(get('os').constants.signals as object) }),
60
70
  crypto: () => createCryptoModule(),
61
71
  diagnostics_channel: () => createDiagnosticsChannelModule(),
62
72
  'dns/promises': (get) => get('dns').promises,
63
73
  events: () => createEventsModule(),
64
- fs: () => createFsModule({ vfs: deps.fs, cwd: () => proc.cwd(), stdout: deps.io.stdout, stderr: deps.io.stderr, hold: () => loop.hold() }),
74
+ fs: () => createFsModule({ vfs: deps.fs, cwd: () => proc.cwd(), stdout: deps.io.stdout, stderr: deps.io.stderr, hold: () => loop.hold(), readStdin: createStdinRead(deps.io, () => loop.hold()) }),
65
75
  'fs/promises': (get) => get('fs').promises,
66
76
  http: () => createHttpModule(clientDeps, 'http:'),
67
77
  https: () => createHttpModule(clientDeps, 'https:'),
@@ -94,10 +104,11 @@ export function createBuiltins(deps: BuiltinDeps) {
94
104
  timers: () => createTimersModule(loop),
95
105
  'timers/promises': (get) => get('timers').promises,
96
106
  tty: () => createTtyModule(!!deps.io.terminal),
97
- url: (get) => createUrlModule(get('querystring')),
107
+ url: (get) => createUrlModule(get('querystring'), (path) => get('path').resolve(path)),
98
108
  util: () => createUtilModule(env, (message) => proc.stderr.write(message + '\n')),
99
109
  'util/types': () => utilTypes,
100
110
  vm: () => createVmModule(),
111
+ wasi: (get) => createWasiModule({ fs: get('fs'), stdout: (bytes) => void proc.stdout.write(bytes), stderr: (bytes) => void proc.stderr.write(bytes), exit: (code) => proc.exit(code) }),
101
112
  zlib: () => createZlibModule(),
102
113
  };
103
114
  for (const [name, mod] of Object.entries(stubs)) factories[name] ??= () => mod;
@@ -9,7 +9,10 @@ import { EventEmitterBase } from './events.js';
9
9
  import { Readable } from './stream/readable.js';
10
10
  import { Writable } from './stream/writable.js';
11
11
  import type { EventLoop } from './loop.js';
12
- import type { ChildHandle, System } from '../system/types.js';
12
+ import type { ChildHandle, StdioChunk, System } from '../system/types.js';
13
+ import { Buffer } from './buffer.js';
14
+ import type { IpcEndpoint } from '../system/ipc.js';
15
+ import { queueCallback } from './processExit.js';
13
16
 
14
17
  interface SpawnOptions {
15
18
  cwd?: string;
@@ -19,6 +22,12 @@ interface SpawnOptions {
19
22
  signal?: AbortSignal;
20
23
  encoding?: string;
21
24
  maxBuffer?: number;
25
+ /** `fork`: open a message channel (`child.send` ↔ `process.send`). */
26
+ ipc?: boolean;
27
+ /** `fork`: pipe the child's stdout/stderr to `child.stdout`/`stderr` instead of the parent's. */
28
+ silent?: boolean;
29
+ /** Keep running after this process exits (otherwise it is killed with it). */
30
+ detached?: boolean;
22
31
  }
23
32
 
24
33
  export interface ChildProcessDeps {
@@ -27,8 +36,8 @@ export interface ChildProcessDeps {
27
36
  cwd(): string;
28
37
  env(): Record<string, string | undefined>;
29
38
  /** Parent's stdio for `stdio: 'inherit'`. */
30
- stdout(chunk: string): void;
31
- stderr(chunk: string): void;
39
+ stdout(chunk: StdioChunk): void;
40
+ stderr(chunk: StdioChunk): void;
32
41
  }
33
42
 
34
43
  const quote = (arg: string) => (/^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`);
@@ -46,6 +55,11 @@ class ChildProcess extends EventEmitterBase {
46
55
  stderr: Readable;
47
56
  stdio: [Writable, Readable, Readable];
48
57
  private handle?: ChildHandle;
58
+ private ipc?: IpcEndpoint;
59
+ /** Lets go of the parent's event loop; undefined once released (exit, or `unref()`). */
60
+ private release?: () => void;
61
+ private exited = false;
62
+ private readonly hold: () => () => void;
49
63
 
50
64
  constructor(deps: ChildProcessDeps, command: string, args: string[], options: SpawnOptions) {
51
65
  super();
@@ -55,7 +69,7 @@ class ChildProcess extends EventEmitterBase {
55
69
  this.stderr = new Readable({ read() {} });
56
70
  this.stdin = new Writable({
57
71
  write: (chunk: Uint8Array | string, _enc: string, cb: () => void) => {
58
- this.handle?.write(typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk));
72
+ this.handle?.write(typeof chunk === 'string' ? chunk : new Uint8Array(chunk)); // bytes stay bytes
59
73
  cb();
60
74
  },
61
75
  final: (cb: () => void) => {
@@ -64,30 +78,45 @@ class ChildProcess extends EventEmitterBase {
64
78
  },
65
79
  });
66
80
  this.stdio = [this.stdin, this.stdout, this.stderr];
67
- const inherit = options.stdio === 'inherit' || (Array.isArray(options.stdio) && options.stdio[1] === 'inherit');
81
+ // Per stream, as Node reads it: `'inherit'`, or `['pipe', 'pipe', 'inherit']` (esbuild's service: its stderr is the parent's).
82
+ const inherits = (fd: 1 | 2) => options.stdio === 'inherit' || (Array.isArray(options.stdio) && options.stdio[fd] === 'inherit');
83
+ const [inheritOut, inheritErr] = [inherits(1), inherits(2)];
68
84
 
69
85
  const env: Record<string, string> = {};
70
86
  for (const [k, v] of Object.entries(options.env ?? deps.env())) if (v !== undefined) env[k] = String(v);
71
87
  const [file, argv] = options.shell ? ['bfsh', ['-c', [command, ...args].join(' ')]] : [command, args];
72
- const release = deps.loop.hold();
88
+ this.hold = () => deps.loop.hold();
89
+ this.release = this.hold();
73
90
  try {
74
- this.handle = deps.system.spawn(file, argv, { cwd: options.cwd ?? deps.cwd(), env });
91
+ this.handle = deps.system.spawn(file, argv, { cwd: options.cwd ?? deps.cwd(), env, ipc: options.ipc, detached: options.detached });
75
92
  } catch (error) {
76
- release();
93
+ this.unref();
77
94
  const code = (error as { code?: string }).code ?? 'ENOENT';
78
95
  const failure = Object.assign(new Error(`spawn ${command} ${code}`), { code, errno: -2, syscall: `spawn ${command}`, path: command, spawnargs: args });
79
- queueMicrotask(() => {
96
+ queueCallback(() => {
80
97
  this.emit('error', failure);
81
98
  this.emit('close', -2, null);
82
99
  });
83
100
  return;
84
101
  }
85
102
  this.pid = this.handle.pid;
86
- this.handle.onStdout((chunk) => (inherit ? deps.stdout(chunk) : this.stdout.push(chunk)));
87
- this.handle.onStderr((chunk) => (inherit ? deps.stderr(chunk) : this.stderr.push(chunk)));
103
+ const ipc = this.handle.ipc;
104
+ if (ipc) {
105
+ this.ipc = ipc;
106
+ this.connected = true;
107
+ ipc.onMessage((message) => deps.loop._run(() => this.emit('message', message, undefined)));
108
+ ipc.onDisconnect(() => {
109
+ this.connected = false;
110
+ deps.loop._run(() => this.emit('disconnect'));
111
+ });
112
+ }
113
+ // Piped output arrives as Buffers, as in Node.
114
+ this.handle.onStdout((chunk) => (inheritOut ? deps.stdout(chunk) : this.stdout.push(Buffer.from(chunk))));
115
+ this.handle.onStderr((chunk) => (inheritErr ? deps.stderr(chunk) : this.stderr.push(Buffer.from(chunk))));
88
116
  options.signal?.addEventListener('abort', () => this.kill());
89
- queueMicrotask(() => this.emit('spawn'));
117
+ queueCallback(() => this.emit('spawn'));
90
118
  void this.handle.exit.then((code) => {
119
+ this.exited = true;
91
120
  this.exitCode = this.killed ? null : code;
92
121
  this.stdout.push(null);
93
122
  this.stderr.push(null);
@@ -95,7 +124,7 @@ class ChildProcess extends EventEmitterBase {
95
124
  this.emit('exit', this.exitCode, this.signalCode);
96
125
  this.emit('close', this.exitCode, this.signalCode);
97
126
  });
98
- release();
127
+ this.unref();
99
128
  });
100
129
  }
101
130
 
@@ -107,12 +136,33 @@ class ChildProcess extends EventEmitterBase {
107
136
  return true;
108
137
  }
109
138
 
110
- send(): boolean {
111
- throw Object.assign(new Error('IPC channels are not supported in the browser runtime'), { code: 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM' });
139
+ send(message: unknown, ...rest: unknown[]): boolean {
140
+ const callback = rest.find((arg): arg is (error: Error | null) => void => typeof arg === 'function');
141
+ const fail = (error: Error) => {
142
+ if (callback) queueCallback(() => callback(error));
143
+ else queueCallback(() => this.emit('error', error));
144
+ return false;
145
+ };
146
+ if (!this.ipc) return fail(Object.assign(new Error('Channel closed'), { code: 'ERR_IPC_CHANNEL_CLOSED' }));
147
+ try {
148
+ this.ipc.send(message);
149
+ } catch (error) {
150
+ return fail(error as Error);
151
+ }
152
+ if (callback) queueCallback(() => callback(null));
153
+ return true;
154
+ }
155
+ disconnect(): void {
156
+ this.ipc?.disconnect();
157
+ }
158
+ /** A running child keeps the parent alive until `unref()` (then `ref()` to hold it again). */
159
+ ref(): void {
160
+ if (!this.release && this.handle && !this.exited) this.release = this.hold();
161
+ }
162
+ unref(): void {
163
+ this.release?.();
164
+ this.release = undefined;
112
165
  }
113
- disconnect(): void {}
114
- ref(): void {}
115
- unref(): void {}
116
166
  }
117
167
 
118
168
  type ExecCallback = (error: (Error & { code?: number | string }) | null, stdout: string, stderr: string) => void;
@@ -152,9 +202,12 @@ export function createChildProcessModule(deps: ChildProcessDeps): Record<string,
152
202
  if (typeof options === 'function') [callback, options] = [options, {}];
153
203
  return collect(new ChildProcess(deps, file, args, options ?? {}), [file, ...args].map(quote).join(' '), callback);
154
204
  },
155
- fork(modulePath: string, args?: string[] | SpawnOptions, options?: SpawnOptions) {
205
+ fork(modulePath: string, args?: string[] | SpawnOptions, options?: SpawnOptions & { execArgv?: string[] }) {
156
206
  if (!Array.isArray(args)) [options, args] = [args, []];
157
- return new ChildProcess(deps, 'node', [modulePath, ...args], options ?? {});
207
+ const opts = options ?? {};
208
+ // A forked child shares the parent's stdout/stderr unless `silent`, as in Node.
209
+ const stdio = opts.stdio ?? (opts.silent ? 'pipe' : 'inherit');
210
+ return new ChildProcess(deps, 'node', [...(opts.execArgv ?? []), modulePath, ...args.map(String)], { ...opts, stdio, ipc: true });
158
211
  },
159
212
  execSync: noSync('execSync'),
160
213
  execFileSync: noSync('execFileSync'),
@@ -7,6 +7,7 @@
7
7
  import { Buffer } from './buffer.js';
8
8
  import { hashAlgorithm, HASHES } from './hashes.js';
9
9
  import { Transform } from './stream/index.js';
10
+ import { queueCallback } from './processExit.js';
10
11
 
11
12
  type Input = string | ArrayBufferView;
12
13
 
@@ -123,7 +124,7 @@ const unsupported = (name: string) => () => {
123
124
  export function createCryptoModule(): Record<string, unknown> {
124
125
  const randomBytes = (size: number, callback?: (error: Error | null, buf: Buffer) => void) => {
125
126
  const buf = randomFill(Buffer.alloc(size));
126
- if (callback) queueMicrotask(() => callback(null, buf));
127
+ if (callback) queueCallback(() => callback(null, buf));
127
128
  return buf;
128
129
  };
129
130
  return {
@@ -142,13 +143,13 @@ export function createCryptoModule(): Record<string, unknown> {
142
143
  randomFill: (view: ArrayBufferView, ...rest: unknown[]) => {
143
144
  const callback = rest.pop() as (e: Error | null, v: ArrayBufferView) => void;
144
145
  randomFill(view);
145
- queueMicrotask(() => callback(null, view));
146
+ queueCallback(() => callback(null, view));
146
147
  },
147
148
  randomUUID: () => globalThis.crypto.randomUUID(),
148
149
  randomInt(min: number, max?: number | ((e: Error | null, n: number) => void), callback?: (e: Error | null, n: number) => void) {
149
150
  if (typeof max !== 'number') [callback, max, min] = [max as typeof callback, min, 0];
150
151
  const value = min + Math.floor((globalThis.crypto.getRandomValues(new Uint32Array(1))[0]! / 2 ** 32) * (max - min));
151
- if (callback) queueMicrotask(() => callback!(null, value));
152
+ if (callback) queueCallback(() => callback!(null, value));
152
153
  return value;
153
154
  },
154
155
  getRandomValues: <T extends ArrayBufferView>(view: T) => randomFill(view),
@@ -162,7 +163,7 @@ export function createCryptoModule(): Record<string, unknown> {
162
163
  },
163
164
  pbkdf2Sync,
164
165
  pbkdf2(password: Input, salt: Input, iterations: number, keylen: number, digest: string, callback: (e: Error | null, key?: Buffer) => void) {
165
- queueMicrotask(() => {
166
+ queueCallback(() => {
166
167
  try {
167
168
  callback(null, pbkdf2Sync(password, salt, iterations, keylen, digest));
168
169
  } catch (error) {
package/src/node/esm.ts CHANGED
@@ -98,6 +98,30 @@ function exportKeywordBefore(source: string, pos: number): number {
98
98
  return -1;
99
99
  }
100
100
 
101
+ /**
102
+ * `import(x)` inside a CommonJS module. Left alone it would be the HOST's native
103
+ * `import()`, resolving against the runtime's own files instead of the project's
104
+ * (Next.js's CLI loads its commands this way); pointed at `__bfwc_dynamic` it goes
105
+ * through this runtime's loader like everything else.
106
+ */
107
+ export function rewriteDynamicImports(source: string): string {
108
+ if (!/\bimport\s*\(/.test(source)) return source;
109
+ let imports: ReturnType<typeof parse>[0];
110
+ try {
111
+ [imports] = parse(source);
112
+ } catch {
113
+ return source; // not lexable as a module; leave it to fail (or not) as written
114
+ }
115
+ let out = '';
116
+ let cursor = 0;
117
+ for (const imp of imports) {
118
+ if (imp.t !== 2) continue;
119
+ out += source.slice(cursor, imp.ss) + '__bfwc_dynamic';
120
+ cursor = imp.d;
121
+ }
122
+ return cursor ? out + source.slice(cursor) : source;
123
+ }
124
+
101
125
  export function esmToCjs(source: string): string {
102
126
  const [imports, exports] = parse(source);
103
127
  const edits: Edit[] = [];
@@ -125,7 +149,7 @@ export function esmToCjs(source: string): string {
125
149
  reexportStarts.add(imp.ss);
126
150
  const nsMatch = /^export\s*\*\s*as\s+("[^"]*"|'[^']*'|[^\s]+)/.exec(statement);
127
151
  if (nsMatch) getters.set(nsMatch[1]!.replace(/^["']|["']$/g, ''), ns);
128
- else if (/^export\s*\*/.test(statement)) edits.push({ start: imp.ss, end: imp.se, text: `${load} __bfwc_star(exports, ${ns});` });
152
+ else if (/^export\s*\*/.test(statement)) edits.push({ start: imp.ss, end: imp.se, text: `${load} __bfwc_star(__bfwc_exports, ${ns});` });
129
153
  else for (const [imported, exported] of parseList(/\{([^}]*)\}/.exec(statement)?.[1] ?? '')) getters.set(exported, access(ns, imported));
130
154
  if (!edits.some((e) => e.start === imp.ss)) edits.push({ start: imp.ss, end: imp.se, text: load });
131
155
  continue;
@@ -192,5 +216,5 @@ export function esmToCjs(source: string): string {
192
216
  for (const edit of edits) code = code.slice(0, edit.start) + edit.text + code.slice(edit.end);
193
217
  const getterList = [...getters].map(([name, expr]) => `${JSON.stringify(name)}: () => ${expr}`).join(', ');
194
218
  // One line, so stack-trace line numbers stay aligned with the source.
195
- return `"use strict";__bfwc_esm(exports, { ${getterList} });${code}`;
219
+ return `"use strict";__bfwc_esm(__bfwc_exports, { ${getterList} });${code}`;
196
220
  }
@@ -8,21 +8,22 @@
8
8
  * cut short by the process exiting.
9
9
  */
10
10
  import { EventEmitterBase } from '../events.js';
11
- import { Buffer } from '../buffer.js';
12
- import { Readable } from '../stream/readable.js';
13
- import { Writable } from '../stream/writable.js';
14
11
  import { createSyncFs, type FsContext, type SyncFs } from './sync.js';
12
+ import { createFsStreams } from './streams.js';
15
13
  import { Dirent, Stats, constants } from './stats.js';
16
14
  import { normalizePath } from '../../paths.js';
15
+ import { queueCallback } from '../processExit.js';
16
+ import type { StdinRead } from './stdinFd.js';
17
17
 
18
18
  export interface FsModuleContext extends FsContext {
19
19
  /** Keep the process alive (a watcher is open); call the result to let go. */
20
20
  hold(): () => void;
21
+ /** fd 0 for `fs.read`: this process's stdin (stdinFd.ts). */
22
+ readStdin?: StdinRead;
21
23
  }
22
24
 
23
25
  type Fn = (...args: any[]) => any;
24
26
 
25
- const CHUNK = 64 * 1024;
26
27
 
27
28
  function lastCallback(args: unknown[]): Fn | undefined {
28
29
  return typeof args[args.length - 1] === 'function' ? (args.pop() as Fn) : undefined;
@@ -34,7 +35,7 @@ export function createFsModule(ctx: FsModuleContext): Record<string, any> {
34
35
  const toCallback = (fn: Fn, shape: (result: any, args: any[]) => any[] = (r) => [r]) =>
35
36
  (...args: any[]) => {
36
37
  const cb = lastCallback(args);
37
- queueMicrotask(() => {
38
+ queueCallback(() => {
38
39
  let result: unknown;
39
40
  try {
40
41
  result = fn(...args);
@@ -48,101 +49,7 @@ export function createFsModule(ctx: FsModuleContext): Record<string, any> {
48
49
 
49
50
  const toPromise = (fn: Fn) => async (...args: any[]) => fn(...args);
50
51
 
51
- class ReadStream extends Readable {
52
- bytesRead = 0;
53
- readonly path: string;
54
- fd: number | null = null;
55
- pending = true;
56
- private data?: Uint8Array;
57
- private offset: number;
58
- private readonly endAt: number;
59
-
60
- constructor(path: string | URL, options: { start?: number; end?: number; encoding?: string; highWaterMark?: number; fd?: number } | string = {}) {
61
- const opts = typeof options === 'string' ? { encoding: options } : options;
62
- super({ highWaterMark: opts.highWaterMark ?? CHUNK, encoding: opts.encoding });
63
- this.path = typeof options === 'object' && opts.fd !== undefined ? '' : sync._resolve(path);
64
- this.offset = opts.start ?? 0;
65
- this.endAt = opts.end ?? Infinity;
66
- queueMicrotask(() => {
67
- try {
68
- const contents = sync.readFileSync(this.path) as Buffer;
69
- this.data = contents;
70
- this.fd = -1;
71
- this.pending = false;
72
- this.emit('open', this.fd);
73
- this.emit('ready');
74
- this._pull();
75
- } catch (error) {
76
- this.destroy(error as Error);
77
- }
78
- });
79
- }
80
-
81
- override _read(): void {
82
- if (!this.data) {
83
- this._readableState.reading = false; // retried once the file is loaded
84
- return;
85
- }
86
- const end = Math.min(this.data.length, this.endAt + 1);
87
- if (this.offset >= end) {
88
- this.push(null);
89
- return;
90
- }
91
- const chunk = this.data.subarray(this.offset, Math.min(end, this.offset + this._readableState.highWaterMark));
92
- this.offset += chunk.length;
93
- this.bytesRead += chunk.length;
94
- this.push(Buffer.from(chunk));
95
- }
96
-
97
- close(callback?: Fn): void {
98
- this.destroy();
99
- if (callback) this.once('close', callback);
100
- }
101
- }
102
-
103
- class WriteStream extends Writable {
104
- bytesWritten = 0;
105
- readonly path: string;
106
- pending = false;
107
- private started = false;
108
-
109
- constructor(path: string | URL, private readonly options: { flags?: string; encoding?: string } | string = {}) {
110
- super({ decodeStrings: true });
111
- this.path = sync._resolve(path);
112
- queueMicrotask(() => {
113
- try {
114
- this.open();
115
- this.emit('open', -1);
116
- this.emit('ready');
117
- } catch (error) {
118
- this.destroy(error as Error);
119
- }
120
- });
121
- }
122
-
123
- private open(): void {
124
- if (this.started) return;
125
- this.started = true;
126
- const flags = typeof this.options === 'object' ? this.options.flags ?? 'w' : 'w';
127
- if (!flags.startsWith('a') || !ctx.vfs.isFile(this.path)) sync.writeFileSync(this.path, '', { flag: flags.includes('x') ? 'wx' : 'w' });
128
- }
129
-
130
- override _write(chunk: Buffer, _encoding: string, callback: (error?: Error | null) => void): void {
131
- try {
132
- this.open();
133
- sync.appendFileSync(this.path, chunk);
134
- this.bytesWritten += chunk.length;
135
- callback();
136
- } catch (error) {
137
- callback(error as Error);
138
- }
139
- }
140
-
141
- close(callback?: Fn): void {
142
- this.end();
143
- if (callback) this.once('close', callback);
144
- }
145
- }
52
+ const { ReadStream, WriteStream } = createFsStreams(sync, ctx);
146
53
 
147
54
  class FSWatcher extends EventEmitterBase {
148
55
  private readonly release: () => void;
@@ -217,11 +124,25 @@ export function createFsModule(ctx: FsModuleContext): Record<string, any> {
217
124
  if (!name.endsWith('Sync')) continue;
218
125
  const base = name.slice(0, -4);
219
126
  const fn = (sync as unknown as Record<string, Fn>)[name]!;
220
- if (base === 'exists') fs.exists = (p: string, cb: Fn) => queueMicrotask(() => cb(sync.existsSync(p)));
221
- else if (base === 'read') fs.read = toCallback(fn, (n, args) => [n, args[1]]);
222
- else if (base === 'write') fs.write = toCallback(fn, (n, args) => [n, args[1]]);
127
+ if (base === 'exists') fs.exists = (p: string, cb: Fn) => queueCallback(() => cb(sync.existsSync(p)));
128
+ // (err, bytes, buffer|buffers), as Node's callbacks report them.
129
+ else if (['read', 'write', 'readv', 'writev'].includes(base)) fs[base] = toCallback(fn, (n, args) => [n, args[1]]);
223
130
  else fs[base] = toCallback(fn);
224
131
  }
132
+ const readFile = fs.read;
133
+ // `fs.read(0, …)` reads stdin: it waits for input instead of failing with EBADF.
134
+ fs.read = (fd: number, ...args: any[]) => {
135
+ if (fd !== 0 || !ctx.readStdin) return readFile(fd, ...args);
136
+ const cb = lastCallback(args);
137
+ const options = args[0] && !ArrayBuffer.isView(args[0]) ? args[0] : typeof args[1] === 'object' && args[1] ? { buffer: args[0], ...args[1] } : { buffer: args[0], offset: args[1], length: args[2] };
138
+ const buffer = options.buffer as ArrayBufferView;
139
+ const offset = Number(options.offset ?? 0);
140
+ const length = Number(options.length ?? buffer.byteLength - offset);
141
+ void ctx.readStdin(new Uint8Array(buffer.buffer, buffer.byteOffset + offset, length)).then(
142
+ (count) => queueCallback(() => cb?.(null, count, buffer)),
143
+ (error: unknown) => queueCallback(() => cb?.(error, 0, buffer)),
144
+ );
145
+ };
225
146
  fs.realpath.native = fs.realpath;
226
147
  fs.createReadStream = (path: string, options?: object | string) => new ReadStream(path, options as object);
227
148
  fs.createWriteStream = (path: string, options?: object | string) => new WriteStream(path, options as object);
@@ -248,6 +169,8 @@ function fileHandle(sync: SyncFs, fd: number, path: string) {
248
169
  appendFile: async (data: string | Uint8Array) => void sync.appendFileSync(path, data),
249
170
  read: async (buffer: Uint8Array, offset?: number, length?: number, position?: number | null) => ({ bytesRead: sync.readSync(fd, buffer, offset, length, position), buffer }),
250
171
  write: async (data: string | Uint8Array, ...rest: any[]) => ({ bytesWritten: sync.writeSync(fd, data, ...rest), buffer: data }),
172
+ writev: async (buffers: Uint8Array[], position?: number | null) => ({ bytesWritten: sync.writevSync(fd, buffers, position), buffers }),
173
+ readv: async (buffers: Uint8Array[], position?: number | null) => ({ bytesRead: sync.readvSync(fd, buffers, position), buffers }),
251
174
  stat: async () => sync.fstatSync(fd),
252
175
  truncate: async (length?: number) => sync.ftruncateSync(fd, length),
253
176
  sync: async () => undefined,
@@ -0,0 +1,44 @@
1
+ /**
2
+ * fd 0 as a file: `fs.read(0, buffer, …, callback)` waits for the process's stdin
3
+ * and fills the buffer from it, as on a pipe. Go's WebAssembly runtime reads its
4
+ * input this way (esbuild-wasm's service process, which Vite drives).
5
+ */
6
+ import type { ProgramIO } from '../../system/types.js';
7
+
8
+ /** Read up to `into.length` bytes of stdin; resolves 0 at end of input. */
9
+ export type StdinRead = (into: Uint8Array) => Promise<number>;
10
+
11
+ export function createStdinRead(io: ProgramIO, hold: () => () => void): StdinRead {
12
+ const chunks: Uint8Array[] = [];
13
+ let ended = false;
14
+ let wake: Array<() => void> = [];
15
+ let subscribed = false;
16
+
17
+ const subscribe = () => {
18
+ if (subscribed) return;
19
+ subscribed = true;
20
+ io.onStdin((chunk) => {
21
+ if (chunk === null) ended = true;
22
+ else chunks.push(typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk);
23
+ const waiting = wake;
24
+ wake = [];
25
+ for (const resume of waiting) resume();
26
+ });
27
+ };
28
+
29
+ return async (into) => {
30
+ subscribe();
31
+ while (!chunks.length && !ended) {
32
+ const release = hold(); // a pending read keeps the process alive, as Node's does
33
+ await new Promise<void>((resolve) => wake.push(resolve));
34
+ release();
35
+ }
36
+ const head = chunks[0];
37
+ if (!head) return 0;
38
+ const count = Math.min(head.length, into.length);
39
+ into.set(head.subarray(0, count));
40
+ if (count === head.length) chunks.shift();
41
+ else chunks[0] = head.subarray(count);
42
+ return count;
43
+ };
44
+ }