@innovatorved/code-lab 0.3.2 → 0.5.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 (164) hide show
  1. package/ARCHITECTURE.md +5 -3
  2. package/CHANGELOG.md +41 -0
  3. package/README.md +53 -175
  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 +1799 -98
  10. package/dist/code-lab.d.ts +110 -15
  11. package/dist/code-lab.esm.js +49678 -23253
  12. package/dist/code-lab.js +49648 -23251
  13. package/dist/code-lab.umd.js +75766 -0
  14. package/dist/diagnostics.d.ts +3 -0
  15. package/dist/extensions/cpp.esm.js +19504 -3788
  16. package/dist/extensions/cpp.js +19501 -3785
  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 +19597 -3788
  21. package/dist/extensions/python.js +19597 -3788
  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 +107 -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 +90 -0
  57. package/dist/packages/ui/src/settings-dialog.d.ts +53 -0
  58. package/dist/packages/ui/src/themes.d.ts +40 -0
  59. package/dist/preview-sw.js +53 -12
  60. package/dist/runtime.d.ts +3 -3
  61. package/dist/runtime.esm.js +467 -44
  62. package/dist/runtime.js +465 -44
  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 +92 -11
  67. package/dist/shell.d.ts +1 -1
  68. package/dist/shell.esm.js +1300 -151
  69. package/dist/shell.js +1300 -151
  70. package/dist/storage.d.ts +47 -0
  71. package/dist/terminal.esm.js +62 -3
  72. package/dist/terminal.js +62 -3
  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/package.json +38 -9
  77. package/packages/commands/README.md +7 -0
  78. package/packages/commands/package.json +16 -0
  79. package/packages/commands/src/index.ts +467 -0
  80. package/packages/commands/tsconfig.json +22 -0
  81. package/packages/core/README.md +12 -0
  82. package/packages/core/package.json +13 -0
  83. package/packages/core/src/di.ts +147 -0
  84. package/packages/core/src/disposable.ts +112 -0
  85. package/packages/core/src/errors.ts +205 -0
  86. package/packages/core/src/events.ts +157 -0
  87. package/packages/core/src/index.ts +49 -0
  88. package/packages/core/src/path.ts +118 -0
  89. package/packages/core/src/registry.ts +61 -0
  90. package/packages/core/tsconfig.json +19 -0
  91. package/packages/editor/README.md +9 -0
  92. package/packages/editor/package.json +18 -0
  93. package/packages/editor/src/index.ts +344 -0
  94. package/packages/editor/tsconfig.json +24 -0
  95. package/packages/fs/README.md +7 -0
  96. package/packages/fs/package.json +16 -0
  97. package/packages/fs/src/backends.ts +301 -0
  98. package/packages/fs/src/index.ts +18 -0
  99. package/packages/fs/src/types.ts +44 -0
  100. package/packages/fs/src/vfs-service.ts +257 -0
  101. package/packages/fs/tsconfig.json +22 -0
  102. package/packages/preview/README.md +3 -0
  103. package/packages/preview/package.json +16 -0
  104. package/packages/preview/src/index.ts +125 -0
  105. package/packages/preview/tsconfig.json +22 -0
  106. package/packages/runtime/README.md +3 -0
  107. package/packages/runtime/package.json +17 -0
  108. package/packages/runtime/src/index.ts +134 -0
  109. package/packages/runtime/tsconfig.json +23 -0
  110. package/packages/settings/README.md +7 -0
  111. package/packages/settings/package.json +16 -0
  112. package/packages/settings/src/builtin-schemas.ts +246 -0
  113. package/packages/settings/src/configuration-service.ts +609 -0
  114. package/packages/settings/src/index.ts +38 -0
  115. package/packages/settings/src/jsonc.ts +189 -0
  116. package/packages/settings/src/schema.ts +164 -0
  117. package/packages/settings/tsconfig.json +22 -0
  118. package/packages/sql/README.md +12 -0
  119. package/packages/sql/package.json +13 -0
  120. package/packages/sql/src/completions.ts +359 -0
  121. package/packages/sql/src/diagnostics.ts +200 -0
  122. package/packages/sql/src/formatter.ts +271 -0
  123. package/packages/sql/src/index.ts +54 -0
  124. package/packages/sql/src/sql-editor.ts +802 -0
  125. package/packages/sql/src/styles.ts +501 -0
  126. package/packages/sql/src/tokenizer.ts +457 -0
  127. package/packages/sql/src/types.ts +148 -0
  128. package/packages/sql/tsconfig.json +19 -0
  129. package/packages/terminal/README.md +3 -0
  130. package/packages/terminal/package.json +16 -0
  131. package/packages/terminal/src/index.ts +183 -0
  132. package/packages/terminal/tsconfig.json +22 -0
  133. package/packages/ui/README.md +8 -0
  134. package/packages/ui/package.json +18 -0
  135. package/packages/ui/src/index.ts +40 -0
  136. package/packages/ui/src/observability.ts +175 -0
  137. package/packages/ui/src/plugin-registry.ts +289 -0
  138. package/packages/ui/src/settings-dialog.ts +575 -0
  139. package/packages/ui/src/themes.ts +267 -0
  140. package/packages/ui/tsconfig.json +24 -0
  141. package/src/code-lab.css +1799 -98
  142. package/src/diagnostics.ts +139 -7
  143. package/src/extensions/cpp.ts +88 -45
  144. package/src/extensions/python.ts +186 -53
  145. package/src/extensions/umbrella.ts +5 -0
  146. package/src/index.ts +1 -1
  147. package/src/modular-kernel.ts +11 -0
  148. package/src/preview-sw.js +52 -11
  149. package/src/runtime.ts +466 -46
  150. package/src/schemas.ts +62 -62
  151. package/src/scm.ts +781 -58
  152. package/src/shell.ts +1299 -151
  153. package/src/storage.ts +336 -3
  154. package/src/terminal.ts +60 -2
  155. package/src/workbench/diff-editor.ts +66 -6
  156. package/src/workbench/icons.ts +12 -2
  157. package/src/workbench/styles.ts +25 -19
  158. package/src/workbench.ts +17059 -6673
  159. package/dist/runtime/index.d.ts +0 -4
  160. package/dist/shell/coreutils/compilers-cli.d.ts +0 -24
  161. package/dist/shell/index.d.ts +0 -4
  162. package/src/runtime/index.ts +0 -5
  163. package/src/shell/coreutils/compilers-cli.ts +0 -103
  164. package/src/shell/index.ts +0 -5
package/dist/shell.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.2 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.5.0 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -86,6 +86,7 @@ var CodeLabLogger = (() => {
86
86
  } catch (err) {
87
87
  sinkError = err;
88
88
  }
89
+ void sinkError;
89
90
  }
90
91
  const consoleObj = typeof console !== "undefined" ? console : null;
91
92
  const fn = consoleObj ? consoleObj[level] : null;
@@ -1712,9 +1713,11 @@ var CodeLabLogger = (() => {
1712
1713
  function createFallbackVfs() {
1713
1714
  const files = new Map();
1714
1715
  const dirs = new Set(['/', '/tmp', '/workspace', '/etc', '/home', '/home/user']);
1716
+ let _activeStdin = '';
1715
1717
 
1716
1718
  function norm(p) {
1717
- return PosixPath.normalize(p.startsWith('/') ? p : '/workspace/' + p);
1719
+ const s = String(p);
1720
+ return PosixPath.normalize(s.startsWith('/') ? s : '/workspace/' + s);
1718
1721
  }
1719
1722
 
1720
1723
  const emitter = {
@@ -1802,6 +1805,12 @@ var CodeLabLogger = (() => {
1802
1805
  return Array.from(children).sort();
1803
1806
  },
1804
1807
  readFileSync(p, encoding) {
1808
+ if (p === 0 || p === '/dev/stdin') {
1809
+ if (!encoding || encoding === 'buffer') {
1810
+ return new TextEncoder().encode(_activeStdin);
1811
+ }
1812
+ return _activeStdin;
1813
+ }
1805
1814
  const np = norm(p);
1806
1815
  const f = files.get(np);
1807
1816
  if (!f) {
@@ -1814,6 +1823,9 @@ var CodeLabLogger = (() => {
1814
1823
  }
1815
1824
  return f.data;
1816
1825
  },
1826
+ _setActiveStdin(text) {
1827
+ _activeStdin = text === null || text === undefined ? '' : String(text);
1828
+ },
1817
1829
  writeFileSync(p, data) {
1818
1830
  const np = norm(p);
1819
1831
  const parent = PosixPath.dirname(np);
@@ -2114,6 +2126,415 @@ var CodeLabLogger = (() => {
2114
2126
  return snap;
2115
2127
  }
2116
2128
 
2129
+ function computeGitShortHash(input) {
2130
+ const str = String(input || '');
2131
+ let h1 = 0xdeadbeef ^ str.length;
2132
+ let h2 = 0x41c6ce57 ^ str.length;
2133
+ for (let i = 0; i < str.length; i++) {
2134
+ const ch = str.charCodeAt(i);
2135
+ h1 = Math.imul(h1 ^ ch, 2654435761);
2136
+ h2 = Math.imul(h2 ^ ch, 1597334677);
2137
+ }
2138
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
2139
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
2140
+ const combined = 4294967296 * (2097151 & h2) + (h1 >>> 0);
2141
+ return combined.toString(16).padStart(7, '0').slice(0, 7);
2142
+ }
2143
+
2144
+ function normalizeGitRelPath(rawPath, repoRoot) {
2145
+ if (!rawPath || typeof rawPath !== 'string') return '';
2146
+ let p = rawPath.trim().replace(/\\/g, '/');
2147
+ if (!p) return '';
2148
+ const cleanRoot = PosixPath.normalize(repoRoot || '/workspace');
2149
+ const prefix = cleanRoot === '/' ? '/' : cleanRoot + '/';
2150
+ if (p === cleanRoot) return '';
2151
+ if (p.startsWith(prefix)) {
2152
+ p = p.slice(prefix.length);
2153
+ } else if (p.startsWith('/workspace/')) {
2154
+ p = p.slice('/workspace/'.length);
2155
+ }
2156
+ while (p.startsWith('./')) p = p.slice(2);
2157
+ if (p.startsWith('/')) p = p.replace(/^\/+/, '');
2158
+
2159
+ const out = [];
2160
+ for (const seg of p.split('/')) {
2161
+ if (!seg || seg === '.') continue;
2162
+ if (seg === '..') {
2163
+ if (out.length === 0) return '';
2164
+ out.pop();
2165
+ continue;
2166
+ }
2167
+ out.push(seg);
2168
+ }
2169
+ const normalized = out.join('/');
2170
+ if (
2171
+ !normalized ||
2172
+ normalized === '.git' ||
2173
+ normalized.startsWith('.git/') ||
2174
+ normalized.includes('/.git/') ||
2175
+ normalized.endsWith('/.git') ||
2176
+ normalized === 'node_modules' ||
2177
+ normalized.startsWith('node_modules/') ||
2178
+ normalized.includes('/node_modules/') ||
2179
+ normalized.endsWith('/node_modules')
2180
+ ) {
2181
+ return '';
2182
+ }
2183
+ return normalized;
2184
+ }
2185
+
2186
+ function isUnbornShellHead(gitState) {
2187
+ return (
2188
+ (!Array.isArray(gitState && gitState.commits) || gitState.commits.length === 0) &&
2189
+ !(gitState && gitState.headCommit)
2190
+ );
2191
+ }
2192
+
2193
+ function isEffectiveShellStagedChange(gitState, relPath, stagedVal, resolvedHeadFiles) {
2194
+ if (!relPath) return false;
2195
+ const headFiles =
2196
+ resolvedHeadFiles || (gitState && (gitState.headSnapshot || gitState.headFiles)) || {};
2197
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
2198
+ const normalizedVal = stagedVal === undefined || stagedVal === null ? null : String(stagedVal);
2199
+
2200
+ if (normalizedVal === null) {
2201
+ return inHead;
2202
+ }
2203
+ if (!inHead || isUnbornShellHead(gitState)) {
2204
+ return true;
2205
+ }
2206
+ return normalizedVal !== headFiles[relPath];
2207
+ }
2208
+
2209
+ function applyShellStagedEntry(gitState, map, rawPath, rawVal, resolvedHeadFiles) {
2210
+ const root = (gitState && gitState.repoRoot) || '/workspace';
2211
+ const rel = normalizeGitRelPath(rawPath, root);
2212
+ if (!rel) return;
2213
+ const normalizedVal = rawVal === undefined || rawVal === null ? null : String(rawVal);
2214
+ if (isEffectiveShellStagedChange(gitState, rel, normalizedVal, resolvedHeadFiles)) {
2215
+ map.set(rel, normalizedVal);
2216
+ } else {
2217
+ map.delete(rel);
2218
+ }
2219
+ }
2220
+
2221
+ function pruneShellStagedMap(gitState, map, resolvedHeadFiles) {
2222
+ if (!(map instanceof Map)) return;
2223
+ const root = (gitState && gitState.repoRoot) || '/workspace';
2224
+ const headFiles =
2225
+ resolvedHeadFiles || (gitState && (gitState.headSnapshot || gitState.headFiles)) || {};
2226
+ for (const [rawK, rawV] of Array.from(map.entries())) {
2227
+ const rel = normalizeGitRelPath(rawK, root);
2228
+ if (rel !== rawK) {
2229
+ map.delete(rawK);
2230
+ }
2231
+ if (!rel) {
2232
+ map.delete(rawK);
2233
+ continue;
2234
+ }
2235
+ const normalizedVal = rawV === undefined || rawV === null ? null : String(rawV);
2236
+ if (isEffectiveShellStagedChange(gitState, rel, normalizedVal, headFiles)) {
2237
+ map.set(rel, normalizedVal);
2238
+ } else {
2239
+ map.delete(rel);
2240
+ }
2241
+ }
2242
+ }
2243
+
2244
+ function getBootSnapshotForDir(shell, initDir) {
2245
+ if (!shell || !shell._initialBootSnapshot || !shell._initialBootRoot) return {};
2246
+ const normInit = PosixPath.normalize(initDir);
2247
+ const normBoot = shell._initialBootRoot;
2248
+ if (normInit === normBoot) {
2249
+ return shell._initialBootSnapshot;
2250
+ }
2251
+ const prefix = normBoot === '/' ? '/' : normBoot + '/';
2252
+ if (normInit.startsWith(prefix)) {
2253
+ const subRel = normInit.slice(prefix.length) + '/';
2254
+ const subSnap = {};
2255
+ for (const [k, v] of Object.entries(shell._initialBootSnapshot)) {
2256
+ if (k.startsWith(subRel)) {
2257
+ subSnap[k.slice(subRel.length)] = v;
2258
+ }
2259
+ }
2260
+ return subSnap;
2261
+ }
2262
+ return {};
2263
+ }
2264
+
2265
+ function attachShellStagedMapShim(map, vfsRef, getRepoRoot, getGitState) {
2266
+ if (!(map instanceof Map)) return map;
2267
+ if (!map._hasShellStagedShim) {
2268
+ Object.defineProperty(map, '_hasShellStagedShim', {
2269
+ value: true,
2270
+ enumerable: false,
2271
+ configurable: true,
2272
+ writable: true
2273
+ });
2274
+ Object.defineProperty(map, 'add', {
2275
+ value(rawPath) {
2276
+ const gs = typeof getGitState === 'function' ? getGitState() : null;
2277
+ const root =
2278
+ typeof getRepoRoot === 'function'
2279
+ ? getRepoRoot()
2280
+ : ((gs && gs.repoRoot) || '/workspace');
2281
+ const rel = normalizeGitRelPath(rawPath, root);
2282
+ if (!rel) return map;
2283
+ let content = null;
2284
+ if (vfsRef && typeof vfsRef.existsSync === 'function') {
2285
+ const abs = PosixPath.join(root, rel);
2286
+ if (vfsRef.existsSync(abs)) {
2287
+ if (typeof vfsRef.statSync === 'function') {
2288
+ try {
2289
+ if (vfsRef.statSync(abs).isDirectory()) return map;
2290
+ } catch (err) {
2291
+ _shellLogger.debug('Failed statting staged path in VFS.', abs, err);
2292
+ }
2293
+ }
2294
+ if (typeof vfsRef.readFileSync === 'function') {
2295
+ try {
2296
+ content = String(vfsRef.readFileSync(abs, 'utf8'));
2297
+ } catch (err) {
2298
+ _shellLogger.debug('Failed reading staged file from VFS.', abs, err);
2299
+ return map;
2300
+ }
2301
+ }
2302
+ }
2303
+ }
2304
+ if (gs) {
2305
+ applyShellStagedEntry(gs, map, rel, content);
2306
+ } else {
2307
+ map.set(rel, content);
2308
+ }
2309
+ return map;
2310
+ },
2311
+ enumerable: false,
2312
+ configurable: true,
2313
+ writable: true
2314
+ });
2315
+ }
2316
+ return map;
2317
+ }
2318
+
2319
+ function ensureShellStagedMap(gitState, vfsRef, repoRoot) {
2320
+ const getRoot = () => (gitState && gitState.repoRoot) || repoRoot || '/workspace';
2321
+ const getGs = () => gitState;
2322
+ if (gitState.staged instanceof Map) {
2323
+ attachShellStagedMapShim(gitState.staged, vfsRef, getRoot, getGs);
2324
+ pruneShellStagedMap(gitState, gitState.staged);
2325
+ gitState.stagedFiles = gitState.staged;
2326
+ return gitState.staged;
2327
+ }
2328
+ const nextMap = attachShellStagedMapShim(new Map(), vfsRef, getRoot, getGs);
2329
+ if (gitState.staged && typeof gitState.staged[Symbol.iterator] === 'function') {
2330
+ for (const item of gitState.staged) {
2331
+ if (Array.isArray(item) && item.length >= 2) {
2332
+ applyShellStagedEntry(
2333
+ gitState,
2334
+ nextMap,
2335
+ item[0],
2336
+ item[1] === null ? null : String(item[1])
2337
+ );
2338
+ } else if (typeof item === 'string') {
2339
+ nextMap.add(item);
2340
+ }
2341
+ }
2342
+ }
2343
+ gitState.staged = nextMap;
2344
+ gitState.stagedFiles = nextMap;
2345
+ return nextMap;
2346
+ }
2347
+
2348
+ function parseGitHeadBranch(vfs, repoRoot) {
2349
+ if (!vfs || typeof vfs.existsSync !== 'function' || typeof vfs.readFileSync !== 'function') {
2350
+ return null;
2351
+ }
2352
+ const candidates = [
2353
+ PosixPath.join(repoRoot, '.git/HEAD'),
2354
+ '/workspace/.git/HEAD'
2355
+ ];
2356
+ for (const headFile of candidates) {
2357
+ if (vfs.existsSync(headFile)) {
2358
+ try {
2359
+ const raw = String(vfs.readFileSync(headFile, 'utf8')).trim();
2360
+ const m = /^ref:\s*refs\/heads\/([^\s]+)$/.exec(raw);
2361
+ if (m && m[1]) return m[1];
2362
+ } catch (err) {
2363
+ _shellLogger.debug('Could not parse .git/HEAD branch.', headFile, err);
2364
+ }
2365
+ }
2366
+ }
2367
+ return null;
2368
+ }
2369
+
2370
+ function createUnifiedShellGitState(vfs, cwd, options = {}) {
2371
+ const cleanCwd = PosixPath.normalize(cwd || '/workspace');
2372
+ const hasDotGit = Boolean(
2373
+ vfs &&
2374
+ typeof vfs.existsSync === 'function' &&
2375
+ (vfs.existsSync(PosixPath.join(cleanCwd, '.git')) ||
2376
+ vfs.existsSync(PosixPath.join(cleanCwd, '.git/HEAD')) ||
2377
+ vfs.existsSync('/workspace/.git') ||
2378
+ vfs.existsSync('/workspace/.git/HEAD'))
2379
+ );
2380
+
2381
+ let _initialized = Boolean(options.gitInitialized === true || hasDotGit);
2382
+ let _repoRoot = cleanCwd;
2383
+ const detectedBranch = hasDotGit ? parseGitHeadBranch(vfs, cleanCwd) : null;
2384
+ const initialBranch = detectedBranch || 'main';
2385
+
2386
+ let _headFiles = _initialized ? snapshotWorktree(vfs, cleanCwd) : {};
2387
+ let _headCommit = _initialized
2388
+ ? computeGitShortHash(JSON.stringify(_headFiles) + ':init')
2389
+ : '';
2390
+ const initTs = Date.now();
2391
+ let _commits = _initialized
2392
+ ? [
2393
+ {
2394
+ hash: _headCommit,
2395
+ author: 'CodeLab Developer <dev@codelab.internal>',
2396
+ date: new Date(initTs).toUTCString(),
2397
+ timestamp: initTs,
2398
+ message: 'Initial commit',
2399
+ files: Object.assign({}, _headFiles)
2400
+ }
2401
+ ]
2402
+ : [];
2403
+
2404
+ const gs = {
2405
+ branch: initialBranch,
2406
+ branches: new Set([initialBranch]),
2407
+ remoteUrl: null,
2408
+ remotes: {}
2409
+ };
2410
+
2411
+ let _stagedMap = attachShellStagedMapShim(new Map(), vfs, () => _repoRoot, () => gs);
2412
+
2413
+ Object.defineProperties(gs, {
2414
+ initialized: {
2415
+ enumerable: true,
2416
+ configurable: true,
2417
+ get() {
2418
+ if (_initialized) return true;
2419
+ const root = _repoRoot || cleanCwd;
2420
+ if (
2421
+ vfs &&
2422
+ typeof vfs.existsSync === 'function' &&
2423
+ (vfs.existsSync(PosixPath.join(root, '.git')) ||
2424
+ vfs.existsSync(PosixPath.join(root, '.git/HEAD')))
2425
+ ) {
2426
+ _initialized = true;
2427
+ return true;
2428
+ }
2429
+ return false;
2430
+ },
2431
+ set(v) {
2432
+ _initialized = Boolean(v);
2433
+ }
2434
+ },
2435
+ repoRoot: {
2436
+ enumerable: true,
2437
+ configurable: true,
2438
+ get() {
2439
+ return _repoRoot;
2440
+ },
2441
+ set(v) {
2442
+ _repoRoot = PosixPath.normalize(String(v || cleanCwd));
2443
+ }
2444
+ },
2445
+ headCommit: {
2446
+ enumerable: true,
2447
+ configurable: true,
2448
+ get() {
2449
+ return _headCommit;
2450
+ },
2451
+ set(v) {
2452
+ _headCommit = String(v || '');
2453
+ }
2454
+ },
2455
+ headSnapshot: {
2456
+ enumerable: true,
2457
+ configurable: true,
2458
+ get() {
2459
+ return _headFiles;
2460
+ },
2461
+ set(v) {
2462
+ _headFiles = v && typeof v === 'object' ? v : {};
2463
+ }
2464
+ },
2465
+ headFiles: {
2466
+ enumerable: true,
2467
+ configurable: true,
2468
+ get() {
2469
+ return _headFiles;
2470
+ },
2471
+ set(v) {
2472
+ _headFiles = v && typeof v === 'object' ? v : {};
2473
+ }
2474
+ },
2475
+ staged: {
2476
+ enumerable: true,
2477
+ configurable: true,
2478
+ get() {
2479
+ return _stagedMap;
2480
+ },
2481
+ set(v) {
2482
+ if (v instanceof Map) {
2483
+ _stagedMap = attachShellStagedMapShim(v, vfs, () => _repoRoot, () => gs);
2484
+ pruneShellStagedMap(gs, _stagedMap);
2485
+ } else {
2486
+ const converted = attachShellStagedMapShim(new Map(), vfs, () => _repoRoot, () => gs);
2487
+ if (v && typeof v[Symbol.iterator] === 'function') {
2488
+ for (const item of v) {
2489
+ if (typeof item === 'string') {
2490
+ converted.add(item);
2491
+ } else if (Array.isArray(item) && item.length >= 2) {
2492
+ applyShellStagedEntry(
2493
+ gs,
2494
+ converted,
2495
+ item[0],
2496
+ item[1] === null ? null : String(item[1])
2497
+ );
2498
+ }
2499
+ }
2500
+ }
2501
+ _stagedMap = converted;
2502
+ }
2503
+ }
2504
+ },
2505
+ stagedFiles: {
2506
+ enumerable: true,
2507
+ configurable: true,
2508
+ get() {
2509
+ return _stagedMap;
2510
+ },
2511
+ set(v) {
2512
+ if (v instanceof Map) {
2513
+ _stagedMap = attachShellStagedMapShim(v, vfs, () => _repoRoot, () => gs);
2514
+ pruneShellStagedMap(gs, _stagedMap);
2515
+ }
2516
+ }
2517
+ },
2518
+ commits: {
2519
+ enumerable: true,
2520
+ configurable: true,
2521
+ get() {
2522
+ return _commits;
2523
+ },
2524
+ set(v) {
2525
+ _commits = Array.isArray(v) ? v : [];
2526
+ if (_commits.length > 0 && _commits[0] && _commits[0].hash) {
2527
+ _headCommit = String(_commits[0].hash);
2528
+ } else if (_commits.length === 0) {
2529
+ _headCommit = '';
2530
+ }
2531
+ }
2532
+ }
2533
+ });
2534
+
2535
+ return gs;
2536
+ }
2537
+
2117
2538
  const BINARY_OR_HEAVY_EXT_RE = /\.(png|jpg|jpeg|gif|webp|ico|bmp|tiff|woff|woff2|ttf|eot|otf|mp3|mp4|wav|ogg|webm|avi|mov|pdf|zip|tar|gz|tgz|bz2|7z|rar|exe|dll|so|dylib|wasm|pyc|pyo|class|jar|war|ear|bin|dat|iso|dmg|pkg|deb|rpm|o|a|lib|DS_Store)$/i;
2118
2539
 
2119
2540
  function scoreRepoFilePriority(relPath) {
@@ -2374,18 +2795,23 @@ var CodeLabLogger = (() => {
2374
2795
  if (commitsRes && commitsRes.ok) {
2375
2796
  const commitsJson = await commitsRes.json();
2376
2797
  if (Array.isArray(commitsJson) && commitsJson.length > 0) {
2377
- commits = commitsJson.map((c) => ({
2378
- hash: String(c.sha || 'a1b2c3d').slice(0, 7),
2379
- author:
2380
- c.commit && c.commit.author
2381
- ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2382
- : `${owner} <${owner}@users.noreply.github.com>`,
2383
- date:
2384
- c.commit && c.commit.author && c.commit.author.date
2385
- ? new Date(c.commit.author.date).toUTCString()
2386
- : new Date().toUTCString(),
2387
- message: c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit'
2388
- }));
2798
+ commits = commitsJson.map((c, idx) => {
2799
+ const msgText = c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit';
2800
+ const fallbackHash = computeGitShortHash(`${owner}/${repo}:${resolvedBranch}:${idx}:${msgText}`);
2801
+ const ts = c.commit && c.commit.author && c.commit.author.date
2802
+ ? Date.parse(c.commit.author.date) || Date.now()
2803
+ : Date.now();
2804
+ return {
2805
+ hash: String(c.sha || fallbackHash).slice(0, 7),
2806
+ author:
2807
+ c.commit && c.commit.author
2808
+ ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2809
+ : `${owner} <${owner}@users.noreply.github.com>`,
2810
+ date: new Date(ts).toUTCString(),
2811
+ timestamp: ts,
2812
+ message: msgText
2813
+ };
2814
+ });
2389
2815
  }
2390
2816
  }
2391
2817
  } catch (err) {
@@ -2393,11 +2819,14 @@ var CodeLabLogger = (() => {
2393
2819
  }
2394
2820
 
2395
2821
  if (commits.length === 0) {
2822
+ const cloneTs = Date.now();
2823
+ const cloneHash = computeGitShortHash(`${owner}/${repo}:${resolvedBranch}:${filesWritten}`);
2396
2824
  commits = [
2397
2825
  {
2398
- hash: 'a1b2c3d',
2826
+ hash: cloneHash,
2399
2827
  author: `${owner} <${owner}@users.noreply.github.com>`,
2400
- date: new Date().toUTCString(),
2828
+ date: new Date(cloneTs).toUTCString(),
2829
+ timestamp: cloneTs,
2401
2830
  message: `Clone ${owner}/${repo} (${resolvedBranch})`
2402
2831
  }
2403
2832
  ];
@@ -3072,9 +3501,31 @@ var CodeLabLogger = (() => {
3072
3501
  '.gif': 'image/gif',
3073
3502
  '.webp': 'image/webp',
3074
3503
  '.ico': 'image/x-icon',
3504
+ '.woff': 'font/woff',
3505
+ '.woff2': 'font/woff2',
3506
+ '.ttf': 'font/ttf',
3507
+ '.otf': 'font/otf',
3508
+ '.wasm': 'application/wasm',
3509
+ '.pdf': 'application/pdf',
3510
+ '.mp3': 'audio/mpeg',
3511
+ '.mp4': 'video/mp4',
3512
+ '.webm': 'video/webm',
3075
3513
  '.txt': 'text/plain; charset=utf-8'
3076
3514
  };
3077
3515
 
3516
+ function isBinaryPreviewMime(mime) {
3517
+ const clean = String(mime || '').toLowerCase().split(';')[0].trim();
3518
+ if (!clean) return false;
3519
+ return !(
3520
+ clean.startsWith('text/') ||
3521
+ clean === 'application/javascript' ||
3522
+ clean === 'application/json' ||
3523
+ clean === 'application/xml' ||
3524
+ clean === 'application/xhtml+xml' ||
3525
+ clean === 'image/svg+xml'
3526
+ );
3527
+ }
3528
+
3078
3529
  function previewMimeFor(p) {
3079
3530
  const lower = String(p).toLowerCase();
3080
3531
  const dot = lower.lastIndexOf('.');
@@ -3258,7 +3709,8 @@ var CodeLabLogger = (() => {
3258
3709
 
3259
3710
  function injectPreviewExtras(html, importMap) {
3260
3711
  let out = html;
3261
- const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
3712
+ const safeImportMapJson = JSON.stringify({ imports: importMap }, null, 2).replace(/</g, '\\u003c');
3713
+ const importMapTag = `<script type="importmap">\n${safeImportMapJson}\n</script>`;
3262
3714
  if (/<head[^>]*>/i.test(out)) {
3263
3715
  out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
3264
3716
  } else {
@@ -3514,6 +3966,20 @@ var CodeLabLogger = (() => {
3514
3966
  );
3515
3967
  }
3516
3968
 
3969
+ const mimeType = previewMimeFor(target);
3970
+ if (isBinaryPreviewMime(mimeType)) {
3971
+ let rawBytes = null;
3972
+ try {
3973
+ rawBytes = ctx.vfs.readFileSync(target);
3974
+ } catch (err) {
3975
+ _shellLogger.debug('Binary preview asset read failed.', target, err);
3976
+ }
3977
+ const binaryBody = rawBytes instanceof Uint8Array
3978
+ ? rawBytes
3979
+ : (typeof rawBytes === 'string' ? new TextEncoder().encode(rawBytes) : new Uint8Array(0));
3980
+ return new Response(binaryBody, { status: 200, headers: { 'content-type': mimeType } });
3981
+ }
3982
+
3517
3983
  let body = readText(target);
3518
3984
  if (body === null) body = '';
3519
3985
  if (/\.html?$/i.test(target)) {
@@ -3529,7 +3995,7 @@ var CodeLabLogger = (() => {
3529
3995
  }
3530
3996
  }
3531
3997
 
3532
- return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
3998
+ return new Response(body, { status: 200, headers: { 'content-type': mimeType } });
3533
3999
  };
3534
4000
 
3535
4001
  const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
@@ -5549,26 +6015,56 @@ var CodeLabLogger = (() => {
5549
6015
  // -----------------------------------------------------------------------
5550
6016
  async git(args, ctx) {
5551
6017
  const subcmd = args[0] || 'status';
6018
+ if (subcmd === 'version' || subcmd === '--version' || subcmd === '-v') {
6019
+ return { code: 0, stdout: 'git version 2.45.0 (CodeLab Virtual Git)\n', stderr: '' };
6020
+ }
6021
+ if (subcmd === 'help' || subcmd === '--help' || subcmd === '-h') {
6022
+ return {
6023
+ code: 0,
6024
+ stdout:
6025
+ 'usage: git <command> [<args>]\n\nCommon commands: init, clone, status, add, diff, commit, restore, reset, rm, branch, checkout, switch, remote, fetch, pull, log\n',
6026
+ stderr: ''
6027
+ };
6028
+ }
6029
+
5552
6030
  const gitState = ctx.shell.gitState;
5553
6031
  if (!(gitState.branches instanceof Set)) {
5554
6032
  gitState.branches = new Set(Array.isArray(gitState.branches) ? gitState.branches : [gitState.branch || 'main']);
5555
6033
  }
5556
- if (!gitState.headSnapshot) {
5557
- gitState.headSnapshot = snapshotWorktree(ctx.vfs, gitState.repoRoot || ctx.cwd);
5558
- }
5559
6034
  if (!gitState.remotes) {
5560
6035
  gitState.remotes = gitState.remoteUrl ? { origin: gitState.remoteUrl } : {};
5561
6036
  }
5562
6037
 
5563
- const repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
6038
+ let repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
6039
+ const stagedMap = ensureShellStagedMap(gitState, ctx.vfs, repoRoot);
6040
+
5564
6041
  const toRepoRel = (p) => {
5565
6042
  const abs = ctx.resolvePath(p);
5566
6043
  const prefix = repoRoot === '/' ? '/' : repoRoot + '/';
5567
6044
  if (abs === repoRoot) return '.';
5568
- if (abs.startsWith(prefix)) return abs.slice(prefix.length);
5569
- return p.replace(/^\.\//, '');
6045
+ if (abs.startsWith(prefix)) return normalizeGitRelPath(abs.slice(prefix.length), repoRoot);
6046
+ return '';
5570
6047
  };
5571
6048
 
6049
+ if (subcmd !== 'init' && subcmd !== 'clone') {
6050
+ const hasDotGitInFs = Boolean(
6051
+ ctx.vfs &&
6052
+ typeof ctx.vfs.existsSync === 'function' &&
6053
+ (ctx.vfs.existsSync(PosixPath.join(repoRoot, '.git')) ||
6054
+ ctx.vfs.existsSync(PosixPath.join(ctx.cwd, '.git')))
6055
+ );
6056
+ if (!gitState.initialized && !hasDotGitInFs) {
6057
+ return {
6058
+ code: 128,
6059
+ stdout: '',
6060
+ stderr: 'fatal: not a git repository (or any of the parent directories): .git\n'
6061
+ };
6062
+ }
6063
+ if (hasDotGitInFs && !gitState.initialized) {
6064
+ gitState.initialized = true;
6065
+ }
6066
+ }
6067
+
5572
6068
  if (subcmd === 'clone') {
5573
6069
  let branchOpt = null;
5574
6070
  const positional = [];
@@ -5615,7 +6111,6 @@ var CodeLabLogger = (() => {
5615
6111
  dirDisplayName = parsed.repo;
5616
6112
  }
5617
6113
 
5618
- // Stream clone progress to the terminal as it happens (no end-of-run buffering).
5619
6114
  const canStream = typeof ctx.onStdout === 'function';
5620
6115
  const streamLine = (text) => { if (canStream && text) ctx.onStdout(text); };
5621
6116
  streamLine(`Cloning into '${dirDisplayName}'...\n`);
@@ -5649,14 +6144,18 @@ var CodeLabLogger = (() => {
5649
6144
  }
5650
6145
  });
5651
6146
 
6147
+ const clonedHead = Object.assign({}, result.headSnapshot);
6148
+ gitState.initialized = true;
5652
6149
  gitState.branch = result.branch;
5653
6150
  gitState.branches.add(result.branch);
5654
6151
  gitState.remoteUrl = result.url;
5655
6152
  gitState.remotes.origin = result.url;
5656
6153
  gitState.repoRoot = targetDir;
5657
- gitState.headSnapshot = Object.assign({}, result.headSnapshot);
6154
+ gitState.headSnapshot = clonedHead;
6155
+ gitState.headFiles = clonedHead;
5658
6156
  gitState.commits = result.commits;
5659
- gitState.staged.clear();
6157
+ gitState.headCommit = (result.commits && result.commits[0] && result.commits[0].hash) || '';
6158
+ stagedMap.clear();
5660
6159
 
5661
6160
  const count = Math.max(1, result.filesWritten);
5662
6161
  const kb = Math.max(0.1, result.totalBytes / 1024).toFixed(1);
@@ -5682,62 +6181,149 @@ var CodeLabLogger = (() => {
5682
6181
  }
5683
6182
 
5684
6183
  if (subcmd === 'init') {
5685
- const initDir = args[1] && !args[1].startsWith('-') ? ctx.resolvePath(args[1]) : ctx.cwd;
6184
+ let initBranch = gitState.branch || 'main';
6185
+ let emptyHead = false;
6186
+ let dirArg = null;
6187
+ for (let i = 1; i < args.length; i++) {
6188
+ const a = args[i];
6189
+ if ((a === '-b' || a === '--initial-branch') && i + 1 < args.length) {
6190
+ initBranch = args[++i];
6191
+ } else if (a.startsWith('--initial-branch=')) {
6192
+ initBranch = a.slice('--initial-branch='.length) || initBranch;
6193
+ } else if (a === '--empty-head') {
6194
+ emptyHead = true;
6195
+ } else if (!a.startsWith('-') && !dirArg) {
6196
+ dirArg = a;
6197
+ }
6198
+ }
6199
+ const initDir = PosixPath.normalize(dirArg ? ctx.resolvePath(dirArg) : ctx.cwd);
5686
6200
  const gitDir = PosixPath.join(initDir, '.git');
6201
+ const wasReinitSameDir =
6202
+ Boolean(gitState.initialized) &&
6203
+ PosixPath.normalize(gitState.repoRoot || ctx.cwd) === initDir &&
6204
+ !emptyHead;
5687
6205
  ensureDirSync(ctx.vfs, gitDir, ctx.emitMutation);
5688
- const branchName = gitState.branch || 'main';
5689
- ctx.vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${branchName}\n`);
6206
+ if (!wasReinitSameDir || !ctx.vfs.existsSync(PosixPath.join(gitDir, 'HEAD'))) {
6207
+ ctx.vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${initBranch}\n`);
6208
+ }
5690
6209
  ctx.vfs.writeFileSync(
5691
6210
  PosixPath.join(gitDir, 'config'),
5692
6211
  `[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n`
5693
6212
  );
5694
6213
  ctx.emitMutation('create', PosixPath.join(gitDir, 'HEAD'));
6214
+
6215
+ if (wasReinitSameDir && !isUnbornShellHead(gitState)) {
6216
+ gitState.branches.add(gitState.branch || initBranch);
6217
+ return {
6218
+ code: 0,
6219
+ stdout: `Reinitialized existing Git repository in ${gitDir}/\n`,
6220
+ stderr: ''
6221
+ };
6222
+ }
6223
+
6224
+ const initSnap = {};
6225
+ if (!emptyHead) {
6226
+ const currentLive = snapshotWorktree(ctx.vfs, initDir);
6227
+ const bootSnap = getBootSnapshotForDir(ctx.shell, initDir);
6228
+ for (const [rel, content] of Object.entries(currentLive)) {
6229
+ if (Object.prototype.hasOwnProperty.call(bootSnap, rel) && bootSnap[rel] === content) {
6230
+ initSnap[rel] = content;
6231
+ }
6232
+ }
6233
+ }
6234
+ gitState.initialized = true;
6235
+ gitState.branch = initBranch;
6236
+ gitState.branches.add(initBranch);
5695
6237
  gitState.repoRoot = initDir;
5696
- gitState.headSnapshot = snapshotWorktree(ctx.vfs, initDir);
5697
- gitState.staged.clear();
5698
- return { code: 0, stdout: `Initialized empty Git repository in ${gitDir}/\n`, stderr: '' };
6238
+ gitState.headSnapshot = initSnap;
6239
+ gitState.headFiles = initSnap;
6240
+ gitState.commits = [];
6241
+ gitState.headCommit = '';
6242
+ stagedMap.clear();
6243
+ return {
6244
+ code: 0,
6245
+ stdout: `${wasReinitSameDir ? 'Reinitialized existing' : 'Initialized empty'} Git repository in ${gitDir}/\n`,
6246
+ stderr: ''
6247
+ };
5699
6248
  }
5700
6249
 
6250
+ repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
6251
+
5701
6252
  if (subcmd === 'status') {
5702
- const isShort = args.includes('-s') || args.includes('--short');
6253
+ const isShort = args.includes('-s') || args.includes('--short') || args.includes('--porcelain');
5703
6254
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5704
- const headFiles = gitState.headSnapshot || {};
6255
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6256
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6257
+ const unbornHead = isUnbornShellHead(gitState);
5705
6258
 
5706
6259
  const stagedList = [];
5707
- for (const relPath of gitState.staged) {
6260
+ const unstagedList = [];
6261
+ const untrackedList = [];
6262
+ const stagedKeysSorted = Array.from(stagedMap.keys()).sort();
6263
+
6264
+ for (const relPath of stagedKeysSorted) {
6265
+ const stagedVal = stagedMap.get(relPath);
5708
6266
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
5709
6267
  const inLive = Object.prototype.hasOwnProperty.call(liveFiles, relPath);
5710
- if (!inHead && inLive) {
5711
- stagedList.push({ status: 'new file', short: 'A ', path: relPath });
5712
- } else if (inHead && !inLive) {
5713
- stagedList.push({ status: 'deleted', short: 'D ', path: relPath });
6268
+
6269
+ if (stagedVal === null) {
6270
+ if (inHead) {
6271
+ stagedList.push({ status: 'deleted', code: 'D', path: relPath });
6272
+ }
6273
+ if (inLive) {
6274
+ untrackedList.push(relPath);
6275
+ }
5714
6276
  } else {
5715
- stagedList.push({ status: 'modified', short: 'M ', path: relPath });
6277
+ if (!inHead || unbornHead) {
6278
+ stagedList.push({ status: 'new file', code: 'A', path: relPath });
6279
+ } else if (stagedVal !== headFiles[relPath]) {
6280
+ stagedList.push({ status: 'modified', code: 'M', path: relPath });
6281
+ }
6282
+
6283
+ if (!inLive) {
6284
+ unstagedList.push({ status: 'deleted', code: 'D', path: relPath });
6285
+ } else if (liveFiles[relPath] !== stagedVal) {
6286
+ unstagedList.push({ status: 'modified', code: 'M', path: relPath });
6287
+ }
5716
6288
  }
5717
6289
  }
5718
6290
 
5719
- const unstagedList = [];
5720
6291
  for (const relPath of Object.keys(headFiles).sort()) {
5721
- if (gitState.staged.has(relPath)) continue;
6292
+ if (stagedMap.has(relPath)) continue;
5722
6293
  if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5723
- unstagedList.push({ status: 'deleted', short: ' D', path: relPath });
6294
+ unstagedList.push({ status: 'deleted', code: 'D', path: relPath });
5724
6295
  } else if (liveFiles[relPath] !== headFiles[relPath]) {
5725
- unstagedList.push({ status: 'modified', short: ' M', path: relPath });
6296
+ unstagedList.push({ status: 'modified', code: 'M', path: relPath });
5726
6297
  }
5727
6298
  }
5728
6299
 
5729
- const untrackedList = [];
5730
6300
  for (const relPath of Object.keys(liveFiles).sort()) {
5731
- if (!Object.prototype.hasOwnProperty.call(headFiles, relPath) && !gitState.staged.has(relPath)) {
6301
+ if (!Object.prototype.hasOwnProperty.call(headFiles, relPath) && !stagedMap.has(relPath)) {
5732
6302
  untrackedList.push(relPath);
5733
6303
  }
5734
6304
  }
5735
6305
 
6306
+ unstagedList.sort((a, b) => a.path.localeCompare(b.path));
6307
+ untrackedList.sort();
6308
+
5736
6309
  if (isShort) {
6310
+ const shortByPath = new Map();
6311
+ for (const item of stagedList) {
6312
+ shortByPath.set(item.path, { idx: item.code, wt: ' ' });
6313
+ }
6314
+ for (const item of unstagedList) {
6315
+ const prev = shortByPath.get(item.path);
6316
+ if (prev) prev.wt = item.code;
6317
+ else shortByPath.set(item.path, { idx: ' ', wt: item.code });
6318
+ }
5737
6319
  let sOut = '';
5738
- for (const item of stagedList) sOut += `${item.short} ${item.path}\n`;
5739
- for (const item of unstagedList) sOut += `${item.short} ${item.path}\n`;
5740
- for (const p of untrackedList) sOut += `?? ${p}\n`;
6320
+ for (const p of Array.from(shortByPath.keys()).sort()) {
6321
+ const pair = shortByPath.get(p);
6322
+ sOut += `${pair.idx}${pair.wt} ${p}\n`;
6323
+ }
6324
+ for (const p of untrackedList) {
6325
+ sOut += `?? ${p}\n`;
6326
+ }
5741
6327
  return { code: 0, stdout: sOut, stderr: '' };
5742
6328
  }
5743
6329
 
@@ -5774,24 +6360,43 @@ var CodeLabLogger = (() => {
5774
6360
 
5775
6361
  if (subcmd === 'diff') {
5776
6362
  const isStaged = args.includes('--staged') || args.includes('--cached');
5777
- const fileFilters = args.slice(1).filter((a) => !a.startsWith('-')).map(toRepoRel);
6363
+ const rawFilterArgs = args.slice(1).filter((a) => !a.startsWith('-'));
6364
+ const fileFilters = rawFilterArgs.map(toRepoRel);
6365
+ const matchAllInRepo = fileFilters.length === 0 || fileFilters.includes('.');
5778
6366
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5779
- const headFiles = gitState.headSnapshot || {};
5780
- const allKeys = Array.from(new Set([...Object.keys(headFiles), ...Object.keys(liveFiles)])).sort();
6367
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6368
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6369
+ const unbornHead = isUnbornShellHead(gitState);
6370
+ const allKeys = Array.from(
6371
+ new Set([...Object.keys(headFiles), ...Object.keys(liveFiles), ...Array.from(stagedMap.keys())])
6372
+ ).sort();
5781
6373
 
5782
6374
  let stdout = '';
5783
6375
  for (const relPath of allKeys) {
5784
- if (fileFilters.length > 0 && !fileFilters.includes(relPath)) continue;
5785
- if (isStaged && !gitState.staged.has(relPath)) continue;
5786
- if (!isStaged && !Object.prototype.hasOwnProperty.call(headFiles, relPath) && !gitState.staged.has(relPath)) {
5787
- continue;
5788
- }
5789
- const oldText = Object.prototype.hasOwnProperty.call(headFiles, relPath) ? headFiles[relPath] : '';
5790
- const newText = Object.prototype.hasOwnProperty.call(liveFiles, relPath) ? liveFiles[relPath] : '';
5791
- if (oldText !== newText) {
5792
- const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
5793
- if (uDiff) {
5794
- stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
6376
+ if (!matchAllInRepo && !fileFilters.includes(relPath)) continue;
6377
+ if (isStaged) {
6378
+ if (!stagedMap.has(relPath)) continue;
6379
+ const stagedVal = stagedMap.get(relPath);
6380
+ if (!isEffectiveShellStagedChange(gitState, relPath, stagedVal, headFiles)) continue;
6381
+ const oldText =
6382
+ !unbornHead && Object.prototype.hasOwnProperty.call(headFiles, relPath)
6383
+ ? headFiles[relPath]
6384
+ : '';
6385
+ const newText = stagedVal === null ? '' : String(stagedVal);
6386
+ if (oldText !== newText) {
6387
+ const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
6388
+ if (uDiff) stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
6389
+ }
6390
+ } else {
6391
+ const isTrackedOrStaged =
6392
+ Object.prototype.hasOwnProperty.call(headFiles, relPath) || stagedMap.has(relPath);
6393
+ if (!isTrackedOrStaged) continue;
6394
+ const baseVal = stagedMap.has(relPath) ? stagedMap.get(relPath) : headFiles[relPath];
6395
+ const oldText = baseVal === null || baseVal === undefined ? '' : String(baseVal);
6396
+ const newText = Object.prototype.hasOwnProperty.call(liveFiles, relPath) ? liveFiles[relPath] : '';
6397
+ if (oldText !== newText) {
6398
+ const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
6399
+ if (uDiff) stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
5795
6400
  }
5796
6401
  }
5797
6402
  }
@@ -5801,38 +6406,76 @@ var CodeLabLogger = (() => {
5801
6406
  if (subcmd === 'add') {
5802
6407
  const targets = args.slice(1);
5803
6408
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5804
- const headFiles = gitState.headSnapshot || {};
6409
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6410
+
6411
+ const stagePath = (relPath) => {
6412
+ const clean = normalizeGitRelPath(relPath, repoRoot);
6413
+ if (!clean) return;
6414
+ const inLive = Object.prototype.hasOwnProperty.call(liveFiles, clean);
6415
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, clean);
6416
+ if (inLive) {
6417
+ applyShellStagedEntry(gitState, stagedMap, clean, liveFiles[clean], headFiles);
6418
+ } else if (inHead) {
6419
+ applyShellStagedEntry(gitState, stagedMap, clean, null, headFiles);
6420
+ } else {
6421
+ stagedMap.delete(clean);
6422
+ }
6423
+ };
5805
6424
 
5806
6425
  if (targets.includes('.') || targets.includes('-A') || targets.includes('--all') || targets.includes('-u')) {
5807
6426
  const includeUntracked = !targets.includes('-u');
5808
6427
  for (const relPath of Object.keys(liveFiles)) {
5809
6428
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
5810
6429
  if (!inHead && includeUntracked) {
5811
- gitState.staged.add(relPath);
5812
- } else if (inHead && liveFiles[relPath] !== headFiles[relPath]) {
5813
- gitState.staged.add(relPath);
6430
+ stagePath(relPath);
6431
+ } else if (inHead) {
6432
+ stagePath(relPath);
5814
6433
  }
5815
6434
  }
5816
6435
  for (const relPath of Object.keys(headFiles)) {
5817
6436
  if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5818
- gitState.staged.add(relPath);
6437
+ stagePath(relPath);
6438
+ }
6439
+ }
6440
+ for (const stagedKey of Array.from(stagedMap.keys())) {
6441
+ if (
6442
+ !Object.prototype.hasOwnProperty.call(liveFiles, stagedKey) &&
6443
+ !Object.prototype.hasOwnProperty.call(headFiles, stagedKey)
6444
+ ) {
6445
+ stagedMap.delete(stagedKey);
5819
6446
  }
5820
6447
  }
5821
6448
  } else {
5822
6449
  for (const f of targets) {
5823
6450
  if (f.startsWith('-')) continue;
5824
6451
  const rel = toRepoRel(f);
6452
+ if (!rel) continue;
5825
6453
  if (rel === '.') {
5826
- for (const k of Object.keys(liveFiles)) {
5827
- if (liveFiles[k] !== headFiles[k]) gitState.staged.add(k);
6454
+ for (const k of Object.keys(liveFiles)) stagePath(k);
6455
+ for (const k of Object.keys(headFiles)) {
6456
+ if (!Object.prototype.hasOwnProperty.call(liveFiles, k)) stagePath(k);
6457
+ }
6458
+ for (const stagedKey of Array.from(stagedMap.keys())) {
6459
+ if (
6460
+ !Object.prototype.hasOwnProperty.call(liveFiles, stagedKey) &&
6461
+ !Object.prototype.hasOwnProperty.call(headFiles, stagedKey)
6462
+ ) {
6463
+ stagedMap.delete(stagedKey);
6464
+ }
5828
6465
  }
5829
6466
  } else {
5830
6467
  const dirPrefix = rel.replace(/\/+$/, '') + '/';
5831
- const matchedSubfiles = Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix));
6468
+ const matchedSubfiles = Array.from(
6469
+ new Set([
6470
+ ...Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix)),
6471
+ ...Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix)),
6472
+ ...Array.from(stagedMap.keys()).filter((k) => k.startsWith(dirPrefix))
6473
+ ])
6474
+ );
5832
6475
  if (matchedSubfiles.length > 0) {
5833
- for (const k of matchedSubfiles) gitState.staged.add(k);
6476
+ for (const k of matchedSubfiles) stagePath(k);
5834
6477
  } else {
5835
- gitState.staged.add(rel);
6478
+ stagePath(rel);
5836
6479
  }
5837
6480
  }
5838
6481
  }
@@ -5842,37 +6485,72 @@ var CodeLabLogger = (() => {
5842
6485
 
5843
6486
  if (subcmd === 'commit') {
5844
6487
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5845
- const headFiles = gitState.headSnapshot || {};
5846
- if (args.includes('-a') || args.includes('-am')) {
6488
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6489
+ const autoStageTracked = args.some(
6490
+ (a) =>
6491
+ a === '-a' ||
6492
+ a === '--all' ||
6493
+ (a.startsWith('-') && !a.startsWith('--') && a !== '-m' && a.includes('a'))
6494
+ );
6495
+ if (autoStageTracked) {
5847
6496
  for (const relPath of Object.keys(headFiles)) {
5848
- if (liveFiles[relPath] !== headFiles[relPath]) {
5849
- gitState.staged.add(relPath);
6497
+ if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
6498
+ applyShellStagedEntry(gitState, stagedMap, relPath, null, headFiles);
6499
+ } else {
6500
+ applyShellStagedEntry(gitState, stagedMap, relPath, liveFiles[relPath], headFiles);
5850
6501
  }
5851
6502
  }
5852
6503
  }
5853
6504
 
6505
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6506
+
6507
+ if (stagedMap.size === 0) {
6508
+ return {
6509
+ code: 1,
6510
+ stdout: `On branch ${gitState.branch}\nnothing to commit, working tree clean\n`,
6511
+ stderr: ''
6512
+ };
6513
+ }
6514
+
5854
6515
  let msg = 'Commit changes';
5855
- const mIdx = args.findIndex((a) => a === '-m' || a === '-am');
6516
+ const mIdx = args.findIndex(
6517
+ (a) => a === '-m' || a === '-am' || a === '-ma'
6518
+ );
5856
6519
  if (mIdx !== -1 && mIdx + 1 < args.length) msg = args[mIdx + 1];
5857
6520
 
5858
- for (const relPath of gitState.staged) {
5859
- if (Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5860
- gitState.headSnapshot[relPath] = liveFiles[relPath];
6521
+ const nextHead = Object.assign({}, headFiles);
6522
+ const summaryParts = [];
6523
+ for (const [relPath, stagedVal] of stagedMap.entries()) {
6524
+ summaryParts.push(`${relPath}:${stagedVal === null ? '<DEL>' : stagedVal}`);
6525
+ if (stagedVal === null) {
6526
+ delete nextHead[relPath];
5861
6527
  } else {
5862
- delete gitState.headSnapshot[relPath];
6528
+ nextHead[relPath] = String(stagedVal);
5863
6529
  }
5864
6530
  }
5865
6531
 
5866
- const hash = Math.random().toString(16).slice(2, 9);
6532
+ const commitTs = Date.now();
6533
+ const hash = computeGitShortHash(
6534
+ `${gitState.headCommit || ''}:${msg}:${commitTs}:${gitState.commits.length}:${summaryParts.join('|')}`
6535
+ );
6536
+ const count = stagedMap.size;
6537
+ gitState.headSnapshot = nextHead;
6538
+ gitState.headFiles = nextHead;
5867
6539
  gitState.commits.unshift({
5868
6540
  hash,
5869
- author: `${ctx.env.USER || 'codelab'} <dev@codelab.internal>`,
5870
- date: new Date().toUTCString(),
5871
- message: msg
6541
+ author: `${ctx.env.USER || 'CodeLab Developer'} <dev@codelab.internal>`,
6542
+ date: new Date(commitTs).toUTCString(),
6543
+ timestamp: commitTs,
6544
+ message: msg,
6545
+ files: Object.assign({}, nextHead)
5872
6546
  });
5873
- const count = gitState.staged.size || 1;
5874
- gitState.staged.clear();
5875
- return { code: 0, stdout: `[${gitState.branch} ${hash}] ${msg}\n ${count} file changed\n`, stderr: '' };
6547
+ gitState.headCommit = hash;
6548
+ stagedMap.clear();
6549
+ return {
6550
+ code: 0,
6551
+ stdout: `[${gitState.branch} ${hash}] ${msg}\n ${count} file${count === 1 ? '' : 's'} changed\n`,
6552
+ stderr: ''
6553
+ };
5876
6554
  }
5877
6555
 
5878
6556
  if (subcmd === 'branch') {
@@ -5932,9 +6610,11 @@ var CodeLabLogger = (() => {
5932
6610
  }
5933
6611
 
5934
6612
  const rel = toRepoRel(target);
5935
- if (gitState.headSnapshot && Object.prototype.hasOwnProperty.call(gitState.headSnapshot, rel)) {
6613
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6614
+ if (rel && Object.prototype.hasOwnProperty.call(headFiles, rel)) {
5936
6615
  const abs = PosixPath.join(repoRoot, rel);
5937
- ctx.vfs.writeFileSync(abs, gitState.headSnapshot[rel]);
6616
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6617
+ ctx.vfs.writeFileSync(abs, headFiles[rel]);
5938
6618
  ctx.emitMutation('change', abs);
5939
6619
  return { code: 0, stdout: `Updated 1 path from the index\n`, stderr: '' };
5940
6620
  }
@@ -5944,20 +6624,199 @@ var CodeLabLogger = (() => {
5944
6624
 
5945
6625
  if (subcmd === 'restore') {
5946
6626
  const isStaged = args.includes('--staged') || args.includes('-S');
5947
- const targets = args.slice(1).filter((a) => !a.startsWith('-'));
6627
+ const isWorktree = args.includes('--worktree') || args.includes('-W') || !isStaged;
6628
+ const targets = args.slice(1).filter((a) => !a.startsWith('-') && a !== '--');
6629
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
5948
6630
  for (const t of targets) {
5949
6631
  const rel = toRepoRel(t);
6632
+ if (!rel) continue;
5950
6633
  if (isStaged) {
5951
- gitState.staged.delete(rel);
5952
- } else if (gitState.headSnapshot && Object.prototype.hasOwnProperty.call(gitState.headSnapshot, rel)) {
6634
+ if (rel === '.') {
6635
+ stagedMap.clear();
6636
+ } else {
6637
+ const cleanRel = rel.replace(/\/+$/, '');
6638
+ const dirPrefix = cleanRel + '/';
6639
+ stagedMap.delete(cleanRel);
6640
+ for (const k of Array.from(stagedMap.keys())) {
6641
+ if (k.startsWith(dirPrefix)) {
6642
+ stagedMap.delete(k);
6643
+ }
6644
+ }
6645
+ }
6646
+ }
6647
+ if (isWorktree) {
6648
+ if (rel === '.') {
6649
+ for (const [k, v] of Object.entries(headFiles)) {
6650
+ const abs = PosixPath.join(repoRoot, k);
6651
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6652
+ ctx.vfs.writeFileSync(abs, v);
6653
+ ctx.emitMutation('change', abs);
6654
+ }
6655
+ } else {
6656
+ const cleanRel = rel.replace(/\/+$/, '');
6657
+ const dirPrefix = cleanRel + '/';
6658
+ const subHeadKeys = Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix));
6659
+ if (subHeadKeys.length > 0 && !Object.prototype.hasOwnProperty.call(headFiles, cleanRel)) {
6660
+ for (const k of subHeadKeys) {
6661
+ const sourceText =
6662
+ !isStaged && stagedMap.has(k) && stagedMap.get(k) !== null
6663
+ ? stagedMap.get(k)
6664
+ : headFiles[k];
6665
+ const abs = PosixPath.join(repoRoot, k);
6666
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6667
+ ctx.vfs.writeFileSync(abs, String(sourceText));
6668
+ ctx.emitMutation('change', abs);
6669
+ }
6670
+ } else {
6671
+ const sourceText =
6672
+ !isStaged && stagedMap.has(cleanRel) && stagedMap.get(cleanRel) !== null
6673
+ ? stagedMap.get(cleanRel)
6674
+ : (Object.prototype.hasOwnProperty.call(headFiles, cleanRel) ? headFiles[cleanRel] : undefined);
6675
+ if (sourceText !== undefined) {
6676
+ const abs = PosixPath.join(repoRoot, cleanRel);
6677
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6678
+ ctx.vfs.writeFileSync(abs, String(sourceText));
6679
+ ctx.emitMutation('change', abs);
6680
+ }
6681
+ }
6682
+ }
6683
+ }
6684
+ }
6685
+ return { code: 0, stdout: '', stderr: '' };
6686
+ }
6687
+
6688
+ if (subcmd === 'reset') {
6689
+ const isHard = args.includes('--hard');
6690
+ const fileArgs = args.slice(1).filter((a) => !a.startsWith('-') && a !== 'HEAD' && a !== '--');
6691
+ if (fileArgs.length > 0) {
6692
+ for (const f of fileArgs) {
6693
+ const rel = toRepoRel(f);
6694
+ if (!rel) continue;
6695
+ if (rel === '.') {
6696
+ stagedMap.clear();
6697
+ } else {
6698
+ const cleanRel = rel.replace(/\/+$/, '');
6699
+ const dirPrefix = cleanRel + '/';
6700
+ stagedMap.delete(cleanRel);
6701
+ for (const k of Array.from(stagedMap.keys())) {
6702
+ if (k.startsWith(dirPrefix)) {
6703
+ stagedMap.delete(k);
6704
+ }
6705
+ }
6706
+ }
6707
+ }
6708
+ return { code: 0, stdout: '', stderr: '' };
6709
+ }
6710
+ stagedMap.clear();
6711
+ if (isHard) {
6712
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6713
+ const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
6714
+ for (const rel of Object.keys(liveFiles)) {
6715
+ if (!Object.prototype.hasOwnProperty.call(headFiles, rel)) {
6716
+ const abs = PosixPath.join(repoRoot, rel);
6717
+ if (typeof ctx.vfs.rmSync === 'function') {
6718
+ ctx.vfs.rmSync(abs, { force: true });
6719
+ } else if (typeof ctx.vfs.unlinkSync === 'function' && ctx.vfs.existsSync(abs)) {
6720
+ ctx.vfs.unlinkSync(abs);
6721
+ }
6722
+ ctx.emitMutation('delete', abs);
6723
+ }
6724
+ }
6725
+ for (const [rel, text] of Object.entries(headFiles)) {
5953
6726
  const abs = PosixPath.join(repoRoot, rel);
5954
- ctx.vfs.writeFileSync(abs, gitState.headSnapshot[rel]);
6727
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6728
+ ctx.vfs.writeFileSync(abs, text);
5955
6729
  ctx.emitMutation('change', abs);
5956
6730
  }
5957
6731
  }
5958
6732
  return { code: 0, stdout: '', stderr: '' };
5959
6733
  }
5960
6734
 
6735
+ if (subcmd === 'rm') {
6736
+ const cachedOnly = args.includes('--cached');
6737
+ const isRecursive = args.some((a) => a === '-r' || a === '-rf' || a === '-fr');
6738
+ const targets = args.slice(1).filter((a) => !a.startsWith('-') && a !== '--');
6739
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6740
+ const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
6741
+
6742
+ if (targets.length === 0) {
6743
+ return { code: 128, stdout: '', stderr: 'usage: git rm [--cached] [-r] [-f] <file>...\n' };
6744
+ }
6745
+
6746
+ const removeSingleRel = (rel) => {
6747
+ if (!rel) return;
6748
+ const abs = PosixPath.join(repoRoot, rel);
6749
+ if (!cachedOnly && ctx.vfs.existsSync(abs)) {
6750
+ if (typeof ctx.vfs.rmSync === 'function') {
6751
+ ctx.vfs.rmSync(abs, { force: true, recursive: isRecursive });
6752
+ } else if (typeof ctx.vfs.unlinkSync === 'function') {
6753
+ ctx.vfs.unlinkSync(abs);
6754
+ }
6755
+ ctx.emitMutation('delete', abs);
6756
+ }
6757
+ if (Object.prototype.hasOwnProperty.call(headFiles, rel)) {
6758
+ stagedMap.set(rel, null);
6759
+ } else {
6760
+ stagedMap.delete(rel);
6761
+ }
6762
+ };
6763
+
6764
+ for (const t of targets) {
6765
+ const rel = toRepoRel(t);
6766
+ if (!rel) continue;
6767
+ if (rel === '.') {
6768
+ if (isRecursive) {
6769
+ const allRel = Array.from(
6770
+ new Set([
6771
+ ...Object.keys(headFiles),
6772
+ ...Object.keys(liveFiles),
6773
+ ...Array.from(stagedMap.keys())
6774
+ ])
6775
+ );
6776
+ for (const sub of allRel) removeSingleRel(sub);
6777
+ }
6778
+ continue;
6779
+ }
6780
+ const dirPrefix = rel.replace(/\/+$/, '') + '/';
6781
+ const subMatches = isRecursive
6782
+ ? Array.from(
6783
+ new Set([
6784
+ ...Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix)),
6785
+ ...Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix)),
6786
+ ...Array.from(stagedMap.keys()).filter((k) => k.startsWith(dirPrefix))
6787
+ ])
6788
+ )
6789
+ : [];
6790
+ if (subMatches.length > 0) {
6791
+ for (const sub of subMatches) removeSingleRel(sub);
6792
+ if (!cachedOnly) removeDirRecursive(ctx.vfs, PosixPath.join(repoRoot, rel), ctx.emitMutation);
6793
+ } else {
6794
+ const abs = PosixPath.join(repoRoot, rel);
6795
+ if (
6796
+ !isRecursive &&
6797
+ ctx.vfs &&
6798
+ typeof ctx.vfs.existsSync === 'function' &&
6799
+ ctx.vfs.existsSync(abs) &&
6800
+ typeof ctx.vfs.statSync === 'function'
6801
+ ) {
6802
+ try {
6803
+ if (ctx.vfs.statSync(abs).isDirectory()) {
6804
+ return {
6805
+ code: 128,
6806
+ stdout: '',
6807
+ stderr: `fatal: not removing '${t}' recursively without -r\n`
6808
+ };
6809
+ }
6810
+ } catch (err) {
6811
+ _shellLogger.debug('Failed statting path in git rm.', abs, err);
6812
+ }
6813
+ }
6814
+ removeSingleRel(rel);
6815
+ }
6816
+ }
6817
+ return { code: 0, stdout: '', stderr: '' };
6818
+ }
6819
+
5961
6820
  if (subcmd === 'remote') {
5962
6821
  const sub = args[1];
5963
6822
  if (!sub) {
@@ -6005,7 +6864,9 @@ var CodeLabLogger = (() => {
6005
6864
  signal: ctx.signal,
6006
6865
  onFile: (absPath) => ctx.emitMutation('change', absPath)
6007
6866
  });
6008
- gitState.headSnapshot = Object.assign({}, result.headSnapshot);
6867
+ const pulledHead = Object.assign({}, result.headSnapshot);
6868
+ gitState.headSnapshot = pulledHead;
6869
+ gitState.headFiles = pulledHead;
6009
6870
  return {
6010
6871
  code: 0,
6011
6872
  stdout: `From ${remoteUrl.replace(/\.git$/, '')}\n * branch ${result.branch} -> FETCH_HEAD\nAlready up to date.\n`,
@@ -6032,9 +6893,11 @@ var CodeLabLogger = (() => {
6032
6893
  if (oneline) {
6033
6894
  stdout += `${c.hash} ${c.message}\n`;
6034
6895
  } else {
6896
+ const authorStr = c.author || 'CodeLab Developer <dev@codelab.internal>';
6897
+ const dateStr = c.date || (c.timestamp ? new Date(c.timestamp).toUTCString() : new Date(0).toUTCString());
6035
6898
  stdout += `commit ${c.hash}\n`;
6036
- stdout += `Author: ${c.author}\n`;
6037
- stdout += `Date: ${c.date}\n\n`;
6899
+ stdout += `Author: ${authorStr}\n`;
6900
+ stdout += `Date: ${dateStr}\n\n`;
6038
6901
  stdout += ` ${c.message}\n\n`;
6039
6902
  }
6040
6903
  }
@@ -6111,6 +6974,9 @@ var CodeLabLogger = (() => {
6111
6974
  mode: 'repl',
6112
6975
  replCode: code,
6113
6976
  printReplResult: false,
6977
+ stdin: ctx.stdin || '',
6978
+ env: ctx.env,
6979
+ cwd: ctx.cwd,
6114
6980
  vfs: ctx.vfs,
6115
6981
  activePortTable: ctx.shell.portTable,
6116
6982
  pid: ctx.pid,
@@ -6128,6 +6994,9 @@ var CodeLabLogger = (() => {
6128
6994
  mode: 'repl',
6129
6995
  replCode: code,
6130
6996
  printReplResult: true,
6997
+ stdin: ctx.stdin || '',
6998
+ env: ctx.env,
6999
+ cwd: ctx.cwd,
6131
7000
  vfs: ctx.vfs,
6132
7001
  activePortTable: ctx.shell.portTable,
6133
7002
  pid: ctx.pid,
@@ -6167,6 +7036,9 @@ var CodeLabLogger = (() => {
6167
7036
  const res = await executeInVirtualRuntime({
6168
7037
  mode: 'test',
6169
7038
  entry: f,
7039
+ stdin: ctx.stdin || '',
7040
+ env: ctx.env,
7041
+ cwd: ctx.cwd,
6170
7042
  vfs: ctx.vfs,
6171
7043
  activePortTable: ctx.shell.portTable,
6172
7044
  pid: ctx.pid,
@@ -6192,6 +7064,9 @@ var CodeLabLogger = (() => {
6192
7064
  mode: 'run',
6193
7065
  entry: scriptFile,
6194
7066
  argv: ['node', scriptFile, ...scriptArgs],
7067
+ stdin: ctx.stdin || '',
7068
+ env: ctx.env,
7069
+ cwd: ctx.cwd,
6195
7070
  vfs: ctx.vfs,
6196
7071
  activePortTable: ctx.shell.portTable,
6197
7072
  pid: ctx.pid,
@@ -6359,6 +7234,9 @@ var CodeLabLogger = (() => {
6359
7234
  const res = await pyCompiler({
6360
7235
  entry: entryFile,
6361
7236
  source: codeToRun,
7237
+ stdin: ctx.stdin || '',
7238
+ env: ctx.env,
7239
+ cwd: ctx.cwd,
6362
7240
  vfs: ctx.vfs,
6363
7241
  onStdout: (t) => {
6364
7242
  outText += t;
@@ -6425,9 +7303,9 @@ var CodeLabLogger = (() => {
6425
7303
  };
6426
7304
  }
6427
7305
  return {
6428
- code: 0,
6429
- stdout: `Successfully installed ${pkgs.join(', ') || 'packages'}\n`,
6430
- stderr: ''
7306
+ code: 1,
7307
+ stdout: '',
7308
+ stderr: 'pip: Python WebAssembly toolchain is not enabled. Enable pythonExtension from "@innovatorved/code-lab/extensions/python".\n'
6431
7309
  };
6432
7310
  }
6433
7311
  return { code: 0, stdout: 'pip 24.0 (Pyodide micropip)\n', stderr: '' };
@@ -6545,6 +7423,9 @@ var CodeLabLogger = (() => {
6545
7423
  mode: 'repl',
6546
7424
  replCode: code,
6547
7425
  printReplResult: false,
7426
+ stdin: ctx.stdin || '',
7427
+ env: ctx.env,
7428
+ cwd: ctx.cwd,
6548
7429
  vfs: ctx.vfs,
6549
7430
  activePortTable: ctx.shell.portTable,
6550
7431
  pid: ctx.pid,
@@ -6584,6 +7465,9 @@ var CodeLabLogger = (() => {
6584
7465
  const res = await executeInVirtualRuntime({
6585
7466
  mode: 'test',
6586
7467
  entry: f,
7468
+ stdin: ctx.stdin || '',
7469
+ env: ctx.env,
7470
+ cwd: ctx.cwd,
6587
7471
  vfs: ctx.vfs,
6588
7472
  activePortTable: ctx.shell.portTable,
6589
7473
  pid: ctx.pid,
@@ -6611,6 +7495,9 @@ var CodeLabLogger = (() => {
6611
7495
  mode: 'run',
6612
7496
  entry: resolved,
6613
7497
  argv: ['bun', resolved, ...scriptArgs],
7498
+ stdin: ctx.stdin || '',
7499
+ env: ctx.env,
7500
+ cwd: ctx.cwd,
6614
7501
  vfs: ctx.vfs,
6615
7502
  activePortTable: ctx.shell.portTable,
6616
7503
  pid: ctx.pid,
@@ -6635,6 +7522,9 @@ var CodeLabLogger = (() => {
6635
7522
  mode: 'run',
6636
7523
  entry: resolved,
6637
7524
  argv: ['bun', resolved, ...scriptArgs],
7525
+ stdin: ctx.stdin || '',
7526
+ env: ctx.env,
7527
+ cwd: ctx.cwd,
6638
7528
  vfs: ctx.vfs,
6639
7529
  activePortTable: ctx.shell.portTable,
6640
7530
  pid: ctx.pid,
@@ -6916,12 +7806,24 @@ var CodeLabLogger = (() => {
6916
7806
  if (!method) method = 'GET';
6917
7807
 
6918
7808
  const portTable = (ctx.shell && ctx.shell.portTable) || null;
7809
+ const fetchImpl = (ctx.shell && ctx.shell.options && typeof (ctx.shell.options.fetch || ctx.shell.options.fetchImpl) === 'function')
7810
+ ? (ctx.shell.options.fetch || ctx.shell.options.fetchImpl)
7811
+ : fetch;
7812
+ let isLoopback = false;
7813
+ try {
7814
+ const parsedUrl = new URL(url);
7815
+ const host = parsedUrl.hostname.toLowerCase();
7816
+ isLoopback = host === 'localhost' || host === '127.0.0.1' || host === '0.0.0.0' || host === '::1' || host === '[::1]';
7817
+ } catch (err) {
7818
+ _shellLogger.debug('curl URL parse fallback', url, err);
7819
+ }
6919
7820
  let resp = null;
6920
7821
  let lastErr = null;
7822
+ const maxAttempts = portTable && isLoopback ? 25 : 1;
6921
7823
 
6922
- for (let attempt = 0; attempt < 25; attempt++) {
7824
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
6923
7825
  try {
6924
- if (portTable) {
7826
+ if (portTable && isLoopback) {
6925
7827
  resp = await portTable.dispatchRequest(url, {
6926
7828
  method,
6927
7829
  headers,
@@ -6930,7 +7832,7 @@ var CodeLabLogger = (() => {
6930
7832
  lastErr = null;
6931
7833
  break;
6932
7834
  } else {
6933
- resp = await fetch(url, {
7835
+ resp = await fetchImpl(url, {
6934
7836
  method,
6935
7837
  headers,
6936
7838
  body: data
@@ -6941,7 +7843,9 @@ var CodeLabLogger = (() => {
6941
7843
  } catch (err) {
6942
7844
  lastErr = err;
6943
7845
  if (err && err.chaosEffect) break;
6944
- await new Promise(r => setTimeout(r, 15));
7846
+ if (attempt + 1 < maxAttempts) {
7847
+ await new Promise(r => setTimeout(r, 15));
7848
+ }
6945
7849
  }
6946
7850
  }
6947
7851
 
@@ -7020,6 +7924,17 @@ var CodeLabLogger = (() => {
7020
7924
  concurrency = Math.min(concurrency, totalRequests);
7021
7925
 
7022
7926
  const portTable = (ctx.shell && ctx.shell.portTable) || null;
7927
+ const fetchImpl = (ctx.shell && ctx.shell.options && typeof (ctx.shell.options.fetch || ctx.shell.options.fetchImpl) === 'function')
7928
+ ? (ctx.shell.options.fetch || ctx.shell.options.fetchImpl)
7929
+ : fetch;
7930
+ let isLoopback = false;
7931
+ try {
7932
+ const parsedUrl = new URL(url);
7933
+ const host = parsedUrl.hostname.toLowerCase();
7934
+ isLoopback = host === 'localhost' || host === '127.0.0.1' || host === '0.0.0.0' || host === '::1' || host === '[::1]';
7935
+ } catch (err) {
7936
+ _shellLogger.debug('hey URL parse fallback', url, err);
7937
+ }
7023
7938
  const latencies = [];
7024
7939
  const statusCounts = {};
7025
7940
  const errorCounts = {};
@@ -7035,10 +7950,10 @@ var CodeLabLogger = (() => {
7035
7950
  const reqStart = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();
7036
7951
  try {
7037
7952
  let resp;
7038
- if (portTable) {
7953
+ if (portTable && isLoopback) {
7039
7954
  resp = await portTable.dispatchRequest(url, { method, headers: { ...headers }, body });
7040
7955
  } else {
7041
- resp = await fetch(url, { method, headers: { ...headers }, body });
7956
+ resp = await fetchImpl(url, { method, headers: { ...headers }, body });
7042
7957
  }
7043
7958
  const reqEnd = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();
7044
7959
  const dur = Math.max(0.05, reqEnd - reqStart);
@@ -7799,6 +8714,16 @@ var CodeLabLogger = (() => {
7799
8714
  if (options.files && typeof options.files === 'object') {
7800
8715
  for (const [k, v] of Object.entries(options.files)) {
7801
8716
  const abs = PosixPath.resolve(this.cwd, k);
8717
+ if (typeof this.vfs.mkdirSync === 'function') {
8718
+ const parentDir = PosixPath.dirname(abs);
8719
+ if (
8720
+ parentDir &&
8721
+ parentDir !== '/' &&
8722
+ (typeof this.vfs.existsSync !== 'function' || !this.vfs.existsSync(parentDir))
8723
+ ) {
8724
+ this.vfs.mkdirSync(parentDir, { recursive: true });
8725
+ }
8726
+ }
7802
8727
  if (typeof this.vfs.writeFileSync === 'function') {
7803
8728
  this.vfs.writeFileSync(abs, String(v ?? ''));
7804
8729
  }
@@ -7810,23 +8735,19 @@ var CodeLabLogger = (() => {
7810
8735
  this.nextPid = 100;
7811
8736
  this.commands = Object.assign({}, COREUTILS, options.commands || {});
7812
8737
 
7813
- this.gitState = {
7814
- branch: 'main',
7815
- branches: new Set(['main']),
7816
- remoteUrl: null,
7817
- remotes: {},
7818
- repoRoot: this.cwd,
7819
- headSnapshot: snapshotWorktree(this.vfs, this.cwd),
7820
- staged: new Set(),
7821
- commits: [
7822
- {
7823
- hash: 'a1b2c3d',
7824
- author: 'CodeLab Developer <dev@codelab.internal>',
7825
- date: new Date().toUTCString(),
7826
- message: 'Initial project commit'
7827
- }
7828
- ]
7829
- };
8738
+ this._initialBootRoot = options._initialBootRoot
8739
+ ? PosixPath.normalize(options._initialBootRoot)
8740
+ : PosixPath.normalize(this.cwd || '/workspace');
8741
+ this._initialBootSnapshot =
8742
+ options._initialBootSnapshot && typeof options._initialBootSnapshot === 'object'
8743
+ ? options._initialBootSnapshot
8744
+ : snapshotWorktree(this.vfs, this._initialBootRoot);
8745
+
8746
+ if (options.gitState && typeof options.gitState === 'object') {
8747
+ this.gitState = options.gitState;
8748
+ } else {
8749
+ this.gitState = createUnifiedShellGitState(this.vfs, this.cwd, options);
8750
+ }
7830
8751
  }
7831
8752
 
7832
8753
  resolvePath(p) {
@@ -7955,6 +8876,9 @@ var CodeLabLogger = (() => {
7955
8876
  ...this.options,
7956
8877
  vfs: this.vfs,
7957
8878
  portTable: this.portTable,
8879
+ gitState: this.gitState,
8880
+ _initialBootRoot: this._initialBootRoot,
8881
+ _initialBootSnapshot: this._initialBootSnapshot,
7958
8882
  env: { ...env, PWD: this.cwd }
7959
8883
  });
7960
8884
  subShell.cwd = this.cwd;
@@ -7971,6 +8895,15 @@ var CodeLabLogger = (() => {
7971
8895
  }
7972
8896
 
7973
8897
  this.history.push(trimmed);
8898
+ if (this.history.length > 1000) {
8899
+ this.history.splice(0, this.history.length - 1000);
8900
+ }
8901
+ if (this.jobs.size > 256) {
8902
+ for (const [jid, j] of this.jobs.entries()) {
8903
+ if (this.jobs.size <= 256) break;
8904
+ if (j && j.status !== 'Running') this.jobs.delete(jid);
8905
+ }
8906
+ }
7974
8907
 
7975
8908
  const cwd = execOptions.cwd ? this.resolvePath(execOptions.cwd) : this.cwd;
7976
8909
  this.cwd = cwd;
@@ -8040,6 +8973,10 @@ var CodeLabLogger = (() => {
8040
8973
  if (res.aborted || (execOptions.signal && execOptions.signal.aborted)) {
8041
8974
  return { code: 130, exitCode: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
8042
8975
  }
8976
+ if (res.controlFlow && res.controlFlow.type === 'exit') {
8977
+ lastCode = res.controlFlow.code !== undefined ? res.controlFlow.code : lastCode;
8978
+ break;
8979
+ }
8043
8980
  }
8044
8981
  }
8045
8982
 
@@ -8050,6 +8987,218 @@ var CodeLabLogger = (() => {
8050
8987
  return this.execute(commandLine, execOptions);
8051
8988
  }
8052
8989
 
8990
+ async _expandHeredocBody(rawBody, cmdEnv) {
8991
+ const src = String(rawBody || '');
8992
+ let out = '';
8993
+ let i = 0;
8994
+ while (i < src.length) {
8995
+ const ch = src[i];
8996
+ if (ch === '\\' && i + 1 < src.length && '$`\\\n'.includes(src[i + 1])) {
8997
+ if (src[i + 1] === '\n') {
8998
+ i += 2;
8999
+ continue;
9000
+ }
9001
+ out += src[i + 1];
9002
+ i += 2;
9003
+ continue;
9004
+ }
9005
+ if (ch === '$' && src[i + 1] === '(' && src[i + 2] === '(') {
9006
+ i += 3;
9007
+ let depth = 2;
9008
+ let expr = '';
9009
+ while (i < src.length && depth > 0) {
9010
+ if (src[i] === '(') { depth++; expr += '('; i++; }
9011
+ else if (src[i] === ')') {
9012
+ if (depth === 2 && src[i + 1] === ')') { depth = 0; i += 2; break; }
9013
+ depth--;
9014
+ if (depth > 0) expr += ')';
9015
+ i++;
9016
+ } else {
9017
+ expr += src[i++];
9018
+ }
9019
+ }
9020
+ out += evaluateArithmetic(expr, cmdEnv, this.env);
9021
+ continue;
9022
+ }
9023
+ if (ch === '$' && src[i + 1] === '(') {
9024
+ i += 2;
9025
+ let depth = 1;
9026
+ let sub = '';
9027
+ while (i < src.length && depth > 0) {
9028
+ if (src[i] === '(') depth++;
9029
+ else if (src[i] === ')') depth--;
9030
+ if (depth > 0) sub += src[i];
9031
+ i++;
9032
+ }
9033
+ out += await this._executeSubshell(sub, cmdEnv);
9034
+ continue;
9035
+ }
9036
+ if (ch === '`') {
9037
+ i++;
9038
+ let sub = '';
9039
+ while (i < src.length && src[i] !== '`') sub += src[i++];
9040
+ if (i < src.length && src[i] === '`') i++;
9041
+ out += await this._executeSubshell(sub, cmdEnv);
9042
+ continue;
9043
+ }
9044
+ if (ch === '$') {
9045
+ i++;
9046
+ if (src[i] === '{') {
9047
+ i++;
9048
+ let varName = '';
9049
+ let bDepth = 1;
9050
+ while (i < src.length && bDepth > 0) {
9051
+ if (src[i] === '{') bDepth++;
9052
+ else if (src[i] === '}') bDepth--;
9053
+ if (bDepth > 0) varName += src[i];
9054
+ i++;
9055
+ }
9056
+ out += this._expandVariable(varName, cmdEnv);
9057
+ } else if (i < src.length && /[0-9?!$#@*]/.test(src[i])) {
9058
+ out += this._expandVariable(src[i++], cmdEnv);
9059
+ } else if (i < src.length && /[a-zA-Z_]/.test(src[i])) {
9060
+ let varName = '';
9061
+ while (i < src.length && /[a-zA-Z0-9_]/.test(src[i])) varName += src[i++];
9062
+ out += this._expandVariable(varName, cmdEnv);
9063
+ } else {
9064
+ out += '$';
9065
+ }
9066
+ continue;
9067
+ }
9068
+ out += ch;
9069
+ i++;
9070
+ }
9071
+ return out;
9072
+ }
9073
+
9074
+ async _resolveInputRedirect(red, cmdEnv) {
9075
+ if (red.type === '<') {
9076
+ const target = await this.evaluateWord(red.target, cmdEnv);
9077
+ const absTarget = this.resolvePath(target);
9078
+ if (!this.vfs.existsSync(absTarget)) {
9079
+ return { ok: false, error: { code: 1, stdout: '', stderr: `shell: ${target}: No such file or directory\n` } };
9080
+ }
9081
+ try {
9082
+ return { ok: true, stdin: this.vfs.readFileSync(absTarget, 'utf8') };
9083
+ } catch (err) {
9084
+ return { ok: false, error: { code: 1, stdout: '', stderr: `shell: ${target}: ${err.message}\n` } };
9085
+ }
9086
+ }
9087
+ if (red.type === '<<<') {
9088
+ const val = await this.evaluateWord(red.target, cmdEnv);
9089
+ return { ok: true, stdin: val + '\n' };
9090
+ }
9091
+ if (red.type === '<<') {
9092
+ let body = String(red.body || '');
9093
+ if (red.stripTabs) {
9094
+ body = body.replace(/^\t+/gm, '');
9095
+ }
9096
+ if (!red.quoted) {
9097
+ body = await this._expandHeredocBody(body, cmdEnv);
9098
+ }
9099
+ return { ok: true, stdin: body };
9100
+ }
9101
+ return null;
9102
+ }
9103
+
9104
+ _evaluateDoubleBracket(rawArgs) {
9105
+ const closeIdx = rawArgs.lastIndexOf(']]');
9106
+ if (closeIdx === -1) {
9107
+ return { code: 2, stdout: '', stderr: 'shell: [[: missing `]]`\n' };
9108
+ }
9109
+ const tokens = rawArgs.slice(0, closeIdx);
9110
+ let idx = 0;
9111
+
9112
+ const globToRegExp = (pat) => {
9113
+ let re = '^';
9114
+ for (let i = 0; i < pat.length; i++) {
9115
+ const c = pat[i];
9116
+ if (c === '*') re += '.*';
9117
+ else if (c === '?') re += '.';
9118
+ else re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
9119
+ }
9120
+ return new RegExp(re + '$');
9121
+ };
9122
+
9123
+ const parseOr = () => {
9124
+ let left = parseAnd();
9125
+ while (tokens[idx] === '||') {
9126
+ idx++;
9127
+ const right = parseAnd();
9128
+ left = left || right;
9129
+ }
9130
+ return left;
9131
+ };
9132
+
9133
+ const parseAnd = () => {
9134
+ let left = parseNot();
9135
+ while (tokens[idx] === '&&') {
9136
+ idx++;
9137
+ const right = parseNot();
9138
+ left = left && right;
9139
+ }
9140
+ return left;
9141
+ };
9142
+
9143
+ const parseNot = () => {
9144
+ if (tokens[idx] === '!') {
9145
+ idx++;
9146
+ return !parseNot();
9147
+ }
9148
+ return parsePrimary();
9149
+ };
9150
+
9151
+ const parsePrimary = () => {
9152
+ if (idx >= tokens.length) return false;
9153
+ if (tokens[idx] === '(') {
9154
+ idx++;
9155
+ const val = parseOr();
9156
+ if (tokens[idx] === ')') idx++;
9157
+ return val;
9158
+ }
9159
+ const unary = tokens[idx];
9160
+ if (/^-(?:z|n|e|f|d|s)$/.test(unary) && idx + 1 < tokens.length) {
9161
+ idx++;
9162
+ const operand = String(tokens[idx++] ?? '');
9163
+ if (unary === '-z') return operand.length === 0;
9164
+ if (unary === '-n') return operand.length > 0;
9165
+ const abs = this.resolvePath(operand);
9166
+ const exists = this.vfs.existsSync(abs);
9167
+ if (unary === '-e') return exists;
9168
+ if (!exists) return false;
9169
+ const st = this.vfs.statSync(abs);
9170
+ if (unary === '-d') return Boolean(st && st.isDirectory());
9171
+ if (unary === '-f') return Boolean(st && !st.isDirectory());
9172
+ if (unary === '-s') return Boolean(st && !st.isDirectory() && st.size > 0);
9173
+ }
9174
+ const left = String(tokens[idx++] ?? '');
9175
+ const op = tokens[idx];
9176
+ if (op && /^(?:==|=|!=|=~|<|>|-eq|-ne|-lt|-le|-gt|-ge)$/.test(op) && idx + 1 < tokens.length) {
9177
+ idx++;
9178
+ const right = String(tokens[idx++] ?? '');
9179
+ if (op === '==' || op === '=') return globToRegExp(right).test(left);
9180
+ if (op === '!=') return !globToRegExp(right).test(left);
9181
+ if (op === '=~') {
9182
+ try { return new RegExp(right).test(left); } catch (err) { _shellLogger.debug('[[ =~ invalid regex', right, err); return false; }
9183
+ }
9184
+ if (op === '<') return left < right;
9185
+ if (op === '>') return left > right;
9186
+ const ln = Number(left) || 0;
9187
+ const rn = Number(right) || 0;
9188
+ if (op === '-eq') return ln === rn;
9189
+ if (op === '-ne') return ln !== rn;
9190
+ if (op === '-lt') return ln < rn;
9191
+ if (op === '-le') return ln <= rn;
9192
+ if (op === '-gt') return ln > rn;
9193
+ if (op === '-ge') return ln >= rn;
9194
+ }
9195
+ return left.length > 0;
9196
+ };
9197
+
9198
+ const ok = parseOr();
9199
+ return { code: ok ? 0 : 1, stdout: '', stderr: '' };
9200
+ }
9201
+
8053
9202
  async _executeWithRedirects(redirects, context, execFn) {
8054
9203
  if (!redirects || redirects.length === 0) {
8055
9204
  return execFn(context);
@@ -8061,22 +9210,15 @@ var CodeLabLogger = (() => {
8061
9210
  let effectiveStdin = context.stdin || '';
8062
9211
 
8063
9212
  for (const red of redirects) {
8064
- if (red.type === '<') {
8065
- const target = await this.evaluateWord(red.target, cmdEnv);
8066
- const absTarget = this.resolvePath(target);
8067
- if (!this.vfs.existsSync(absTarget)) {
8068
- return { code: 1, stdout: '', stderr: `shell: ${target}: No such file or directory\n` };
8069
- }
8070
- try {
8071
- effectiveStdin = this.vfs.readFileSync(absTarget, 'utf8');
8072
- } catch (err) {
8073
- return { code: 1, stdout: '', stderr: `shell: ${target}: ${err.message}\n` };
8074
- }
9213
+ if (red.type === '<' || red.type === '<<' || red.type === '<<<') {
9214
+ const inRes = await this._resolveInputRedirect(red, cmdEnv);
9215
+ if (inRes && !inRes.ok) return inRes.error;
9216
+ if (inRes && inRes.ok) effectiveStdin = inRes.stdin;
8075
9217
  }
8076
9218
  }
8077
9219
 
8078
9220
  for (const red of redirects) {
8079
- if (red.type === '<') continue;
9221
+ if (red.type === '<' || red.type === '<<' || red.type === '<<<') continue;
8080
9222
  if (red.type === '>' || red.type === '>>' || red.type === '&>') {
8081
9223
  const target = await this.evaluateWord(red.target, cmdEnv);
8082
9224
  const abs = this.resolvePath(target);
@@ -8458,6 +9600,7 @@ var CodeLabLogger = (() => {
8458
9600
  ...this.options,
8459
9601
  vfs: this.vfs,
8460
9602
  portTable: this.portTable,
9603
+ gitState: this.gitState,
8461
9604
  env: Object.assign({}, this.env, innerCtx.env || {})
8462
9605
  });
8463
9606
  subShell.cwd = innerCtx.cwd || this.cwd;
@@ -8585,7 +9728,20 @@ var CodeLabLogger = (() => {
8585
9728
  args.push(...expanded);
8586
9729
  }
8587
9730
 
8588
- // 3. Built-in flow control
9731
+ // 3. Built-in flow control & POSIX special builtins
9732
+ if (cmdName === ':') {
9733
+ Object.assign(this.env, cmdEnv);
9734
+ Object.assign(context.env, cmdEnv);
9735
+ return { code: 0, stdout: '', stderr: '' };
9736
+ }
9737
+ if (cmdName === 'exit') {
9738
+ const rawCode = args.length > 0 ? parseInt(args[0], 10) : parseInt(this.env['?'] || '0', 10);
9739
+ const code = Number.isNaN(rawCode) ? 2 : ((rawCode % 256) + 256) % 256;
9740
+ return { code, stdout: '', stderr: '', controlFlow: { type: 'exit', code } };
9741
+ }
9742
+ if (cmdName === '[[') {
9743
+ return this._evaluateDoubleBracket(args);
9744
+ }
8589
9745
  if (cmdName === 'break') {
8590
9746
  const count = parseInt(args[0], 10) || 1;
8591
9747
  return { code: 0, stdout: '', stderr: '', controlFlow: { type: 'break', count } };
@@ -8603,20 +9759,13 @@ var CodeLabLogger = (() => {
8603
9759
  return { code: 130, stdout: '', stderr: '', aborted: true };
8604
9760
  }
8605
9761
 
8606
- // 4. Process input redirection (<, 0<)
9762
+ // 4. Process input redirection (<, 0<, <<, <<-, <<<)
8607
9763
  let effectiveStdin = context.stdin || '';
8608
9764
  for (const red of cmdNode.redirects) {
8609
- if (red.type === '<') {
8610
- const target = await this.evaluateWord(red.target, cmdEnv);
8611
- const absTarget = this.resolvePath(target);
8612
- if (!this.vfs.existsSync(absTarget)) {
8613
- return { code: 1, stdout: '', stderr: `shell: ${target}: No such file or directory\n` };
8614
- }
8615
- try {
8616
- effectiveStdin = this.vfs.readFileSync(absTarget, 'utf8');
8617
- } catch (err) {
8618
- return { code: 1, stdout: '', stderr: `shell: ${target}: ${err.message}\n` };
8619
- }
9765
+ if (red.type === '<' || red.type === '<<' || red.type === '<<<') {
9766
+ const inRes = await this._resolveInputRedirect(red, cmdEnv);
9767
+ if (inRes && !inRes.ok) return inRes.error;
9768
+ if (inRes && inRes.ok) effectiveStdin = inRes.stdin;
8620
9769
  }
8621
9770
  }
8622
9771
 
@@ -8625,7 +9774,7 @@ var CodeLabLogger = (() => {
8625
9774
  let fd2 = { type: 'stderr' };
8626
9775
 
8627
9776
  for (const red of cmdNode.redirects) {
8628
- if (red.type === '<') continue;
9777
+ if (red.type === '<' || red.type === '<<' || red.type === '<<<') continue;
8629
9778
  if (red.type === '>' || red.type === '>>' || red.type === '&>') {
8630
9779
  const target = await this.evaluateWord(red.target, cmdEnv);
8631
9780
  const abs = this.resolvePath(target);