@innovatorved/code-lab 0.3.1 → 0.4.0

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 (171) hide show
  1. package/ARCHITECTURE.md +8 -4
  2. package/CHANGELOG.md +45 -0
  3. package/README.md +70 -158
  4. package/dist/apps/web/src/index.d.ts +34 -0
  5. package/dist/code-lab-sql.css +482 -0
  6. package/dist/code-lab-sql.d.ts +179 -0
  7. package/dist/code-lab-sql.esm.js +542 -0
  8. package/dist/code-lab-sql.umd.js +531 -0
  9. package/dist/code-lab.css +298 -2
  10. package/dist/code-lab.d.ts +110 -15
  11. package/dist/code-lab.esm.js +35284 -18253
  12. package/dist/code-lab.js +40434 -23431
  13. package/dist/code-lab.umd.js +65502 -0
  14. package/dist/diagnostics.d.ts +5 -0
  15. package/dist/extensions/cpp.esm.js +19532 -3772
  16. package/dist/extensions/cpp.js +19529 -3769
  17. package/dist/extensions/guided-lab.esm.js +19401 -3725
  18. package/dist/extensions/guided-lab.js +19400 -3724
  19. package/dist/extensions/python.d.ts +1 -0
  20. package/dist/extensions/python.esm.js +19666 -3843
  21. package/dist/extensions/python.js +19668 -3845
  22. package/dist/extensions/umbrella.d.ts +5 -0
  23. package/dist/index.d.ts +1 -1
  24. package/dist/modular-kernel.d.ts +11 -0
  25. package/dist/packages/commands/src/index.d.ts +96 -0
  26. package/dist/packages/core/src/di.d.ts +36 -0
  27. package/dist/packages/core/src/disposable.d.ts +27 -0
  28. package/dist/packages/core/src/errors.d.ts +69 -0
  29. package/dist/packages/core/src/events.d.ts +38 -0
  30. package/dist/packages/core/src/index.d.ts +6 -0
  31. package/dist/packages/core/src/path.d.ts +14 -0
  32. package/dist/packages/core/src/registry.d.ts +23 -0
  33. package/dist/packages/editor/src/index.d.ts +118 -0
  34. package/dist/packages/fs/src/backends.d.ts +37 -0
  35. package/dist/packages/fs/src/index.d.ts +3 -0
  36. package/dist/packages/fs/src/types.d.ts +40 -0
  37. package/dist/packages/fs/src/vfs-service.d.ts +33 -0
  38. package/dist/packages/preview/src/index.d.ts +34 -0
  39. package/dist/packages/runtime/src/index.d.ts +47 -0
  40. package/dist/packages/settings/src/builtin-schemas.d.ts +15 -0
  41. package/dist/packages/settings/src/configuration-service.d.ts +100 -0
  42. package/dist/packages/settings/src/index.d.ts +4 -0
  43. package/dist/packages/settings/src/jsonc.d.ts +20 -0
  44. package/dist/packages/settings/src/schema.d.ts +28 -0
  45. package/dist/packages/sql/src/completions.d.ts +8 -0
  46. package/dist/packages/sql/src/diagnostics.d.ts +2 -0
  47. package/dist/packages/sql/src/formatter.d.ts +2 -0
  48. package/dist/packages/sql/src/index.d.ts +7 -0
  49. package/dist/packages/sql/src/sql-editor.d.ts +2 -0
  50. package/dist/packages/sql/src/styles.d.ts +2 -0
  51. package/dist/packages/sql/src/tokenizer.d.ts +13 -0
  52. package/dist/packages/sql/src/types.d.ts +130 -0
  53. package/dist/packages/terminal/src/index.d.ts +54 -0
  54. package/dist/packages/ui/src/index.d.ts +4 -0
  55. package/dist/packages/ui/src/observability.d.ts +22 -0
  56. package/dist/packages/ui/src/plugin-registry.d.ts +89 -0
  57. package/dist/packages/ui/src/settings-dialog.d.ts +25 -0
  58. package/dist/packages/ui/src/themes.d.ts +35 -0
  59. package/dist/preview-sw.js +82 -24
  60. package/dist/runtime.d.ts +3 -3
  61. package/dist/runtime.esm.js +503 -73
  62. package/dist/runtime.js +501 -73
  63. package/dist/schemas.d.ts +234 -814
  64. package/dist/schemas.esm.js +19401 -3725
  65. package/dist/schemas.js +19404 -3728
  66. package/dist/scm.d.ts +13 -2
  67. package/dist/search.d.ts +5 -1
  68. package/dist/shell.d.ts +1 -1
  69. package/dist/shell.esm.js +435 -54
  70. package/dist/shell.js +435 -54
  71. package/dist/terminal.esm.js +242 -54
  72. package/dist/terminal.js +242 -54
  73. package/dist/workbench/diff-editor.d.ts +1 -0
  74. package/dist/workbench/index.d.ts +1 -1
  75. package/dist/workbench/styles.d.ts +1 -1
  76. package/dist/zip.d.ts +4 -3
  77. package/package.json +37 -8
  78. package/packages/commands/README.md +7 -0
  79. package/packages/commands/package.json +16 -0
  80. package/packages/commands/src/index.ts +467 -0
  81. package/packages/commands/tsconfig.json +22 -0
  82. package/packages/core/README.md +12 -0
  83. package/packages/core/package.json +13 -0
  84. package/packages/core/src/di.ts +147 -0
  85. package/packages/core/src/disposable.ts +112 -0
  86. package/packages/core/src/errors.ts +205 -0
  87. package/packages/core/src/events.ts +157 -0
  88. package/packages/core/src/index.ts +49 -0
  89. package/packages/core/src/path.ts +118 -0
  90. package/packages/core/src/registry.ts +61 -0
  91. package/packages/core/tsconfig.json +19 -0
  92. package/packages/editor/README.md +9 -0
  93. package/packages/editor/package.json +18 -0
  94. package/packages/editor/src/index.ts +344 -0
  95. package/packages/editor/tsconfig.json +24 -0
  96. package/packages/fs/README.md +7 -0
  97. package/packages/fs/package.json +16 -0
  98. package/packages/fs/src/backends.ts +301 -0
  99. package/packages/fs/src/index.ts +18 -0
  100. package/packages/fs/src/types.ts +44 -0
  101. package/packages/fs/src/vfs-service.ts +257 -0
  102. package/packages/fs/tsconfig.json +22 -0
  103. package/packages/preview/README.md +3 -0
  104. package/packages/preview/package.json +16 -0
  105. package/packages/preview/src/index.ts +125 -0
  106. package/packages/preview/tsconfig.json +22 -0
  107. package/packages/runtime/README.md +3 -0
  108. package/packages/runtime/package.json +17 -0
  109. package/packages/runtime/src/index.ts +134 -0
  110. package/packages/runtime/tsconfig.json +23 -0
  111. package/packages/settings/README.md +7 -0
  112. package/packages/settings/package.json +16 -0
  113. package/packages/settings/src/builtin-schemas.ts +235 -0
  114. package/packages/settings/src/configuration-service.ts +543 -0
  115. package/packages/settings/src/index.ts +37 -0
  116. package/packages/settings/src/jsonc.ts +189 -0
  117. package/packages/settings/src/schema.ts +164 -0
  118. package/packages/settings/tsconfig.json +22 -0
  119. package/packages/sql/README.md +12 -0
  120. package/packages/sql/package.json +13 -0
  121. package/packages/sql/src/completions.ts +359 -0
  122. package/packages/sql/src/diagnostics.ts +200 -0
  123. package/packages/sql/src/formatter.ts +271 -0
  124. package/packages/sql/src/index.ts +54 -0
  125. package/packages/sql/src/sql-editor.ts +802 -0
  126. package/packages/sql/src/styles.ts +501 -0
  127. package/packages/sql/src/tokenizer.ts +457 -0
  128. package/packages/sql/src/types.ts +148 -0
  129. package/packages/sql/tsconfig.json +19 -0
  130. package/packages/terminal/README.md +3 -0
  131. package/packages/terminal/package.json +16 -0
  132. package/packages/terminal/src/index.ts +183 -0
  133. package/packages/terminal/tsconfig.json +22 -0
  134. package/packages/ui/README.md +8 -0
  135. package/packages/ui/package.json +18 -0
  136. package/packages/ui/src/index.ts +36 -0
  137. package/packages/ui/src/observability.ts +175 -0
  138. package/packages/ui/src/plugin-registry.ts +274 -0
  139. package/packages/ui/src/settings-dialog.ts +293 -0
  140. package/packages/ui/src/themes.ts +174 -0
  141. package/packages/ui/tsconfig.json +24 -0
  142. package/src/code-lab.css +298 -2
  143. package/src/csp.ts +7 -10
  144. package/src/diagnostics.ts +42 -3
  145. package/src/extensions/cpp.ts +105 -24
  146. package/src/extensions/python.ts +260 -116
  147. package/src/extensions/umbrella.ts +5 -0
  148. package/src/index.ts +1 -1
  149. package/src/modular-kernel.ts +11 -0
  150. package/src/preview-sw.js +73 -12
  151. package/src/runtime.ts +501 -74
  152. package/src/schemas.ts +62 -62
  153. package/src/scm.ts +106 -19
  154. package/src/search.ts +71 -27
  155. package/src/shell.ts +433 -53
  156. package/src/terminal.ts +239 -52
  157. package/src/workbench/diff-editor.ts +106 -18
  158. package/src/workbench/drawer.ts +17 -4
  159. package/src/workbench/guided-pane.ts +12 -2
  160. package/src/workbench/icons.ts +5 -2
  161. package/src/workbench/share.ts +37 -8
  162. package/src/workbench/styles.ts +2 -1
  163. package/src/workbench/toolbar.ts +15 -4
  164. package/src/workbench.ts +2877 -284
  165. package/src/zip.ts +29 -7
  166. package/dist/runtime/index.d.ts +0 -4
  167. package/dist/shell/coreutils/compilers-cli.d.ts +0 -24
  168. package/dist/shell/index.d.ts +0 -4
  169. package/src/runtime/index.ts +0 -5
  170. package/src/shell/coreutils/compilers-cli.ts +0 -103
  171. package/src/shell/index.ts +0 -5
package/src/shell.ts CHANGED
@@ -1593,9 +1593,11 @@
1593
1593
  function createFallbackVfs() {
1594
1594
  const files = new Map();
1595
1595
  const dirs = new Set(['/', '/tmp', '/workspace', '/etc', '/home', '/home/user']);
1596
+ let _activeStdin = '';
1596
1597
 
1597
1598
  function norm(p) {
1598
- return PosixPath.normalize(p.startsWith('/') ? p : '/workspace/' + p);
1599
+ const s = String(p);
1600
+ return PosixPath.normalize(s.startsWith('/') ? s : '/workspace/' + s);
1599
1601
  }
1600
1602
 
1601
1603
  const emitter = {
@@ -1683,6 +1685,12 @@
1683
1685
  return Array.from(children).sort();
1684
1686
  },
1685
1687
  readFileSync(p, encoding) {
1688
+ if (p === 0 || p === '/dev/stdin') {
1689
+ if (!encoding || encoding === 'buffer') {
1690
+ return new TextEncoder().encode(_activeStdin);
1691
+ }
1692
+ return _activeStdin;
1693
+ }
1686
1694
  const np = norm(p);
1687
1695
  const f = files.get(np);
1688
1696
  if (!f) {
@@ -1695,6 +1703,9 @@
1695
1703
  }
1696
1704
  return f.data;
1697
1705
  },
1706
+ _setActiveStdin(text) {
1707
+ _activeStdin = text === null || text === undefined ? '' : String(text);
1708
+ },
1698
1709
  writeFileSync(p, data) {
1699
1710
  const np = norm(p);
1700
1711
  const parent = PosixPath.dirname(np);
@@ -2902,6 +2913,13 @@
2902
2913
  return out;
2903
2914
  }
2904
2915
 
2916
+ function quoteShellArg(arg) {
2917
+ const s = String(arg ?? '');
2918
+ if (s.length === 0) return "''";
2919
+ if (!/[\s"'\\$&|;<>()`!*?~#]/.test(s)) return s;
2920
+ return "'" + s.replace(/'/g, "'\\''") + "'";
2921
+ }
2922
+
2905
2923
  async function runPackageScript(scriptName, scriptArgs, ctx) {
2906
2924
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2907
2925
  if (!pkgData.scripts || !pkgData.scripts[scriptName]) {
@@ -2909,7 +2927,7 @@
2909
2927
  }
2910
2928
  let cmd = pkgData.scripts[scriptName];
2911
2929
  if (scriptArgs && scriptArgs.length > 0) {
2912
- cmd += ' ' + scriptArgs.join(' ');
2930
+ cmd += ' ' + scriptArgs.map(quoteShellArg).join(' ');
2913
2931
  }
2914
2932
  const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
2915
2933
  if (fallback) return fallback;
@@ -2946,9 +2964,31 @@
2946
2964
  '.gif': 'image/gif',
2947
2965
  '.webp': 'image/webp',
2948
2966
  '.ico': 'image/x-icon',
2967
+ '.woff': 'font/woff',
2968
+ '.woff2': 'font/woff2',
2969
+ '.ttf': 'font/ttf',
2970
+ '.otf': 'font/otf',
2971
+ '.wasm': 'application/wasm',
2972
+ '.pdf': 'application/pdf',
2973
+ '.mp3': 'audio/mpeg',
2974
+ '.mp4': 'video/mp4',
2975
+ '.webm': 'video/webm',
2949
2976
  '.txt': 'text/plain; charset=utf-8'
2950
2977
  };
2951
2978
 
2979
+ function isBinaryPreviewMime(mime) {
2980
+ const clean = String(mime || '').toLowerCase().split(';')[0].trim();
2981
+ if (!clean) return false;
2982
+ return !(
2983
+ clean.startsWith('text/') ||
2984
+ clean === 'application/javascript' ||
2985
+ clean === 'application/json' ||
2986
+ clean === 'application/xml' ||
2987
+ clean === 'application/xhtml+xml' ||
2988
+ clean === 'image/svg+xml'
2989
+ );
2990
+ }
2991
+
2952
2992
  function previewMimeFor(p) {
2953
2993
  const lower = String(p).toLowerCase();
2954
2994
  const dot = lower.lastIndexOf('.');
@@ -3132,7 +3172,8 @@
3132
3172
 
3133
3173
  function injectPreviewExtras(html, importMap) {
3134
3174
  let out = html;
3135
- const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
3175
+ const safeImportMapJson = JSON.stringify({ imports: importMap }, null, 2).replace(/</g, '\\u003c');
3176
+ const importMapTag = `<script type="importmap">\n${safeImportMapJson}\n</script>`;
3136
3177
  if (/<head[^>]*>/i.test(out)) {
3137
3178
  out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
3138
3179
  } else {
@@ -3162,6 +3203,11 @@
3162
3203
  const isFile = (p) => exists(p) && !isDir(p);
3163
3204
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
3164
3205
 
3206
+ const isWithinRoot = (p) => {
3207
+ const rootPrefix = rootDir === '/' ? '/' : rootDir + '/';
3208
+ return p === rootDir || p.startsWith(rootPrefix);
3209
+ };
3210
+
3165
3211
  const resolveLocalTarget = (baseDir, rawSpec) => {
3166
3212
  if (!rawSpec || typeof rawSpec !== 'string') return null;
3167
3213
  const clean = rawSpec.split(/[?#]/)[0].trim();
@@ -3169,6 +3215,7 @@
3169
3215
  const candidateBase = clean.startsWith('/')
3170
3216
  ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
3171
3217
  : PosixPath.join(baseDir, clean);
3218
+ if (!isWithinRoot(candidateBase)) return null;
3172
3219
  if (isFile(candidateBase)) return candidateBase;
3173
3220
  const cands = [
3174
3221
  candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
@@ -3177,7 +3224,7 @@
3177
3224
  PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
3178
3225
  ];
3179
3226
  for (const c of cands) {
3180
- if (isFile(c)) return c;
3227
+ if (isWithinRoot(c) && isFile(c)) return c;
3181
3228
  }
3182
3229
  return null;
3183
3230
  };
@@ -3306,7 +3353,7 @@
3306
3353
  if (/@import\s+['"]tailwindcss['"]/i.test(cssContent)) {
3307
3354
  needsTailwindBrowser = true;
3308
3355
  }
3309
- const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget));
3356
+ const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget)).replace(/<\/style/gi, '<\\/style');
3310
3357
  return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${resolvedCss}\n</style>`;
3311
3358
  });
3312
3359
 
@@ -3318,7 +3365,7 @@
3318
3365
  if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
3319
3366
  const rawScript = readText(scriptTarget);
3320
3367
  if (rawScript === null) return fullTag;
3321
- const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
3368
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget).replace(/<\/script/gi, '<\\/script');
3322
3369
  const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget) || /^\s*(?:import|export)\b/m.test(rawScript);
3323
3370
  const typeAttr = isMod ? ' type="module"' : '';
3324
3371
  return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
@@ -3341,6 +3388,12 @@
3341
3388
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
3342
3389
  const rel = pathname.replace(/^\/+/, '');
3343
3390
  let target = PosixPath.join(rootDir, rel);
3391
+ if (!isWithinRoot(target)) {
3392
+ return new Response(
3393
+ '<!doctype html><meta charset="utf-8"><title>403</title><h1>403 Forbidden</h1>',
3394
+ { status: 403, headers: { 'content-type': 'text/html; charset=utf-8' } }
3395
+ );
3396
+ }
3344
3397
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
3345
3398
 
3346
3399
  if (!rel || pathname.endsWith('/') || isDir(target)) {
@@ -3365,12 +3418,31 @@
3365
3418
  target = (!exists(rootIdx) && exists(pubIdx)) ? pubIdx : rootIdx; // SPA fallback
3366
3419
  }
3367
3420
  if (!exists(target)) {
3421
+ const safePath = String(pathname)
3422
+ .replace(/&/g, '&amp;')
3423
+ .replace(/</g, '&lt;')
3424
+ .replace(/>/g, '&gt;')
3425
+ .replace(/"/g, '&quot;');
3368
3426
  return new Response(
3369
- `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
3427
+ `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${safePath}</p>`,
3370
3428
  { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
3371
3429
  );
3372
3430
  }
3373
3431
 
3432
+ const mimeType = previewMimeFor(target);
3433
+ if (isBinaryPreviewMime(mimeType)) {
3434
+ let rawBytes = null;
3435
+ try {
3436
+ rawBytes = ctx.vfs.readFileSync(target);
3437
+ } catch (err) {
3438
+ _shellLogger.debug('Binary preview asset read failed.', target, err);
3439
+ }
3440
+ const binaryBody = rawBytes instanceof Uint8Array
3441
+ ? rawBytes
3442
+ : (typeof rawBytes === 'string' ? new TextEncoder().encode(rawBytes) : new Uint8Array(0));
3443
+ return new Response(binaryBody, { status: 200, headers: { 'content-type': mimeType } });
3444
+ }
3445
+
3374
3446
  let body = readText(target);
3375
3447
  if (body === null) body = '';
3376
3448
  if (/\.html?$/i.test(target)) {
@@ -3386,7 +3458,7 @@
3386
3458
  }
3387
3459
  }
3388
3460
 
3389
- return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
3461
+ return new Response(body, { status: 200, headers: { 'content-type': mimeType } });
3390
3462
  };
3391
3463
 
3392
3464
  const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
@@ -5517,13 +5589,17 @@
5517
5589
 
5518
5590
  const count = Math.max(1, result.filesWritten);
5519
5591
  const kb = Math.max(0.1, result.totalBytes / 1024).toFixed(1);
5592
+ if (!enumeratedEmitted) {
5593
+ streamLine(`remote: Enumerating objects: ${count}, done.\n`);
5594
+ streamLine(`remote: Counting objects: 100% (${count}/${count}), done.\n`);
5595
+ }
5520
5596
  streamLine(`Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`);
5521
5597
  const stdout =
5522
5598
  `Cloning into '${dirDisplayName}'...\n` +
5523
5599
  `remote: Enumerating objects: ${count}, done.\n` +
5524
5600
  `remote: Counting objects: 100% (${count}/${count}), done.\n` +
5525
5601
  `Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`;
5526
- return { code: 0, stdout, stderr: '' };
5602
+ return { code: 0, stdout, stderr: '', alreadyStreamed: canStream };
5527
5603
  } catch (err) {
5528
5604
  if (ctx.signal && ctx.signal.aborted) {
5529
5605
  return { code: 130, stdout: '', stderr: '', aborted: true };
@@ -5964,6 +6040,9 @@
5964
6040
  mode: 'repl',
5965
6041
  replCode: code,
5966
6042
  printReplResult: false,
6043
+ stdin: ctx.stdin || '',
6044
+ env: ctx.env,
6045
+ cwd: ctx.cwd,
5967
6046
  vfs: ctx.vfs,
5968
6047
  activePortTable: ctx.shell.portTable,
5969
6048
  pid: ctx.pid,
@@ -5981,6 +6060,9 @@
5981
6060
  mode: 'repl',
5982
6061
  replCode: code,
5983
6062
  printReplResult: true,
6063
+ stdin: ctx.stdin || '',
6064
+ env: ctx.env,
6065
+ cwd: ctx.cwd,
5984
6066
  vfs: ctx.vfs,
5985
6067
  activePortTable: ctx.shell.portTable,
5986
6068
  pid: ctx.pid,
@@ -6020,6 +6102,9 @@
6020
6102
  const res = await executeInVirtualRuntime({
6021
6103
  mode: 'test',
6022
6104
  entry: f,
6105
+ stdin: ctx.stdin || '',
6106
+ env: ctx.env,
6107
+ cwd: ctx.cwd,
6023
6108
  vfs: ctx.vfs,
6024
6109
  activePortTable: ctx.shell.portTable,
6025
6110
  pid: ctx.pid,
@@ -6045,6 +6130,9 @@
6045
6130
  mode: 'run',
6046
6131
  entry: scriptFile,
6047
6132
  argv: ['node', scriptFile, ...scriptArgs],
6133
+ stdin: ctx.stdin || '',
6134
+ env: ctx.env,
6135
+ cwd: ctx.cwd,
6048
6136
  vfs: ctx.vfs,
6049
6137
  activePortTable: ctx.shell.portTable,
6050
6138
  pid: ctx.pid,
@@ -6212,6 +6300,9 @@
6212
6300
  const res = await pyCompiler({
6213
6301
  entry: entryFile,
6214
6302
  source: codeToRun,
6303
+ stdin: ctx.stdin || '',
6304
+ env: ctx.env,
6305
+ cwd: ctx.cwd,
6215
6306
  vfs: ctx.vfs,
6216
6307
  onStdout: (t) => {
6217
6308
  outText += t;
@@ -6278,9 +6369,9 @@
6278
6369
  };
6279
6370
  }
6280
6371
  return {
6281
- code: 0,
6282
- stdout: `Successfully installed ${pkgs.join(', ') || 'packages'}\n`,
6283
- stderr: ''
6372
+ code: 1,
6373
+ stdout: '',
6374
+ stderr: 'pip: Python WebAssembly toolchain is not enabled. Enable pythonExtension from "@innovatorved/code-lab/extensions/python".\n'
6284
6375
  };
6285
6376
  }
6286
6377
  return { code: 0, stdout: 'pip 24.0 (Pyodide micropip)\n', stderr: '' };
@@ -6398,6 +6489,9 @@
6398
6489
  mode: 'repl',
6399
6490
  replCode: code,
6400
6491
  printReplResult: false,
6492
+ stdin: ctx.stdin || '',
6493
+ env: ctx.env,
6494
+ cwd: ctx.cwd,
6401
6495
  vfs: ctx.vfs,
6402
6496
  activePortTable: ctx.shell.portTable,
6403
6497
  pid: ctx.pid,
@@ -6437,6 +6531,9 @@
6437
6531
  const res = await executeInVirtualRuntime({
6438
6532
  mode: 'test',
6439
6533
  entry: f,
6534
+ stdin: ctx.stdin || '',
6535
+ env: ctx.env,
6536
+ cwd: ctx.cwd,
6440
6537
  vfs: ctx.vfs,
6441
6538
  activePortTable: ctx.shell.portTable,
6442
6539
  pid: ctx.pid,
@@ -6464,6 +6561,9 @@
6464
6561
  mode: 'run',
6465
6562
  entry: resolved,
6466
6563
  argv: ['bun', resolved, ...scriptArgs],
6564
+ stdin: ctx.stdin || '',
6565
+ env: ctx.env,
6566
+ cwd: ctx.cwd,
6467
6567
  vfs: ctx.vfs,
6468
6568
  activePortTable: ctx.shell.portTable,
6469
6569
  pid: ctx.pid,
@@ -6488,6 +6588,9 @@
6488
6588
  mode: 'run',
6489
6589
  entry: resolved,
6490
6590
  argv: ['bun', resolved, ...scriptArgs],
6591
+ stdin: ctx.stdin || '',
6592
+ env: ctx.env,
6593
+ cwd: ctx.cwd,
6491
6594
  vfs: ctx.vfs,
6492
6595
  activePortTable: ctx.shell.portTable,
6493
6596
  pid: ctx.pid,
@@ -6586,7 +6689,8 @@
6586
6689
  if (ctx.vfs.existsSync(binPath)) {
6587
6690
  return await ctx.commands.node([binPath, ...cmdArgs], ctx);
6588
6691
  }
6589
- return await ctx.shell.execute(cmd + (cmdArgs.length ? ' ' + cmdArgs.join(' ') : ''));
6692
+ const cmdStr = [cmd, ...cmdArgs].map(quoteShellArg).join(' ');
6693
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
6590
6694
  },
6591
6695
 
6592
6696
  async bunx(args, ctx) {
@@ -6657,7 +6761,8 @@
6657
6761
  if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
6658
6762
  const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
6659
6763
  if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
6660
- return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
6764
+ const cmdStr = [cmd, ...args.slice(2)].map(quoteShellArg).join(' ');
6765
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
6661
6766
  }
6662
6767
 
6663
6768
  if (sub === 'dlx') {
@@ -6767,12 +6872,24 @@
6767
6872
  if (!method) method = 'GET';
6768
6873
 
6769
6874
  const portTable = (ctx.shell && ctx.shell.portTable) || null;
6875
+ const fetchImpl = (ctx.shell && ctx.shell.options && typeof (ctx.shell.options.fetch || ctx.shell.options.fetchImpl) === 'function')
6876
+ ? (ctx.shell.options.fetch || ctx.shell.options.fetchImpl)
6877
+ : fetch;
6878
+ let isLoopback = false;
6879
+ try {
6880
+ const parsedUrl = new URL(url);
6881
+ const host = parsedUrl.hostname.toLowerCase();
6882
+ isLoopback = host === 'localhost' || host === '127.0.0.1' || host === '0.0.0.0' || host === '::1' || host === '[::1]';
6883
+ } catch (err) {
6884
+ _shellLogger.debug('curl URL parse fallback', url, err);
6885
+ }
6770
6886
  let resp = null;
6771
6887
  let lastErr = null;
6888
+ const maxAttempts = portTable && isLoopback ? 25 : 1;
6772
6889
 
6773
- for (let attempt = 0; attempt < 25; attempt++) {
6890
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
6774
6891
  try {
6775
- if (portTable) {
6892
+ if (portTable && isLoopback) {
6776
6893
  resp = await portTable.dispatchRequest(url, {
6777
6894
  method,
6778
6895
  headers,
@@ -6781,7 +6898,7 @@
6781
6898
  lastErr = null;
6782
6899
  break;
6783
6900
  } else {
6784
- resp = await fetch(url, {
6901
+ resp = await fetchImpl(url, {
6785
6902
  method,
6786
6903
  headers,
6787
6904
  body: data
@@ -6792,7 +6909,9 @@
6792
6909
  } catch (err) {
6793
6910
  lastErr = err;
6794
6911
  if (err && err.chaosEffect) break;
6795
- await new Promise(r => setTimeout(r, 15));
6912
+ if (attempt + 1 < maxAttempts) {
6913
+ await new Promise(r => setTimeout(r, 15));
6914
+ }
6796
6915
  }
6797
6916
  }
6798
6917
 
@@ -6871,6 +6990,17 @@
6871
6990
  concurrency = Math.min(concurrency, totalRequests);
6872
6991
 
6873
6992
  const portTable = (ctx.shell && ctx.shell.portTable) || null;
6993
+ const fetchImpl = (ctx.shell && ctx.shell.options && typeof (ctx.shell.options.fetch || ctx.shell.options.fetchImpl) === 'function')
6994
+ ? (ctx.shell.options.fetch || ctx.shell.options.fetchImpl)
6995
+ : fetch;
6996
+ let isLoopback = false;
6997
+ try {
6998
+ const parsedUrl = new URL(url);
6999
+ const host = parsedUrl.hostname.toLowerCase();
7000
+ isLoopback = host === 'localhost' || host === '127.0.0.1' || host === '0.0.0.0' || host === '::1' || host === '[::1]';
7001
+ } catch (err) {
7002
+ _shellLogger.debug('hey URL parse fallback', url, err);
7003
+ }
6874
7004
  const latencies = [];
6875
7005
  const statusCounts = {};
6876
7006
  const errorCounts = {};
@@ -6886,10 +7016,10 @@
6886
7016
  const reqStart = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();
6887
7017
  try {
6888
7018
  let resp;
6889
- if (portTable) {
7019
+ if (portTable && isLoopback) {
6890
7020
  resp = await portTable.dispatchRequest(url, { method, headers: { ...headers }, body });
6891
7021
  } else {
6892
- resp = await fetch(url, { method, headers: { ...headers }, body });
7022
+ resp = await fetchImpl(url, { method, headers: { ...headers }, body });
6893
7023
  }
6894
7024
  const reqEnd = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();
6895
7025
  const dur = Math.max(0.05, reqEnd - reqStart);
@@ -7822,6 +7952,15 @@
7822
7952
  }
7823
7953
 
7824
7954
  this.history.push(trimmed);
7955
+ if (this.history.length > 1000) {
7956
+ this.history.splice(0, this.history.length - 1000);
7957
+ }
7958
+ if (this.jobs.size > 256) {
7959
+ for (const [jid, j] of this.jobs.entries()) {
7960
+ if (this.jobs.size <= 256) break;
7961
+ if (j && j.status !== 'Running') this.jobs.delete(jid);
7962
+ }
7963
+ }
7825
7964
 
7826
7965
  const cwd = execOptions.cwd ? this.resolvePath(execOptions.cwd) : this.cwd;
7827
7966
  this.cwd = cwd;
@@ -7840,18 +7979,27 @@
7840
7979
  if (item.background) {
7841
7980
  const pid = this.nextPid++;
7842
7981
  const jobId = this.nextJobId++;
7982
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
7843
7983
  const job = {
7844
7984
  id: jobId,
7845
7985
  pid,
7846
7986
  command: trimmed,
7847
7987
  status: 'Running',
7848
- startTime: Date.now()
7988
+ startTime: Date.now(),
7989
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
7849
7990
  };
7850
7991
  this.jobs.set(jobId, job);
7851
7992
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
7852
7993
 
7853
- // Run in background promise
7854
- this._executeAstNode(item.node, { ...execOptions, env: Object.assign({}, this.env, currentEnv), cwd: this.cwd, pid, isBackground: true })
7994
+ // Run in background promise with its own independent AbortSignal
7995
+ this._executeAstNode(item.node, {
7996
+ ...execOptions,
7997
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
7998
+ env: Object.assign({}, this.env, currentEnv),
7999
+ cwd: this.cwd,
8000
+ pid,
8001
+ isBackground: true
8002
+ })
7855
8003
  .then(res => {
7856
8004
  if (job.status !== 'Terminated') {
7857
8005
  job.status = 'Done';
@@ -7882,6 +8030,10 @@
7882
8030
  if (res.aborted || (execOptions.signal && execOptions.signal.aborted)) {
7883
8031
  return { code: 130, exitCode: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
7884
8032
  }
8033
+ if (res.controlFlow && res.controlFlow.type === 'exit') {
8034
+ lastCode = res.controlFlow.code !== undefined ? res.controlFlow.code : lastCode;
8035
+ break;
8036
+ }
7885
8037
  }
7886
8038
  }
7887
8039
 
@@ -7892,6 +8044,218 @@
7892
8044
  return this.execute(commandLine, execOptions);
7893
8045
  }
7894
8046
 
8047
+ async _expandHeredocBody(rawBody, cmdEnv) {
8048
+ const src = String(rawBody || '');
8049
+ let out = '';
8050
+ let i = 0;
8051
+ while (i < src.length) {
8052
+ const ch = src[i];
8053
+ if (ch === '\\' && i + 1 < src.length && '$`\\\n'.includes(src[i + 1])) {
8054
+ if (src[i + 1] === '\n') {
8055
+ i += 2;
8056
+ continue;
8057
+ }
8058
+ out += src[i + 1];
8059
+ i += 2;
8060
+ continue;
8061
+ }
8062
+ if (ch === '$' && src[i + 1] === '(' && src[i + 2] === '(') {
8063
+ i += 3;
8064
+ let depth = 2;
8065
+ let expr = '';
8066
+ while (i < src.length && depth > 0) {
8067
+ if (src[i] === '(') { depth++; expr += '('; i++; }
8068
+ else if (src[i] === ')') {
8069
+ if (depth === 2 && src[i + 1] === ')') { depth = 0; i += 2; break; }
8070
+ depth--;
8071
+ if (depth > 0) expr += ')';
8072
+ i++;
8073
+ } else {
8074
+ expr += src[i++];
8075
+ }
8076
+ }
8077
+ out += evaluateArithmetic(expr, cmdEnv, this.env);
8078
+ continue;
8079
+ }
8080
+ if (ch === '$' && src[i + 1] === '(') {
8081
+ i += 2;
8082
+ let depth = 1;
8083
+ let sub = '';
8084
+ while (i < src.length && depth > 0) {
8085
+ if (src[i] === '(') depth++;
8086
+ else if (src[i] === ')') depth--;
8087
+ if (depth > 0) sub += src[i];
8088
+ i++;
8089
+ }
8090
+ out += await this._executeSubshell(sub, cmdEnv);
8091
+ continue;
8092
+ }
8093
+ if (ch === '`') {
8094
+ i++;
8095
+ let sub = '';
8096
+ while (i < src.length && src[i] !== '`') sub += src[i++];
8097
+ if (i < src.length && src[i] === '`') i++;
8098
+ out += await this._executeSubshell(sub, cmdEnv);
8099
+ continue;
8100
+ }
8101
+ if (ch === '$') {
8102
+ i++;
8103
+ if (src[i] === '{') {
8104
+ i++;
8105
+ let varName = '';
8106
+ let bDepth = 1;
8107
+ while (i < src.length && bDepth > 0) {
8108
+ if (src[i] === '{') bDepth++;
8109
+ else if (src[i] === '}') bDepth--;
8110
+ if (bDepth > 0) varName += src[i];
8111
+ i++;
8112
+ }
8113
+ out += this._expandVariable(varName, cmdEnv);
8114
+ } else if (i < src.length && /[0-9?!$#@*]/.test(src[i])) {
8115
+ out += this._expandVariable(src[i++], cmdEnv);
8116
+ } else if (i < src.length && /[a-zA-Z_]/.test(src[i])) {
8117
+ let varName = '';
8118
+ while (i < src.length && /[a-zA-Z0-9_]/.test(src[i])) varName += src[i++];
8119
+ out += this._expandVariable(varName, cmdEnv);
8120
+ } else {
8121
+ out += '$';
8122
+ }
8123
+ continue;
8124
+ }
8125
+ out += ch;
8126
+ i++;
8127
+ }
8128
+ return out;
8129
+ }
8130
+
8131
+ async _resolveInputRedirect(red, cmdEnv) {
8132
+ if (red.type === '<') {
8133
+ const target = await this.evaluateWord(red.target, cmdEnv);
8134
+ const absTarget = this.resolvePath(target);
8135
+ if (!this.vfs.existsSync(absTarget)) {
8136
+ return { ok: false, error: { code: 1, stdout: '', stderr: `shell: ${target}: No such file or directory\n` } };
8137
+ }
8138
+ try {
8139
+ return { ok: true, stdin: this.vfs.readFileSync(absTarget, 'utf8') };
8140
+ } catch (err) {
8141
+ return { ok: false, error: { code: 1, stdout: '', stderr: `shell: ${target}: ${err.message}\n` } };
8142
+ }
8143
+ }
8144
+ if (red.type === '<<<') {
8145
+ const val = await this.evaluateWord(red.target, cmdEnv);
8146
+ return { ok: true, stdin: val + '\n' };
8147
+ }
8148
+ if (red.type === '<<') {
8149
+ let body = String(red.body || '');
8150
+ if (red.stripTabs) {
8151
+ body = body.replace(/^\t+/gm, '');
8152
+ }
8153
+ if (!red.quoted) {
8154
+ body = await this._expandHeredocBody(body, cmdEnv);
8155
+ }
8156
+ return { ok: true, stdin: body };
8157
+ }
8158
+ return null;
8159
+ }
8160
+
8161
+ _evaluateDoubleBracket(rawArgs) {
8162
+ const closeIdx = rawArgs.lastIndexOf(']]');
8163
+ if (closeIdx === -1) {
8164
+ return { code: 2, stdout: '', stderr: 'shell: [[: missing `]]`\n' };
8165
+ }
8166
+ const tokens = rawArgs.slice(0, closeIdx);
8167
+ let idx = 0;
8168
+
8169
+ const globToRegExp = (pat) => {
8170
+ let re = '^';
8171
+ for (let i = 0; i < pat.length; i++) {
8172
+ const c = pat[i];
8173
+ if (c === '*') re += '.*';
8174
+ else if (c === '?') re += '.';
8175
+ else re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
8176
+ }
8177
+ return new RegExp(re + '$');
8178
+ };
8179
+
8180
+ const parseOr = () => {
8181
+ let left = parseAnd();
8182
+ while (tokens[idx] === '||') {
8183
+ idx++;
8184
+ const right = parseAnd();
8185
+ left = left || right;
8186
+ }
8187
+ return left;
8188
+ };
8189
+
8190
+ const parseAnd = () => {
8191
+ let left = parseNot();
8192
+ while (tokens[idx] === '&&') {
8193
+ idx++;
8194
+ const right = parseNot();
8195
+ left = left && right;
8196
+ }
8197
+ return left;
8198
+ };
8199
+
8200
+ const parseNot = () => {
8201
+ if (tokens[idx] === '!') {
8202
+ idx++;
8203
+ return !parseNot();
8204
+ }
8205
+ return parsePrimary();
8206
+ };
8207
+
8208
+ const parsePrimary = () => {
8209
+ if (idx >= tokens.length) return false;
8210
+ if (tokens[idx] === '(') {
8211
+ idx++;
8212
+ const val = parseOr();
8213
+ if (tokens[idx] === ')') idx++;
8214
+ return val;
8215
+ }
8216
+ const unary = tokens[idx];
8217
+ if (/^-(?:z|n|e|f|d|s)$/.test(unary) && idx + 1 < tokens.length) {
8218
+ idx++;
8219
+ const operand = String(tokens[idx++] ?? '');
8220
+ if (unary === '-z') return operand.length === 0;
8221
+ if (unary === '-n') return operand.length > 0;
8222
+ const abs = this.resolvePath(operand);
8223
+ const exists = this.vfs.existsSync(abs);
8224
+ if (unary === '-e') return exists;
8225
+ if (!exists) return false;
8226
+ const st = this.vfs.statSync(abs);
8227
+ if (unary === '-d') return Boolean(st && st.isDirectory());
8228
+ if (unary === '-f') return Boolean(st && !st.isDirectory());
8229
+ if (unary === '-s') return Boolean(st && !st.isDirectory() && st.size > 0);
8230
+ }
8231
+ const left = String(tokens[idx++] ?? '');
8232
+ const op = tokens[idx];
8233
+ if (op && /^(?:==|=|!=|=~|<|>|-eq|-ne|-lt|-le|-gt|-ge)$/.test(op) && idx + 1 < tokens.length) {
8234
+ idx++;
8235
+ const right = String(tokens[idx++] ?? '');
8236
+ if (op === '==' || op === '=') return globToRegExp(right).test(left);
8237
+ if (op === '!=') return !globToRegExp(right).test(left);
8238
+ if (op === '=~') {
8239
+ try { return new RegExp(right).test(left); } catch (err) { _shellLogger.debug('[[ =~ invalid regex', right, err); return false; }
8240
+ }
8241
+ if (op === '<') return left < right;
8242
+ if (op === '>') return left > right;
8243
+ const ln = Number(left) || 0;
8244
+ const rn = Number(right) || 0;
8245
+ if (op === '-eq') return ln === rn;
8246
+ if (op === '-ne') return ln !== rn;
8247
+ if (op === '-lt') return ln < rn;
8248
+ if (op === '-le') return ln <= rn;
8249
+ if (op === '-gt') return ln > rn;
8250
+ if (op === '-ge') return ln >= rn;
8251
+ }
8252
+ return left.length > 0;
8253
+ };
8254
+
8255
+ const ok = parseOr();
8256
+ return { code: ok ? 0 : 1, stdout: '', stderr: '' };
8257
+ }
8258
+
7895
8259
  async _executeWithRedirects(redirects, context, execFn) {
7896
8260
  if (!redirects || redirects.length === 0) {
7897
8261
  return execFn(context);
@@ -7903,22 +8267,15 @@
7903
8267
  let effectiveStdin = context.stdin || '';
7904
8268
 
7905
8269
  for (const red of redirects) {
7906
- if (red.type === '<') {
7907
- const target = await this.evaluateWord(red.target, cmdEnv);
7908
- const absTarget = this.resolvePath(target);
7909
- if (!this.vfs.existsSync(absTarget)) {
7910
- return { code: 1, stdout: '', stderr: `shell: ${target}: No such file or directory\n` };
7911
- }
7912
- try {
7913
- effectiveStdin = this.vfs.readFileSync(absTarget, 'utf8');
7914
- } catch (err) {
7915
- return { code: 1, stdout: '', stderr: `shell: ${target}: ${err.message}\n` };
7916
- }
8270
+ if (red.type === '<' || red.type === '<<' || red.type === '<<<') {
8271
+ const inRes = await this._resolveInputRedirect(red, cmdEnv);
8272
+ if (inRes && !inRes.ok) return inRes.error;
8273
+ if (inRes && inRes.ok) effectiveStdin = inRes.stdin;
7917
8274
  }
7918
8275
  }
7919
8276
 
7920
8277
  for (const red of redirects) {
7921
- if (red.type === '<') continue;
8278
+ if (red.type === '<' || red.type === '<<' || red.type === '<<<') continue;
7922
8279
  if (red.type === '>' || red.type === '>>' || red.type === '&>') {
7923
8280
  const target = await this.evaluateWord(red.target, cmdEnv);
7924
8281
  const abs = this.resolvePath(target);
@@ -8005,17 +8362,24 @@
8005
8362
  if (item.background) {
8006
8363
  const pid = this.nextPid++;
8007
8364
  const jobId = this.nextJobId++;
8365
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
8008
8366
  const job = {
8009
8367
  id: jobId,
8010
8368
  pid,
8011
8369
  command: 'background',
8012
8370
  status: 'Running',
8013
- startTime: Date.now()
8371
+ startTime: Date.now(),
8372
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
8014
8373
  };
8015
8374
  this.jobs.set(jobId, job);
8016
8375
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
8017
8376
 
8018
- this._executeAstNode(item.node, { ...context, pid, isBackground: true })
8377
+ this._executeAstNode(item.node, {
8378
+ ...context,
8379
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
8380
+ pid,
8381
+ isBackground: true
8382
+ })
8019
8383
  .then(res => {
8020
8384
  if (job.status !== 'Terminated') {
8021
8385
  job.status = 'Done';
@@ -8131,7 +8495,11 @@
8131
8495
  wordItems.push(...(innerCtx.positionalArgs || []));
8132
8496
  }
8133
8497
 
8498
+ let loopIter = 0;
8134
8499
  for (const val of wordItems) {
8500
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
8501
+ await new Promise((r) => setTimeout(r, 0));
8502
+ }
8135
8503
  if (innerCtx.signal && innerCtx.signal.aborted) {
8136
8504
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
8137
8505
  }
@@ -8176,7 +8544,11 @@
8176
8544
  let combinedStderr = '';
8177
8545
  let lastCode = 0;
8178
8546
 
8547
+ let loopIter = 0;
8179
8548
  while (true) {
8549
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
8550
+ await new Promise((r) => setTimeout(r, 0));
8551
+ }
8180
8552
  if (innerCtx.signal && innerCtx.signal.aborted) {
8181
8553
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
8182
8554
  }
@@ -8412,7 +8784,20 @@
8412
8784
  args.push(...expanded);
8413
8785
  }
8414
8786
 
8415
- // 3. Built-in flow control
8787
+ // 3. Built-in flow control & POSIX special builtins
8788
+ if (cmdName === ':') {
8789
+ Object.assign(this.env, cmdEnv);
8790
+ Object.assign(context.env, cmdEnv);
8791
+ return { code: 0, stdout: '', stderr: '' };
8792
+ }
8793
+ if (cmdName === 'exit') {
8794
+ const rawCode = args.length > 0 ? parseInt(args[0], 10) : parseInt(this.env['?'] || '0', 10);
8795
+ const code = Number.isNaN(rawCode) ? 2 : ((rawCode % 256) + 256) % 256;
8796
+ return { code, stdout: '', stderr: '', controlFlow: { type: 'exit', code } };
8797
+ }
8798
+ if (cmdName === '[[') {
8799
+ return this._evaluateDoubleBracket(args);
8800
+ }
8416
8801
  if (cmdName === 'break') {
8417
8802
  const count = parseInt(args[0], 10) || 1;
8418
8803
  return { code: 0, stdout: '', stderr: '', controlFlow: { type: 'break', count } };
@@ -8430,20 +8815,13 @@
8430
8815
  return { code: 130, stdout: '', stderr: '', aborted: true };
8431
8816
  }
8432
8817
 
8433
- // 4. Process input redirection (<, 0<)
8818
+ // 4. Process input redirection (<, 0<, <<, <<-, <<<)
8434
8819
  let effectiveStdin = context.stdin || '';
8435
8820
  for (const red of cmdNode.redirects) {
8436
- if (red.type === '<') {
8437
- const target = await this.evaluateWord(red.target, cmdEnv);
8438
- const absTarget = this.resolvePath(target);
8439
- if (!this.vfs.existsSync(absTarget)) {
8440
- return { code: 1, stdout: '', stderr: `shell: ${target}: No such file or directory\n` };
8441
- }
8442
- try {
8443
- effectiveStdin = this.vfs.readFileSync(absTarget, 'utf8');
8444
- } catch (err) {
8445
- return { code: 1, stdout: '', stderr: `shell: ${target}: ${err.message}\n` };
8446
- }
8821
+ if (red.type === '<' || red.type === '<<' || red.type === '<<<') {
8822
+ const inRes = await this._resolveInputRedirect(red, cmdEnv);
8823
+ if (inRes && !inRes.ok) return inRes.error;
8824
+ if (inRes && inRes.ok) effectiveStdin = inRes.stdin;
8447
8825
  }
8448
8826
  }
8449
8827
 
@@ -8452,7 +8830,7 @@
8452
8830
  let fd2 = { type: 'stderr' };
8453
8831
 
8454
8832
  for (const red of cmdNode.redirects) {
8455
- if (red.type === '<') continue;
8833
+ if (red.type === '<' || red.type === '<<' || red.type === '<<<') continue;
8456
8834
  if (red.type === '>' || red.type === '>>' || red.type === '&>') {
8457
8835
  const target = await this.evaluateWord(red.target, cmdEnv);
8458
8836
  const abs = this.resolvePath(target);
@@ -8643,7 +9021,9 @@
8643
9021
 
8644
9022
  // Route any remaining unstreamed output
8645
9023
  if (res.stdout) {
8646
- if (streamedStdoutBytes > 0) {
9024
+ if (res.alreadyStreamed) {
9025
+ stdoutOut = res.stdout;
9026
+ } else if (streamedStdoutBytes > 0) {
8647
9027
  if (res.stdout.length > streamedStdoutBytes) {
8648
9028
  routeOutput(fd1, res.stdout.slice(streamedStdoutBytes), true);
8649
9029
  }
@@ -8702,7 +9082,7 @@ export const tokenizeShell: (input: string) => any[] = _hostShell.tokenizeShell;
8702
9082
  export const PosixShell: any = _hostShell.PosixShell;
8703
9083
  export const COREUTILS: Record<string, any> = _hostShell.COREUTILS;
8704
9084
  export const PosixPath: any = _hostShell.PosixPath;
8705
- export const expandGlob: (pattern: string, vfs: any, cwd?: string) => string[] = _hostShell.expandGlob;
9085
+ export const expandGlob: (pattern: string, cwd: string, vfs: any) => string[] = _hostShell.expandGlob;
8706
9086
  export const createVirtualPortTable: () => any = _hostShell.createVirtualPortTable;
8707
9087
  export const parseGitHubRepoUrl: (input: string) => any = _hostShell.parseGitHubRepoUrl;
8708
9088
  export const cloneGitHubRepository: (repoInput: string, vfs: any, options?: any) => Promise<any> = _hostShell.cloneGitHubRepository;