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