@seanhogg/builderforce-webcontainers-core 2026.10.11 → 2026.10.13

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 (199) hide show
  1. package/dist/archive.d.ts +25 -2
  2. package/dist/archive.d.ts.map +1 -1
  3. package/dist/archive.js +45 -6
  4. package/dist/archive.js.map +1 -1
  5. package/dist/attribution.js.map +1 -1
  6. package/dist/check/acquire.js.map +1 -1
  7. package/dist/check/typeStore.d.ts.map +1 -1
  8. package/dist/compileScript.js.map +1 -1
  9. package/dist/devServer.d.ts +2 -0
  10. package/dist/devServer.d.ts.map +1 -1
  11. package/dist/devServer.js +2 -2
  12. package/dist/devServer.js.map +1 -1
  13. package/dist/hot/moduleGraph.d.ts.map +1 -1
  14. package/dist/html.d.ts +5 -2
  15. package/dist/html.d.ts.map +1 -1
  16. package/dist/html.js +9 -7
  17. package/dist/html.js.map +1 -1
  18. package/dist/index.d.ts +3 -3
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +2 -2
  21. package/dist/index.js.map +1 -1
  22. package/dist/installer/npmrc.js.map +1 -1
  23. package/dist/installer/registry.d.ts.map +1 -1
  24. package/dist/installer/registry.js.map +1 -1
  25. package/dist/installer/semver.js.map +1 -1
  26. package/dist/installer/tree.d.ts +2 -2
  27. package/dist/installer/tree.d.ts.map +1 -1
  28. package/dist/node/assert.d.ts.map +1 -1
  29. package/dist/node/buffer.d.ts.map +1 -1
  30. package/dist/node/buffer.js.map +1 -1
  31. package/dist/node/callable.js.map +1 -1
  32. package/dist/node/crypto.d.ts.map +1 -1
  33. package/dist/node/crypto.js +6 -2
  34. package/dist/node/crypto.js.map +1 -1
  35. package/dist/node/events.d.ts.map +1 -1
  36. package/dist/node/events.js.map +1 -1
  37. package/dist/node/fs/index.js.map +1 -1
  38. package/dist/node/fs/stats.d.ts.map +1 -1
  39. package/dist/node/fs/stats.js.map +1 -1
  40. package/dist/node/fs/sync.d.ts +1 -1
  41. package/dist/node/fs/sync.d.ts.map +1 -1
  42. package/dist/node/fs/sync.js.map +1 -1
  43. package/dist/node/hostClock.d.ts +14 -0
  44. package/dist/node/hostClock.d.ts.map +1 -0
  45. package/dist/node/hostClock.js +15 -0
  46. package/dist/node/hostClock.js.map +1 -0
  47. package/dist/node/http/client.d.ts.map +1 -1
  48. package/dist/node/http/client.js.map +1 -1
  49. package/dist/node/http/index.js.map +1 -1
  50. package/dist/node/http/messages.d.ts.map +1 -1
  51. package/dist/node/http/messages.js.map +1 -1
  52. package/dist/node/http/server.d.ts.map +1 -1
  53. package/dist/node/http/server.js +10 -1
  54. package/dist/node/http/server.js.map +1 -1
  55. package/dist/node/http/serverResponse.d.ts +2 -1
  56. package/dist/node/http/serverResponse.d.ts.map +1 -1
  57. package/dist/node/http/serverResponse.js +4 -2
  58. package/dist/node/http/serverResponse.js.map +1 -1
  59. package/dist/node/http/upgradeSocket.d.ts.map +1 -1
  60. package/dist/node/http/upgradeSocket.js.map +1 -1
  61. package/dist/node/inspect.d.ts +2 -2
  62. package/dist/node/inspect.d.ts.map +1 -1
  63. package/dist/node/inspect.js.map +1 -1
  64. package/dist/node/loader.d.ts.map +1 -1
  65. package/dist/node/loader.js.map +1 -1
  66. package/dist/node/loop.d.ts.map +1 -1
  67. package/dist/node/loop.js.map +1 -1
  68. package/dist/node/misc.d.ts.map +1 -1
  69. package/dist/node/misc.js +3 -2
  70. package/dist/node/misc.js.map +1 -1
  71. package/dist/node/process.d.ts.map +1 -1
  72. package/dist/node/process.js +9 -8
  73. package/dist/node/process.js.map +1 -1
  74. package/dist/node/processExit.d.ts.map +1 -1
  75. package/dist/node/processExit.js.map +1 -1
  76. package/dist/node/readline.js.map +1 -1
  77. package/dist/node/resolve.d.ts +2 -2
  78. package/dist/node/resolve.d.ts.map +1 -1
  79. package/dist/node/runtime.d.ts.map +1 -1
  80. package/dist/node/runtime.js +2 -2
  81. package/dist/node/runtime.js.map +1 -1
  82. package/dist/node/stream/index.d.ts.map +1 -1
  83. package/dist/node/stream/index.js.map +1 -1
  84. package/dist/node/stream/readable.d.ts.map +1 -1
  85. package/dist/node/stream/readable.js.map +1 -1
  86. package/dist/node/stream/writable.d.ts.map +1 -1
  87. package/dist/node/stream/writable.js.map +1 -1
  88. package/dist/node/util.d.ts +2 -2
  89. package/dist/node/util.d.ts.map +1 -1
  90. package/dist/node/util.js.map +1 -1
  91. package/dist/node/wasi/abi.d.ts.map +1 -1
  92. package/dist/node/wasi/abi.js.map +1 -1
  93. package/dist/node/wasi/files.d.ts.map +1 -1
  94. package/dist/node/wasi/index.d.ts.map +1 -1
  95. package/dist/node/wasi/index.js +2 -1
  96. package/dist/node/wasi/index.js.map +1 -1
  97. package/dist/node/workerThreads.js.map +1 -1
  98. package/dist/packageCdn.js.map +1 -1
  99. package/dist/previewBridge.d.ts +15 -3
  100. package/dist/previewBridge.d.ts.map +1 -1
  101. package/dist/previewBridge.js +30 -8
  102. package/dist/previewBridge.js.map +1 -1
  103. package/dist/projectConfig.d.ts +1 -1
  104. package/dist/projectConfig.d.ts.map +1 -1
  105. package/dist/projectConfig.js.map +1 -1
  106. package/dist/resolve.d.ts +1 -1
  107. package/dist/resolve.d.ts.map +1 -1
  108. package/dist/rootedFs.d.ts +7 -0
  109. package/dist/rootedFs.d.ts.map +1 -1
  110. package/dist/rootedFs.js +22 -2
  111. package/dist/rootedFs.js.map +1 -1
  112. package/dist/shell/builtins.d.ts +3 -0
  113. package/dist/shell/builtins.d.ts.map +1 -1
  114. package/dist/shell/builtins.js +4 -4
  115. package/dist/shell/builtins.js.map +1 -1
  116. package/dist/shell/compound.js.map +1 -1
  117. package/dist/shell/context.js.map +1 -1
  118. package/dist/shell/exec.d.ts +15 -3
  119. package/dist/shell/exec.d.ts.map +1 -1
  120. package/dist/shell/exec.js +47 -7
  121. package/dist/shell/exec.js.map +1 -1
  122. package/dist/shell/expand.js.map +1 -1
  123. package/dist/shell/lineEditor.d.ts.map +1 -1
  124. package/dist/shell/lineEditor.js.map +1 -1
  125. package/dist/shell/npm.d.ts.map +1 -1
  126. package/dist/shell/npm.js +6 -2
  127. package/dist/shell/npm.js.map +1 -1
  128. package/dist/shell/options.d.ts +37 -0
  129. package/dist/shell/options.d.ts.map +1 -0
  130. package/dist/shell/options.js +86 -0
  131. package/dist/shell/options.js.map +1 -0
  132. package/dist/shell/packageManagers.d.ts +2 -2
  133. package/dist/shell/packageManagers.d.ts.map +1 -1
  134. package/dist/shell/parse.js.map +1 -1
  135. package/dist/shell/program.d.ts +4 -0
  136. package/dist/shell/program.d.ts.map +1 -1
  137. package/dist/shell/program.js +20 -8
  138. package/dist/shell/program.js.map +1 -1
  139. package/dist/shell/testCommand.js.map +1 -1
  140. package/dist/shell/textCommands.d.ts.map +1 -1
  141. package/dist/shell/textCommands.js +3 -1
  142. package/dist/shell/textCommands.js.map +1 -1
  143. package/dist/shell/tokenize.d.ts.map +1 -1
  144. package/dist/shell/tokenize.js.map +1 -1
  145. package/dist/styles/imports.d.ts.map +1 -1
  146. package/dist/system/commands.d.ts +1 -1
  147. package/dist/system/commands.d.ts.map +1 -1
  148. package/dist/system/cookieJar.d.ts.map +1 -1
  149. package/dist/system/httpStream.d.ts +16 -4
  150. package/dist/system/httpStream.d.ts.map +1 -1
  151. package/dist/system/httpStream.js +25 -3
  152. package/dist/system/httpStream.js.map +1 -1
  153. package/dist/system/index.d.ts +1 -0
  154. package/dist/system/index.d.ts.map +1 -1
  155. package/dist/system/index.js +1 -0
  156. package/dist/system/index.js.map +1 -1
  157. package/dist/system/ipc.js.map +1 -1
  158. package/dist/system/kernel.d.ts.map +1 -1
  159. package/dist/system/kernel.js.map +1 -1
  160. package/dist/system/ports.d.ts.map +1 -1
  161. package/dist/system/process.js.map +1 -1
  162. package/dist/system/serverEvents.d.ts.map +1 -1
  163. package/dist/system/signals.d.ts +26 -0
  164. package/dist/system/signals.d.ts.map +1 -0
  165. package/dist/system/signals.js +36 -0
  166. package/dist/system/signals.js.map +1 -0
  167. package/dist/system/terminal.d.ts +13 -1
  168. package/dist/system/terminal.d.ts.map +1 -1
  169. package/dist/system/terminal.js +49 -0
  170. package/dist/system/terminal.js.map +1 -1
  171. package/dist/system/webSocketFrames.d.ts.map +1 -1
  172. package/dist/system/webSocketFrames.js.map +1 -1
  173. package/dist/vfs.d.ts.map +1 -1
  174. package/dist/vfs.js.map +1 -1
  175. package/package.json +6 -5
  176. package/src/archive.ts +46 -6
  177. package/src/devServer.ts +4 -2
  178. package/src/html.ts +11 -7
  179. package/src/index.ts +3 -3
  180. package/src/node/crypto.ts +6 -1
  181. package/src/node/hostClock.ts +16 -0
  182. package/src/node/http/server.ts +9 -1
  183. package/src/node/http/serverResponse.ts +5 -3
  184. package/src/node/misc.ts +3 -2
  185. package/src/node/process.ts +9 -8
  186. package/src/node/runtime.ts +2 -3
  187. package/src/node/wasi/index.ts +2 -1
  188. package/src/previewBridge.ts +31 -9
  189. package/src/rootedFs.ts +21 -2
  190. package/src/shell/builtins.ts +6 -4
  191. package/src/shell/exec.ts +52 -10
  192. package/src/shell/npm.ts +5 -2
  193. package/src/shell/options.ts +104 -0
  194. package/src/shell/program.ts +20 -8
  195. package/src/shell/textCommands.ts +3 -1
  196. package/src/system/httpStream.ts +42 -11
  197. package/src/system/index.ts +1 -0
  198. package/src/system/signals.ts +39 -0
  199. package/src/system/terminal.ts +51 -1
@@ -15,6 +15,7 @@ import { join, normalizePath } from '../paths.js';
15
15
  import { fsError } from './fs/stats.js';
16
16
  import { format } from './inspect.js';
17
17
  import { ProcessExit, queueCallback } from './processExit.js';
18
+ import { hostNow } from './hostClock.js';
18
19
 
19
20
  export const NODE_VERSION = '20.18.0';
20
21
 
@@ -168,7 +169,7 @@ export function createProcess(options: ProcessOptions): NodeProcess {
168
169
  let cwd = normalizePath(options.cwd);
169
170
  let exited = false;
170
171
  let gone = false;
171
- const started = performance.now();
172
+ const started = hostNow();
172
173
  const proc = new EventEmitterBase() as NodeProcess;
173
174
  const pid = nextPid++;
174
175
 
@@ -192,7 +193,7 @@ export function createProcess(options: ProcessOptions): NodeProcess {
192
193
  };
193
194
 
194
195
  const hrtime = (previous?: [number, number]): [number, number] => {
195
- const now = performance.now();
196
+ const now = hostNow();
196
197
  let seconds = Math.floor(now / 1000);
197
198
  let nanos = Math.floor((now % 1000) * 1e6);
198
199
  if (previous) {
@@ -205,7 +206,7 @@ export function createProcess(options: ProcessOptions): NodeProcess {
205
206
  }
206
207
  return [seconds, nanos];
207
208
  };
208
- hrtime.bigint = () => BigInt(Math.floor(performance.now() * 1e6));
209
+ hrtime.bigint = () => BigInt(Math.floor(hostNow() * 1e6));
209
210
 
210
211
  const memoryUsage = () => ({ rss: 50e6, heapTotal: 30e6, heapUsed: 20e6, external: 1e6, arrayBuffers: 1e5 });
211
212
  memoryUsage.rss = () => 50e6;
@@ -253,9 +254,9 @@ export function createProcess(options: ProcessOptions): NodeProcess {
253
254
  },
254
255
  hrtime,
255
256
  memoryUsage,
256
- cpuUsage: () => ({ user: Math.floor((performance.now() - started) * 1000), system: 0 }),
257
+ cpuUsage: () => ({ user: Math.floor((hostNow() - started) * 1000), system: 0 }),
257
258
  resourceUsage: () => ({ userCPUTime: 0, systemCPUTime: 0, maxRSS: 50000 }),
258
- uptime: () => (performance.now() - started) / 1000,
259
+ uptime: () => (hostNow() - started) / 1000,
259
260
  umask: () => 0o22,
260
261
  getuid: () => 1000,
261
262
  geteuid: () => 1000,
@@ -317,10 +318,10 @@ export function createConsole(proc: NodeProcess): Console {
317
318
  indent += ' ';
318
319
  },
319
320
  groupEnd: () => void (indent = indent.slice(2)),
320
- time: (label = 'default') => void timers.set(label, performance.now()),
321
- timeLog: (label = 'default', ...args: unknown[]) => log(`${label}: ${(performance.now() - (timers.get(label) ?? 0)).toFixed(3)}ms`, ...args),
321
+ time: (label = 'default') => void timers.set(label, hostNow()),
322
+ timeLog: (label = 'default', ...args: unknown[]) => log(`${label}: ${(hostNow() - (timers.get(label) ?? 0)).toFixed(3)}ms`, ...args),
322
323
  timeEnd: (label = 'default') => {
323
- log(`${label}: ${(performance.now() - (timers.get(label) ?? 0)).toFixed(3)}ms`);
324
+ log(`${label}: ${(hostNow() - (timers.get(label) ?? 0)).toFixed(3)}ms`);
324
325
  timers.delete(label);
325
326
  },
326
327
  clear: () => undefined,
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import type { ProgramIO, System, ThreadInfo } from '../system/types.js';
8
8
  import type { IpcEndpoint } from '../system/ipc.js';
9
+ import { signalExitCode } from '../system/signals.js';
9
10
  import { attachProcessChannel } from './ipc.js';
10
11
  import { threadErrorEnvelope } from './workerThreads.js';
11
12
  import { Buffer } from './buffer.js';
@@ -52,8 +53,6 @@ export interface NodeInstance {
52
53
  hold(): () => void;
53
54
  }
54
55
 
55
- const SIGNAL_CODES: Record<string, number> = { SIGINT: 130, SIGTERM: 143, SIGKILL: 137, SIGHUP: 129 };
56
-
57
56
  export async function startNode(options: NodeOptions): Promise<NodeInstance> {
58
57
  await esmReady;
59
58
  const { system } = options;
@@ -188,7 +187,7 @@ export async function startNode(options: NodeOptions): Promise<NodeInstance> {
188
187
  loop._run(() => proc.emit(signal, signal));
189
188
  return;
190
189
  }
191
- finish(SIGNAL_CODES[signal] ?? 1);
190
+ finish(signalExitCode(signal));
192
191
  },
193
192
  reportUncaught: uncaught,
194
193
  hold: () => loop.hold(),
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import { CLOCK, ERRNO, Memory, attempt, guest, u64 } from './abi.js';
12
12
  import { createWasiFiles, type WasiFs } from './files.js';
13
+ import { hostNow } from '../hostClock.js';
13
14
 
14
15
  /** Every `wasi_snapshot_preview1` function: a module imports by name, so each must exist (ENOSYS when not implemented). */
15
16
  const WASI_FUNCTIONS = [
@@ -76,7 +77,7 @@ export function createWasiModule(deps: WasiDeps): Record<string, unknown> {
76
77
  environ_sizes_get: (count: number, size: number) => attempt(() => memory.sizes(env, count, size)),
77
78
  clock_res_get: (id: number, result: number) => (knownClock(id) ? attempt(() => memory.u64(result, 1000n)) : ERRNO.INVAL),
78
79
  clock_time_get: (id: number, _precision: bigint, result: number) =>
79
- knownClock(id) ? attempt(() => memory.u64(result, id === CLOCK.REALTIME ? u64(Date.now()) * 1_000_000n : u64(performance.now() * 1_000_000))) : ERRNO.INVAL,
80
+ knownClock(id) ? attempt(() => memory.u64(result, id === CLOCK.REALTIME ? u64(Date.now()) * 1_000_000n : u64(hostNow() * 1_000_000))) : ERRNO.INVAL,
80
81
  random_get: (buffer: number, length: number) =>
81
82
  attempt(() => {
82
83
  // Filled outside the module's memory, which may be shared: getRandomValues rejects a view over it.
@@ -17,6 +17,16 @@
17
17
  * `{ kind: 'close', code, reason }`; host → page: `{ kind: 'open', protocol }`,
18
18
  * `{ kind: 'message', data }` (string or ArrayBuffer), `{ kind: 'close', code, reason, wasClean }`.
19
19
  * On the cookie channel — page → host `{ kind: 'set-cookie', value }`, host → page `{ kind: 'cookies', value }`.
20
+ *
21
+ * A MessagePort gives no signal when the page on the other end goes away, so
22
+ * the page says so: on `pagehide`, and when it gives up waiting for the host
23
+ * (the connect timeout), it posts `{ kind: 'close', code: 1001 }` for every
24
+ * socket still open — otherwise the server's end (an HMR socket) would leak on
25
+ * every reload.
26
+ *
27
+ * Every message to the host carries the runtime's `nonce` (when it has one):
28
+ * the host accepts a page's messages only with it, so a frame on the preview
29
+ * origin cannot pass itself off as another runtime's page by its `href` alone.
20
30
  */
21
31
 
22
32
  /** page → host, with a MessagePort: "connect a WebSocket to `port` at `path`". */
@@ -26,8 +36,11 @@ export const COOKIE_MESSAGE_TYPE = 'bfwc:cookies';
26
36
  /** How long a page waits for the host to answer a socket before failing it (code 1006). */
27
37
  export const SOCKET_CONNECT_TIMEOUT_MS = 15_000;
28
38
 
29
- /** The `WebSocket` replacement; runs in every preview page (dev-server documents and virtual-server HTML). */
30
- export function previewSocketScript(): string {
39
+ /** `JSON.stringify`, safe inside an inline script. */
40
+ export const scriptLiteral = (value: unknown) => JSON.stringify(value).replace(/</g, '\\u003c');
41
+
42
+ /** The `WebSocket` replacement; runs in every preview page (dev-server documents and virtual-server HTML). `nonce`: the runtime's (see the module doc). */
43
+ export function previewSocketScript(nonce = ''): string {
31
44
  return `<script>(function(){
32
45
  var Native = window.WebSocket;
33
46
  if (!Native || Native.__bfwc) return;
@@ -51,6 +64,10 @@ export function previewSocketScript(): string {
51
64
  return null;
52
65
  }
53
66
  var CONNECTING = 0, OPEN = 1, CLOSING = 2, CLOSED = 3;
67
+ var live = new Set();
68
+ window.addEventListener('pagehide', function () {
69
+ live.forEach(function (s) { s._abandon(); });
70
+ });
54
71
  class VirtualWebSocket extends EventTarget {
55
72
  constructor(url, protocols) {
56
73
  var t = target(url);
@@ -64,9 +81,10 @@ export function previewSocketScript(): string {
64
81
  this._queue = Promise.resolve();
65
82
  this._port = channel.port1;
66
83
  this._port.onmessage = function (e) { self._receive(e.data); };
67
- this._timer = setTimeout(function () { self._receive({ kind: 'close', code: 1006, reason: '', wasClean: false }); }, ${SOCKET_CONNECT_TIMEOUT_MS});
84
+ this._timer = setTimeout(function () { self._abandon(); }, ${SOCKET_CONNECT_TIMEOUT_MS});
85
+ live.add(this);
68
86
  var list = protocols === undefined ? [] : typeof protocols === 'string' ? [protocols] : Array.from(protocols, String);
69
- runtime.postMessage({ type: ${JSON.stringify(SOCKET_MESSAGE_TYPE)}, href: location.href, port: t.port, path: t.path, protocols: list }, '*', [channel.port2]);
87
+ runtime.postMessage({ type: ${JSON.stringify(SOCKET_MESSAGE_TYPE)}, href: location.href, nonce: ${scriptLiteral(nonce)}, port: t.port, path: t.path, protocols: list }, '*', [channel.port2]);
70
88
  }
71
89
  get url() { return this._url; }
72
90
  get readyState() { return this._state; }
@@ -92,6 +110,12 @@ export function previewSocketScript(): string {
92
110
  var port = this._port;
93
111
  this._queue.then(function () { port.postMessage({ kind: 'close', code: code, reason: reason === undefined ? '' : String(reason) }); });
94
112
  }
113
+ /** Tell the host this end is gone (it would never know otherwise), then close here. */
114
+ _abandon() {
115
+ if (this._state === CLOSED) return;
116
+ this._port.postMessage({ kind: 'close', code: 1001, reason: '' });
117
+ this._receive({ kind: 'close', code: 1006, reason: '', wasClean: false });
118
+ }
95
119
  _receive(m) {
96
120
  if (!m || this._state === CLOSED) return;
97
121
  if (m.kind === 'open' && this._state === CONNECTING) {
@@ -106,6 +130,7 @@ export function previewSocketScript(): string {
106
130
  } else if (m.kind === 'close') {
107
131
  clearTimeout(this._timer);
108
132
  this._state = CLOSED;
133
+ live.delete(this);
109
134
  this._port.close();
110
135
  if (!m.wasClean) this._emit(new Event('error'));
111
136
  this._emit(new CloseEvent('close', { code: m.code, reason: m.reason || '', wasClean: !!m.wasClean }));
@@ -127,15 +152,12 @@ export function previewSocketScript(): string {
127
152
  })();</script>`;
128
153
  }
129
154
 
130
- /** `JSON.stringify`, safe inside an inline script. */
131
- const scriptLiteral = (value: unknown) => JSON.stringify(value).replace(/</g, '\\u003c');
132
-
133
155
  /**
134
156
  * `document.cookie` for a page a virtual server served: starts from the host's
135
157
  * jar (`initial`: the non-HttpOnly cookies for this page's path), stays in sync
136
158
  * over a channel, and sends assignments to the host's jar.
137
159
  */
138
- export function previewCookieScript(initial: string): string {
160
+ export function previewCookieScript(initial: string, nonce = ''): string {
139
161
  return `<script>(function(){
140
162
  var runtime = window.parent !== window ? window.parent : window.opener;
141
163
  var cookies = ${scriptLiteral(initial)};
@@ -144,7 +166,7 @@ export function previewCookieScript(initial: string): string {
144
166
  var channel = new MessageChannel();
145
167
  port = channel.port1;
146
168
  port.onmessage = function (e) { if (e.data && e.data.kind === 'cookies') cookies = String(e.data.value); };
147
- runtime.postMessage({ type: ${JSON.stringify(COOKIE_MESSAGE_TYPE)}, href: location.href }, '*', [channel.port2]);
169
+ runtime.postMessage({ type: ${JSON.stringify(COOKIE_MESSAGE_TYPE)}, href: location.href, nonce: ${scriptLiteral(nonce)} }, '*', [channel.port2]);
148
170
  }
149
171
  function apply(value) {
150
172
  var parts = value.split(';'), pair = parts[0], eq = pair.indexOf('=');
package/src/rootedFs.ts CHANGED
@@ -16,6 +16,26 @@
16
16
  import { VirtualFileSystem, type DirectoryEntry, type FileContent, type FlatFiles, type FsChange } from './vfs.js';
17
17
  import { normalizePath } from './paths.js';
18
18
 
19
+ /**
20
+ * A project path (`/src`, rooted at `/`) as a path in the base file system under
21
+ * `root`. `..` cannot climb out: the result is always `root` or below it.
22
+ */
23
+ export function projectToBase(root: string, path: string): string {
24
+ const key = normalizePath(path);
25
+ const at = normalizePath(root);
26
+ if (at === '/') return key;
27
+ return key === '/' ? at : at + key;
28
+ }
29
+
30
+ /** A base path as a project path (`/` is `root`); undefined when it lies outside `root`. */
31
+ export function baseToProject(root: string, path: string): string | undefined {
32
+ const key = normalizePath(path);
33
+ const at = normalizePath(root);
34
+ if (at === '/') return key;
35
+ if (key === at) return '/';
36
+ return key.startsWith(at + '/') ? key.slice(at.length) : undefined;
37
+ }
38
+
19
39
  class RootedFileSystem extends VirtualFileSystem {
20
40
  private readonly prefix: string;
21
41
 
@@ -26,8 +46,7 @@ class RootedFileSystem extends VirtualFileSystem {
26
46
 
27
47
  /** View path → base path. */
28
48
  private real(path: string): string {
29
- const key = normalizePath(path);
30
- return key === '/' ? this.root : this.root + key;
49
+ return projectToBase(this.root, path);
31
50
  }
32
51
 
33
52
  /** Base path under `root` → view path. */
@@ -11,6 +11,7 @@ import { basename, clear, dirname, echo, env, falseCommand, grep, head, printf,
11
11
  import { bracket, test } from './testCommand.js';
12
12
  import { readLine } from './lineReader.js';
13
13
  import type { Flow } from './compound.js';
14
+ import { setBuiltin, type ShellSettings } from './options.js';
14
15
 
15
16
  /** A command started with `&`. */
16
17
  export interface BackgroundJob {
@@ -30,6 +31,8 @@ export interface ShellState {
30
31
  flow?: Flow;
31
32
  /** `$1…`, `$@`; a function call swaps them for its arguments. */
32
33
  positional: string[];
34
+ /** `set -o` options (pipefail). */
35
+ readonly settings: ShellSettings;
33
36
  readonly functions: ReadonlyMap<string, unknown>;
34
37
  readonly jobs: ReadonlyMap<number, BackgroundJob>;
35
38
  /** One frame per running function (for `local`). */
@@ -54,7 +57,8 @@ export const SYSTEM_PROGRAMS = ['node', 'npm', 'npx', 'pnpm', 'yarn', 'bfsh', 's
54
57
  const HELP = `bfsh — BuilderForce WebContainers shell
55
58
 
56
59
  Builtins: cd, pwd, export, unset, exit, source, history, type, which, help,
57
- read, local, shift, return, break, continue, jobs, wait
60
+ read, local, shift, return, break, continue, jobs, wait,
61
+ set -o|+o pipefail (on by default), set -- args
58
62
  Files: ls [-la], cat, mkdir [-p], rm [-rf], cp [-r], mv, touch, test / [ … ]
59
63
  Text: echo, printf, head, tail, grep, wc, env, clear, sleep, basename, dirname
60
64
  Node: node <file>, npm install|ci|run|start|test, npx <bin>, pnpm, yarn
@@ -65,6 +69,7 @@ const HELP = `bfsh — BuilderForce WebContainers shell
65
69
  `;
66
70
 
67
71
  export const BUILTINS: Record<string, Builtin> = {
72
+ set: setBuiltin,
68
73
  async cd(ctx, shell) {
69
74
  const home = shell.env.HOME && ctx.fs.isDirectory(shell.env.HOME) ? shell.env.HOME : '/';
70
75
  const target = ctx.args[0] === '-' ? shell.env.OLDPWD ?? shell.cwd : ctx.args[0] ?? home;
@@ -154,9 +159,6 @@ export const BUILTINS: Record<string, Builtin> = {
154
159
  }
155
160
  return status;
156
161
  },
157
- async set() {
158
- return 0; // options (-e, -x) are accepted and ignored
159
- },
160
162
  async break(ctx, shell) {
161
163
  return loopControl(ctx, shell, 'break');
162
164
  },
package/src/shell/exec.ts CHANGED
@@ -1,14 +1,19 @@
1
1
  /**
2
2
  * The executor: runs a parsed script. Lists honour `&&`/`||`/`;`/`&`; pipeline
3
- * stages run concurrently, joined by in-memory pipes; redirects (here-documents
4
- * included) swap a stage's stdin/stdout/stderr. Compound commands run through
5
- * compound.ts. Dispatch order per simple command: shell functions, builtins,
3
+ * stages run concurrently, joined by in-memory pipes, and a pipeline's status is
4
+ * the rightmost non-zero stage (pipefail, on by default; `set +o pipefail` gives
5
+ * the POSIX last-stage status). A stage writing to a pipe whose reader is gone
6
+ * stops with EPIPE (SIGPIPE's status, 141) instead of buffering forever. Redirects
7
+ * (here-documents included) swap a stage's stdin/stdout/stderr. Compound
8
+ * commands run through compound.ts. Dispatch order per simple command: shell
9
+ * functions, builtins,
6
10
  * extra in-process commands (npm, npx), the dev-server handoff, coreutils, and
7
11
  * finally `system.spawn` (node, scripts on PATH, `.bin` entries) — which in the
8
12
  * browser is a separate Web Worker.
9
13
  */
10
14
  import type { System } from '../system/types.js';
11
15
  import { InputQueue, textChunks } from '../system/terminal.js';
16
+ import { SIGPIPE_STATUS, brokePipe, isBrokenPipe } from '../system/signals.js';
12
17
  import type { Command as CommandNode, FunctionDefinition, Pipeline, Redirect, Script, SimpleCommand, Word } from './ast.js';
13
18
  import { parse, ShellSyntaxError } from './parse.js';
14
19
  import { expandWord, expandWords, type ExpandContext } from './expand.js';
@@ -16,6 +21,7 @@ import { BUILTINS, COREUTILS, type BackgroundJob, type ShellState } from './buil
16
21
  import { resolvePath, type CommandContext } from './context.js';
17
22
  import { devServerHandoff, runDevServerHandoff } from './devHandoff.js';
18
23
  import { runCompound, type Flow, type ScriptRunner } from './compound.js';
24
+ import { DEFAULT_SHELL_SETTINGS, pipelineStatus, type ShellSettings } from './options.js';
19
25
 
20
26
  export interface ShellIO {
21
27
  stdout(text: string): void;
@@ -44,6 +50,12 @@ export interface ShellOptions {
44
50
  commands?: Record<string, ShellCommand>;
45
51
  /** Functions inherited from a parent shell (subshells and `$(…)`). */
46
52
  functions?: Map<string, FunctionDefinition>;
53
+ /**
54
+ * Fail a pipeline when any stage fails (status: the rightmost non-zero).
55
+ * Default true; false is POSIX (the last stage's status). Scripts switch it
56
+ * with `set -o pipefail` / `set +o pipefail`.
57
+ */
58
+ pipefail?: boolean;
47
59
  }
48
60
 
49
61
  let nextShellPid = 500;
@@ -57,6 +69,7 @@ export class Shell implements ShellState, ScriptRunner {
57
69
  flow?: Flow;
58
70
  positional: string[];
59
71
  readonly functions: Map<string, FunctionDefinition>;
72
+ readonly settings: ShellSettings;
60
73
  readonly jobs = new Map<number, BackgroundJob>();
61
74
  /** One frame per running function: names declared `local`, with the value to restore. */
62
75
  readonly localFrames: Array<Map<string, string | undefined>> = [];
@@ -71,11 +84,12 @@ export class Shell implements ShellState, ScriptRunner {
71
84
  this.env = { ...options.env, PWD: options.cwd };
72
85
  this.positional = [...(options.positional ?? [])];
73
86
  this.functions = new Map(options.functions);
87
+ this.settings = { ...DEFAULT_SHELL_SETTINGS, pipefail: options.pipefail ?? DEFAULT_SHELL_SETTINGS.pipefail };
74
88
  }
75
89
 
76
90
  /** A child shell for `npm run` / subshells: same IO, its own cwd, environment and functions. */
77
91
  fork(overrides: { cwd?: string; env?: Record<string, string>; positional?: string[] }): Shell {
78
- return new Shell({ ...this.options, cwd: overrides.cwd ?? this.cwd, env: { ...this.env, ...overrides.env }, positional: overrides.positional ?? this.positional, functions: this.functions });
92
+ return new Shell({ ...this.options, cwd: overrides.cwd ?? this.cwd, env: { ...this.env, ...overrides.env }, positional: overrides.positional ?? this.positional, functions: this.functions, pipefail: this.settings.pipefail });
79
93
  }
80
94
 
81
95
  subshell(): Shell {
@@ -168,19 +182,32 @@ export class Shell implements ShellState, ScriptRunner {
168
182
  private async runPipeline(pipeline: Pipeline, io: ShellIO, input: JobInput, signal: AbortSignal): Promise<number> {
169
183
  const count = pipeline.commands.length;
170
184
  const pipes = Array.from({ length: count - 1 }, () => new InputQueue());
171
- const statuses = await Promise.all(
185
+ // Every stage settles before the pipeline does: none is left running detached.
186
+ const settled = await Promise.allSettled(
172
187
  pipeline.commands.map(async (command, i) => {
173
188
  const stdin: JobInput = i === 0 ? input : { queue: pipes[i - 1]! };
174
189
  const stdout = i === count - 1 ? io.stdout : (text: string) => pipes[i]!.push(text);
175
190
  const stageIO: ShellIO = { stdout, stderr: io.stderr, isTerminal: io.isTerminal && i === count - 1 };
176
191
  try {
177
192
  return await this.runCommand(command, stageIO, stdin, signal, count === 1);
193
+ } catch (error) {
194
+ // Its own pipe broke (the reader exited): SIGPIPE ends the stage. An enclosing
195
+ // pipeline's pipe is not its to absorb: that travels on, ending loops on the way.
196
+ if (i < count - 1 && brokePipe(error, pipes[i]!)) return SIGPIPE_STATUS;
197
+ throw error;
178
198
  } finally {
179
199
  if (i < count - 1) pipes[i]!.push(null);
200
+ if (i > 0) pipes[i - 1]!.closeReader(); // its reader is gone: the writer upstream gets EPIPE
180
201
  }
181
202
  }),
182
203
  );
183
- const status = statuses[statuses.length - 1]!;
204
+ const failed = settled.find((stage): stage is PromiseRejectedResult => stage.status === 'rejected');
205
+ if (failed) throw failed.reason;
206
+ const statuses = settled.map((stage) => (stage as PromiseFulfilledResult<number>).value);
207
+ // pipefail (the default): any non-zero stage fails the pipeline, the status the
208
+ // rightmost non-zero, so `build 2>&1 | tail` reports the build rather than tail's 0.
209
+ // A one-stage pipeline (a non-pipeline command) is the same either way.
210
+ const status = pipelineStatus(statuses, this.settings);
184
211
  return pipeline.negate ? (status === 0 ? 1 : 0) : status;
185
212
  }
186
213
 
@@ -331,9 +358,22 @@ export class Shell implements ShellState, ScriptRunner {
331
358
  io.stderr(`bfsh: command not found: ${name}\n`);
332
359
  return 127;
333
360
  }
334
- // The shell's own IO is text; a child's bytes are decoded as they enter it.
335
- child.onStdout(textChunks((text) => text !== null && io.stdout(text)));
336
- child.onStderr(textChunks((text) => text !== null && io.stderr(text)));
361
+ // The shell's own IO is text; a child's bytes are decoded as they enter it. Writing into
362
+ // a pipe whose reader has exited kills the child with SIGPIPE (its timers stop with it),
363
+ // then raises the break here, so the stage owning the pipe ends — a loop around it too.
364
+ let brokenPipe: unknown;
365
+ const relay = (write: (text: string) => void) => (text: string | null) => {
366
+ if (text === null || brokenPipe !== undefined) return;
367
+ try {
368
+ write(text);
369
+ } catch (error) {
370
+ if (!isBrokenPipe(error)) throw error;
371
+ brokenPipe = error;
372
+ child.kill('SIGPIPE');
373
+ }
374
+ };
375
+ child.onStdout(textChunks(relay(io.stdout)));
376
+ child.onStderr(textChunks(relay(io.stderr)));
337
377
  let stop: (() => void) | undefined;
338
378
  if (size && input.setRawSink) input.setRawSink((data) => child.write(data));
339
379
  else stop = input.queue.subscribe((chunk) => (chunk === null ? child.closeStdin() : child.write(chunk)));
@@ -341,7 +381,9 @@ export class Shell implements ShellState, ScriptRunner {
341
381
  if (signal.aborted) onAbort();
342
382
  signal.addEventListener('abort', onAbort);
343
383
  try {
344
- return await child.exit;
384
+ const code = await child.exit;
385
+ if (brokenPipe !== undefined) throw brokenPipe;
386
+ return code;
345
387
  } finally {
346
388
  signal.removeEventListener('abort', onAbort);
347
389
  if (size && input.setRawSink) input.setRawSink(undefined);
package/src/shell/npm.ts CHANGED
@@ -14,6 +14,8 @@ import { findPackageScope } from '../node/resolve.js';
14
14
  import { parseFlags, type CommandContext } from './context.js';
15
15
  import type { JobInput, Shell } from './exec.js';
16
16
  import { devServerHandoff } from './devHandoff.js';
17
+ import { hostNow } from '../node/hostClock.js';
18
+ import { isBrokenPipe } from '../system/signals.js';
17
19
 
18
20
  export const NPM_VERSION = '10.8.2';
19
21
 
@@ -32,7 +34,7 @@ function readPackage(ctx: CommandContext, dir: string): PackageJson | undefined
32
34
  }
33
35
 
34
36
  async function install(ctx: CommandContext, options: Partial<InstallOptions>, dir = projectDir(ctx)): Promise<number> {
35
- const started = performance.now();
37
+ const started = hostNow();
36
38
  const progress = ctx.io.isTerminal;
37
39
  try {
38
40
  // User file first, then the project's: later files win, as with npm.
@@ -50,11 +52,12 @@ async function install(ctx: CommandContext, options: Partial<InstallOptions>, di
50
52
  });
51
53
  if (progress) ctx.io.stdout('\r\x1b[K');
52
54
  for (const warning of result.warnings) ctx.io.stderr(`npm warn ${warning}\n`);
53
- const seconds = ((performance.now() - started) / 1000).toFixed(1);
55
+ const seconds = ((hostNow() - started) / 1000).toFixed(1);
54
56
  const parts = [result.added && `added ${result.added} package${result.added === 1 ? '' : 's'}`, result.removed && `removed ${result.removed} package${result.removed === 1 ? '' : 's'}`].filter(Boolean);
55
57
  ctx.io.stdout(`\n${parts.length ? parts.join(', ') : 'up to date'}, audited ${result.total + 1} packages in ${seconds}s\n`);
56
58
  return 0;
57
59
  } catch (error) {
60
+ if (isBrokenPipe(error)) throw error; // its reader exited: SIGPIPE, not an install failure
58
61
  if (progress) ctx.io.stdout('\r\x1b[K');
59
62
  if (ctx.signal.aborted) return 130;
60
63
  ctx.io.stderr(`npm error ${error instanceof Error ? error.message : String(error)}\n`);
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Shell options (`set -o NAME` / `set +o NAME`, and the same flags when invoking
3
+ * `bfsh`). Only `pipefail` exists so far. It is ON by default: a pipeline fails
4
+ * when any stage fails, which the Builderforce canvas relies on to see a failing
5
+ * `build 2>&1 | tail`. `set +o pipefail` (or `bfsh +o pipefail -c …`) opts a
6
+ * script out to POSIX behaviour, where a pipeline's status is its last stage's.
7
+ */
8
+ import type { CommandContext } from './context.js';
9
+
10
+ export interface ShellSettings {
11
+ pipefail: boolean;
12
+ }
13
+
14
+ export const DEFAULT_SHELL_SETTINGS: Readonly<ShellSettings> = { pipefail: true };
15
+
16
+ const NAMES = Object.keys(DEFAULT_SHELL_SETTINGS) as Array<keyof ShellSettings>;
17
+
18
+ const isName = (name: string | undefined): name is keyof ShellSettings => NAMES.includes(name as keyof ShellSettings);
19
+
20
+ /**
21
+ * Leading `-o NAME` / `+o NAME` pairs of a `bfsh` invocation, applied to
22
+ * `settings`; returns the arguments after them, or an error message.
23
+ */
24
+ export function takeInvocationOptions(args: string[], settings: ShellSettings): { rest: string[] } | { error: string } {
25
+ let i = 0;
26
+ while ((args[i] === '-o' || args[i] === '+o') && i + 1 < args.length) {
27
+ const name = args[i + 1];
28
+ if (!isName(name)) return { error: `bfsh: ${name}: invalid option name` };
29
+ settings[name] = args[i] === '-o';
30
+ i += 2;
31
+ }
32
+ return { rest: args.slice(i) };
33
+ }
34
+
35
+ /** The state `set` changes. */
36
+ export interface SetTarget {
37
+ settings: ShellSettings;
38
+ positional: string[];
39
+ }
40
+
41
+ /** Real `set -o` names this shell does not model: accepted and ignored, like their short flags. */
42
+ const ACCEPTED_UNMODELLED = new Set([
43
+ 'allexport', 'braceexpand', 'emacs', 'errexit', 'errtrace', 'functrace', 'hashall', 'histexpand',
44
+ 'history', 'ignoreeof', 'interactive-comments', 'keyword', 'monitor', 'noclobber', 'noexec',
45
+ 'noglob', 'nolog', 'notify', 'nounset', 'onecmd', 'physical', 'posix', 'privileged', 'verbose',
46
+ 'vi', 'xtrace',
47
+ ]);
48
+
49
+ /**
50
+ * The `set` builtin: `set -o NAME` / `set +o NAME` and clustered short flags
51
+ * (`-euo pipefail`), `set -o` / `set +o` to list, and `set -- ARGS…` to replace
52
+ * the positional parameters. Only `pipefail` is modelled; other real options
53
+ * (`-e`, `-u`, `-x`, errexit…) are accepted and ignored as the shell always did,
54
+ * and an unknown option name is refused (status 2), as bash does.
55
+ */
56
+ export async function setBuiltin(ctx: CommandContext, shell: SetTarget): Promise<number> {
57
+ const args = ctx.args;
58
+ if (!args.length || (args.length === 1 && (args[0] === '-o' || args[0] === '+o'))) {
59
+ const listing = args[0] === '+o'
60
+ ? NAMES.map((name) => `set ${shell.settings[name] ? '-o' : '+o'} ${name}\n`)
61
+ : NAMES.map((name) => `${name.padEnd(15)}${shell.settings[name] ? 'on' : 'off'}\n`);
62
+ ctx.io.stdout(listing.join(''));
63
+ return 0;
64
+ }
65
+ for (let i = 0; i < args.length; i++) {
66
+ const arg = args[i]!;
67
+ if (arg === '--') {
68
+ shell.positional = args.slice(i + 1);
69
+ return 0;
70
+ }
71
+ // `-o NAME` / `+o NAME`, and clustered short flags (`-euo pipefail`, `+x`): only
72
+ // `pipefail` is modelled. Every other option (errexit, nounset, xtrace, -e, -u, -x)
73
+ // is accepted and ignored, as before, so ordinary `set -euo pipefail` headers in
74
+ // npm scripts keep working.
75
+ const flags = /^[-+][a-zA-Z]+$/.test(arg) ? arg.slice(1) : undefined;
76
+ if (flags === undefined) {
77
+ shell.positional = args.slice(i);
78
+ return 0;
79
+ }
80
+ const on = arg[0] === '-';
81
+ for (const flag of flags) {
82
+ if (flag !== 'o') continue;
83
+ const name = args[++i];
84
+ if (name === undefined) {
85
+ ctx.io.stderr('bfsh: set: -o: option name required\n');
86
+ return 2;
87
+ }
88
+ if (isName(name)) shell.settings[name] = on;
89
+ else if (!ACCEPTED_UNMODELLED.has(name)) {
90
+ ctx.io.stderr(`bfsh: set: ${name}: invalid option name\n`);
91
+ return 2;
92
+ }
93
+ }
94
+ }
95
+ return 0;
96
+ }
97
+
98
+ /** A pipeline's status from its stages': the rightmost non-zero under pipefail, else the last stage's. */
99
+ export function pipelineStatus(statuses: number[], settings: ShellSettings): number {
100
+ if (!settings.pipefail) return statuses[statuses.length - 1] ?? 0;
101
+ let status = 0;
102
+ for (const stage of statuses) if (stage !== 0) status = stage;
103
+ return status;
104
+ }
@@ -16,11 +16,13 @@ import { BUILTINS, COREUTILS, SYSTEM_PROGRAMS } from './builtins.js';
16
16
  import { npmCommand, npxCommand } from './npm.js';
17
17
  import { pnpmCommand, yarnCommand } from './packageManagers.js';
18
18
  import { glob } from './expand.js';
19
+ import { DEFAULT_SHELL_SETTINGS, takeInvocationOptions, type ShellSettings } from './options.js';
19
20
 
20
21
  export const SHELL_COMMANDS: Record<string, ShellCommand> = { npm: npmCommand, npx: npxCommand, pnpm: pnpmCommand, yarn: yarnCommand };
21
22
 
22
- function createShell(ctx: ProgramContext, positional: string[] = []): Shell {
23
+ function createShell(ctx: ProgramContext, positional: string[] = [], settings: ShellSettings = DEFAULT_SHELL_SETTINGS): Shell {
23
24
  return new Shell({
25
+ pipefail: settings.pipefail,
24
26
  system: ctx.system,
25
27
  cwd: ctx.cwd,
26
28
  env: { ...ctx.env, SHELL: '/bin/bfsh' },
@@ -104,9 +106,9 @@ function completer(shell: Shell) {
104
106
  };
105
107
  }
106
108
 
107
- async function interactive(ctx: ProgramContext): Promise<number> {
109
+ async function interactive(ctx: ProgramContext, settings: ShellSettings): Promise<number> {
108
110
  const terminal = ctx.io.terminal!;
109
- const shell = createShell(ctx);
111
+ const shell = createShell(ctx, [], settings);
110
112
  const io = text(ctx);
111
113
  terminal.setRawMode(true);
112
114
  const editor = new LineEditor({ write: (t) => ctx.io.stdout(t), history: shell.history, complete: completer(shell) });
@@ -200,9 +202,19 @@ async function interactive(ctx: ProgramContext): Promise<number> {
200
202
  return code;
201
203
  }
202
204
 
205
+ /**
206
+ * `bfsh [-o|+o OPTION]… -c SCRIPT [ARGS…]`, `bfsh [-o|+o OPTION]… FILE [ARGS…]`,
207
+ * or no arguments (interactive / stdin). `+o pipefail` opts out of pipefail.
208
+ */
203
209
  export const shellProgram: Program = async (ctx) => {
204
- const args = ctx.args.filter((a) => a !== '-l' && a !== '--login' && a !== '-i');
205
- if (args[0] === '-c') return runOnce(ctx, createShell(ctx, args.slice(2)), args[1] ?? '');
210
+ const settings: ShellSettings = { ...DEFAULT_SHELL_SETTINGS };
211
+ const taken = takeInvocationOptions(ctx.args.filter((a) => a !== '-l' && a !== '--login' && a !== '-i'), settings);
212
+ if ('error' in taken) {
213
+ ctx.io.stderr(`${taken.error}\n`);
214
+ return 2;
215
+ }
216
+ const args = taken.rest;
217
+ if (args[0] === '-c') return runOnce(ctx, createShell(ctx, args.slice(2), settings), args[1] ?? '');
206
218
  if (args[0]) {
207
219
  const path = args[0].startsWith('/') ? args[0] : join(ctx.cwd, args[0]);
208
220
  const source = ctx.system.fs.readText(path);
@@ -210,14 +222,14 @@ export const shellProgram: Program = async (ctx) => {
210
222
  ctx.io.stderr(`bfsh: ${args[0]}: No such file or directory\n`);
211
223
  return 127;
212
224
  }
213
- return runOnce(ctx, createShell(ctx, args.slice(1)), source.replace(/^#!.*\n/, ''));
225
+ return runOnce(ctx, createShell(ctx, args.slice(1), settings), source.replace(/^#!.*\n/, ''));
214
226
  }
215
- if (ctx.io.terminal) return interactive(ctx);
227
+ if (ctx.io.terminal) return interactive(ctx, settings);
216
228
  // No terminal, no script: read commands from stdin.
217
229
  const { input, stop } = stdinJob(ctx);
218
230
  const source = await input.queue.readAll();
219
231
  stop();
220
- const shell = createShell(ctx);
232
+ const shell = createShell(ctx, [], settings);
221
233
  const empty = new InputQueue();
222
234
  empty.push(null);
223
235
  return shell.exec(source, text(ctx), { queue: empty }, ctx.signal);
@@ -62,7 +62,9 @@ function headTail(which: 'head' | 'tail'): Command {
62
62
  const numeric = ctx.args.find((a) => /^-\d+$/.test(a));
63
63
  const { values, operands } = parseFlags(ctx.args.filter((a) => a !== numeric), ['n']);
64
64
  const count = numeric ? Number(numeric.slice(1)) : values.n !== undefined ? Number(values.n) : 10;
65
- const files = await inputs(ctx, operands, which);
65
+ // head on stdin stops reading once it has its lines (and exits, closing the pipe), as the real one does.
66
+ const fromStdin = which === 'head' && (!operands.length || (operands.length === 1 && operands[0] === '-'));
67
+ const files = fromStdin ? [{ label: '(standard input)', text: await ctx.io.stdin.readLines(count) }] : await inputs(ctx, operands, which);
66
68
  if (typeof files === 'number') return files;
67
69
  files.forEach((file, index) => {
68
70
  if (files.length > 1) ctx.io.stdout(`${index ? '\n' : ''}==> ${file.label} <==\n`);