@innovatorved/code-lab 0.1.7 → 0.1.9

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.
package/src/runtime.ts CHANGED
@@ -20,6 +20,14 @@ if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined')
20
20
  */
21
21
 
22
22
  function __initVirtualRuntime(rootScope) {
23
+ const _runtimeLogger = (rootScope && rootScope.CodeLabLogger && typeof rootScope.CodeLabLogger.createLogger === 'function')
24
+ ? rootScope.CodeLabLogger.createLogger()
25
+ : {
26
+ debug() {},
27
+ info() {},
28
+ warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
29
+ error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
30
+ };
23
31
  // =========================================================================
24
32
  // 1. UTF-8 / HEX / BASE64 / BASE64URL CODECS & VIRTUAL BUFFER
25
33
  // =========================================================================
@@ -1579,7 +1587,7 @@ function __initVirtualRuntime(rootScope) {
1579
1587
  },
1580
1588
  final(cb) {
1581
1589
  if (fd !== null) {
1582
- try { fsShim.closeSync(fd); } catch (_) {}
1590
+ try { fsShim.closeSync(fd); } catch (err) { _runtimeLogger.debug('vfs writeStream closeSync failed', err); }
1583
1591
  fd = null;
1584
1592
  }
1585
1593
  cb(null);
@@ -2099,7 +2107,9 @@ function __initVirtualRuntime(rootScope) {
2099
2107
  return pathname + search + hash;
2100
2108
  }
2101
2109
  return resolvedUrl.href;
2102
- } catch (_) {}
2110
+ } catch (err) {
2111
+ _runtimeLogger.debug('url.resolve fallback used', err);
2112
+ }
2103
2113
  }
2104
2114
  if (toStr.startsWith('/')) {
2105
2115
  const m = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]+)/.exec(fromStr);
@@ -2538,10 +2548,10 @@ function __initVirtualRuntime(rootScope) {
2538
2548
  for (const [port, entry] of Array.from(table.entries())) {
2539
2549
  if (entry.pid !== undefined && String(entry.pid) === pStr) {
2540
2550
  if (entry.server && typeof entry.server.close === 'function') {
2541
- try { entry.server.close(); } catch (_) {}
2551
+ try { entry.server.close(); } catch (err) { _runtimeLogger.debug('portTable server.close failed', err); }
2542
2552
  }
2543
2553
  if (typeof entry.stop === 'function') {
2544
- try { entry.stop(); } catch (_) {}
2554
+ try { entry.stop(); } catch (err) { _runtimeLogger.debug('portTable entry.stop failed', err); }
2545
2555
  }
2546
2556
  // Avoid a double 'close' emission when entry.server.close() already
2547
2557
  // unregistered the port through unregisterServer().
@@ -3178,7 +3188,7 @@ function __initVirtualRuntime(rootScope) {
3178
3188
  },
3179
3189
  closeAllServers() {
3180
3190
  for (const s of Array.from(activeServers.values())) {
3181
- try { s.close(); } catch (_) {}
3191
+ try { s.close(); } catch (err) { _runtimeLogger.debug('vhttp closeAllServers close failed', err); }
3182
3192
  }
3183
3193
  activeServers.clear();
3184
3194
  }
@@ -4004,7 +4014,7 @@ function __initVirtualRuntime(rootScope) {
4004
4014
 
4005
4015
  function closeAllServers() {
4006
4016
  for (const srv of servers.values()) {
4007
- try { srv.close(); } catch (_) {}
4017
+ try { srv.close(); } catch (err) { _runtimeLogger.debug('vnet closeAllServers close failed', err); }
4008
4018
  }
4009
4019
  servers.clear();
4010
4020
  }
@@ -5084,7 +5094,9 @@ function __initVirtualRuntime(rootScope) {
5084
5094
  try {
5085
5095
  const pkgJson = JSON.parse(content);
5086
5096
  for (const dep of Object.keys(pkgJson.dependencies || {})) addSpec(dep);
5087
- } catch (_) {}
5097
+ } catch (err) {
5098
+ _runtimeLogger.debug('preloadNpmPackages invalid package.json', err);
5099
+ }
5088
5100
  continue;
5089
5101
  }
5090
5102
  const reqRe = /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
@@ -5113,7 +5125,9 @@ function __initVirtualRuntime(rootScope) {
5113
5125
  const meta = await res.json();
5114
5126
  deps = Object.keys((meta && meta.dependencies) || {});
5115
5127
  }
5116
- } catch (_) {}
5128
+ } catch (err) {
5129
+ _runtimeLogger.debug('preloadNpmPackages metadata fetch failed', { pkg, err });
5130
+ }
5117
5131
  _npmMetadataCache.set(pkg, deps);
5118
5132
  }));
5119
5133
  for (const pkg of pending) {
@@ -5131,7 +5145,7 @@ function __initVirtualRuntime(rootScope) {
5131
5145
  continue;
5132
5146
  }
5133
5147
  if (typeof onProgress === 'function') {
5134
- try { onProgress(pkg); } catch (_) {}
5148
+ try { onProgress(pkg); } catch (err) { _runtimeLogger.debug('preloadNpmPackages onProgress callback failed', err); }
5135
5149
  }
5136
5150
  if (typeof fetch === 'function') {
5137
5151
  try {
@@ -5141,7 +5155,9 @@ function __initVirtualRuntime(rootScope) {
5141
5155
  if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
5142
5156
  loaded[pkg] = text;
5143
5157
  }
5144
- } catch (_) {}
5158
+ } catch (err) {
5159
+ _runtimeLogger.debug('preloadNpmPackages package fetch failed', { pkg, err });
5160
+ }
5145
5161
  }
5146
5162
  }
5147
5163
  return loaded;
@@ -5333,7 +5349,9 @@ function __initVirtualRuntime(rootScope) {
5333
5349
  const dir = VirtualPath.dirname(abs);
5334
5350
  if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
5335
5351
  vfs.writeFileSync(abs, content);
5336
- } catch (_) {}
5352
+ } catch (err) {
5353
+ _runtimeLogger.warn('vfs initial file seed failed', { abs, err });
5354
+ }
5337
5355
  }
5338
5356
  }
5339
5357
  const vhttp = createVirtualHttp(resourceTracker, activePortTable);
@@ -5778,7 +5796,7 @@ function __initVirtualRuntime(rootScope) {
5778
5796
  exitCode = Number(code) || 0;
5779
5797
  if (!hasExited) {
5780
5798
  hasExited = true;
5781
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
5799
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('process exit listener threw', err); }
5782
5800
  }
5783
5801
  if (syncExecDepth > 0) {
5784
5802
  throw new ProcessExitSignal(exitCode);
@@ -5811,8 +5829,8 @@ function __initVirtualRuntime(rootScope) {
5811
5829
  resourceTracker.inFlightHttp.clear();
5812
5830
 
5813
5831
  if (!isBackground) {
5814
- try { vhttp.closeAllServers(); } catch (_) {}
5815
- try { vnet.closeAllServers(); } catch (_) {}
5832
+ try { vhttp.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vhttp closeAllServers failed', err); }
5833
+ try { vnet.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vnet closeAllServers failed', err); }
5816
5834
  }
5817
5835
  };
5818
5836
 
@@ -5922,10 +5940,10 @@ function __initVirtualRuntime(rootScope) {
5922
5940
  sandboxConsole.log(`✗ ${fullName}\n ${e && e.stack ? e.stack : e}`);
5923
5941
  } finally {
5924
5942
  for (const ae of hooksSnapshot.afterEachList) {
5925
- try { await ae(); } catch (_) {}
5943
+ try { await ae(); } catch (err) { _runtimeLogger.debug('node:test afterEach hook failed', err); }
5926
5944
  }
5927
5945
  for (const af of hooksSnapshot.afterToRun) {
5928
- try { await af(); } catch (_) {}
5946
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test after hook failed', err); }
5929
5947
  }
5930
5948
  hooksSnapshot.afterToRun.length = 0;
5931
5949
  }
@@ -5973,7 +5991,7 @@ function __initVirtualRuntime(rootScope) {
5973
5991
  const afters = [...suiteCtx.afterCallbacks];
5974
5992
  const cleanupTask = nodeTestChain.then(async () => {
5975
5993
  for (const af of afters) {
5976
- try { await af(); } catch (_) {}
5994
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test suite after hook failed', err); }
5977
5995
  }
5978
5996
  });
5979
5997
  nodeTestChain = cleanupTask.catch(() => {});
@@ -6019,7 +6037,7 @@ function __initVirtualRuntime(rootScope) {
6019
6037
  getEntriesByName: (n, t) => (entry.name === n && (!t || entry.entryType === t) ? [entry] : []),
6020
6038
  getEntriesByType: (t) => (entry.entryType === t ? [entry] : [])
6021
6039
  };
6022
- try { obs._cb(list, obs); } catch (_) {}
6040
+ try { obs._cb(list, obs); } catch (err) { _runtimeLogger.debug('PerformanceObserver callback failed', err); }
6023
6041
  }
6024
6042
  }
6025
6043
  }
@@ -6124,7 +6142,7 @@ function __initVirtualRuntime(rootScope) {
6124
6142
  getEntriesByName: (n, t) => buffered.filter((e) => e.name === n && (!t || e.entryType === t)),
6125
6143
  getEntriesByType: (t) => buffered.filter((e) => e.entryType === t)
6126
6144
  };
6127
- queueMicrotask(() => { try { this._cb(list, this); } catch (_) {} });
6145
+ queueMicrotask(() => { try { this._cb(list, this); } catch (err) { _runtimeLogger.debug('PerformanceObserver buffered callback failed', err); } });
6128
6146
  }
6129
6147
  }
6130
6148
  }
@@ -7395,7 +7413,9 @@ function __initVirtualRuntime(rootScope) {
7395
7413
  const resolvedEntry = resolveFileOrDirCandidates(VirtualPath.resolve(base, entryRel));
7396
7414
  if (resolvedEntry) return resolvedEntry;
7397
7415
  }
7398
- } catch (_) {}
7416
+ } catch (err) {
7417
+ _runtimeLogger.debug('resolveFileOrDirCandidates package.json parse failed', err);
7418
+ }
7399
7419
  }
7400
7420
  const indexCandidates = ['index.js', 'index.ts', 'index.mjs', 'index.cjs', 'index.json'];
7401
7421
  for (const idx of indexCandidates) {
@@ -7465,7 +7485,9 @@ function __initVirtualRuntime(rootScope) {
7465
7485
  if (found) return found;
7466
7486
  }
7467
7487
  }
7468
- } catch (_) {}
7488
+ } catch (err) {
7489
+ _runtimeLogger.debug('resolveModulePath subpath package.json parse failed', err);
7490
+ }
7469
7491
  }
7470
7492
  const foundSub = resolveFileOrDirCandidates(VirtualPath.join(pkgRoot, subpath));
7471
7493
  if (foundSub) return foundSub;
@@ -7507,7 +7529,9 @@ function __initVirtualRuntime(rootScope) {
7507
7529
  if (isLocal && activePortTable) {
7508
7530
  return await activePortTable.dispatchRequest(urlStr, finalInit);
7509
7531
  }
7510
- } catch (_) {}
7532
+ } catch (err) {
7533
+ _runtimeLogger.debug('virtualFetch local URL dispatch skipped', err);
7534
+ }
7511
7535
 
7512
7536
  if (typeof globalThis.fetch === 'function') {
7513
7537
  return await globalThis.fetch(urlOrReq, init);
@@ -7674,7 +7698,9 @@ function __initVirtualRuntime(rootScope) {
7674
7698
  if (err instanceof SyntaxError && (/\bawait\b/.test(body) || /await/i.test(err.message))) {
7675
7699
  try {
7676
7700
  return new AsyncFunction(...argNames, body);
7677
- } catch (_) {}
7701
+ } catch (asyncErr) {
7702
+ _runtimeLogger.debug('AsyncFunction compilation fallback failed', asyncErr);
7703
+ }
7678
7704
  }
7679
7705
  if (
7680
7706
  err &&
@@ -7728,7 +7754,9 @@ function __initVirtualRuntime(rootScope) {
7728
7754
  if (signal && onAbort) {
7729
7755
  try {
7730
7756
  signal.removeEventListener('abort', onAbort);
7731
- } catch (_) {}
7757
+ } catch (err) {
7758
+ _runtimeLogger.debug('raceWithAbort removeEventListener failed', err);
7759
+ }
7732
7760
  }
7733
7761
  };
7734
7762
 
@@ -7887,11 +7915,11 @@ function __initVirtualRuntime(rootScope) {
7887
7915
  }
7888
7916
  } finally {
7889
7917
  if (signal && signalListener) {
7890
- try { signal.removeEventListener('abort', signalListener); } catch (_) {}
7918
+ try { signal.removeEventListener('abort', signalListener); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime removeEventListener failed', err); }
7891
7919
  }
7892
7920
  if (!hasExited) {
7893
7921
  hasExited = true;
7894
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
7922
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime exit listener failed', err); }
7895
7923
  }
7896
7924
  for (const rawId of resourceTracker.allTimers) {
7897
7925
  clearTimeout(rawId);
@@ -7999,7 +8027,16 @@ function createWorkerRuntimeSource() {
7999
8027
  return `'use strict';\nself.__virtualRuntime = (${__initVirtualRuntime.toString()})(self);\n(${__workerMessageLoop.toString()})(self);\n`;
8000
8028
  }
8001
8029
 
8002
- const _hostRuntime = __initVirtualRuntime(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global));
8030
+ const _hostScope = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global);
8031
+ const _hostLogger = (_hostScope && _hostScope.CodeLabLogger && typeof _hostScope.CodeLabLogger.createLogger === 'function')
8032
+ ? _hostScope.CodeLabLogger.createLogger()
8033
+ : {
8034
+ debug() {},
8035
+ info() {},
8036
+ warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
8037
+ error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
8038
+ };
8039
+ const _hostRuntime = __initVirtualRuntime(_hostScope);
8003
8040
  _hostRuntime.createWorkerRuntimeSource = createWorkerRuntimeSource;
8004
8041
 
8005
8042
  let _cachedWorkerUrl = null;
@@ -8023,7 +8060,7 @@ function _ensureWarmWorker() {
8023
8060
 
8024
8061
  function _destroyWarmWorker() {
8025
8062
  if (_warmWorker) {
8026
- try { _warmWorker.terminate(); } catch (_) {}
8063
+ try { _warmWorker.terminate(); } catch (err) { _hostLogger.debug('warmWorker.terminate failed', err); }
8027
8064
  _warmWorker = null;
8028
8065
  }
8029
8066
  _warmWorkerBusy = false;
@@ -8078,7 +8115,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8078
8115
 
8079
8116
  function releaseWorker(terminateWorker) {
8080
8117
  if (options.signal && abortListener) {
8081
- try { options.signal.removeEventListener('abort', abortListener); } catch (_) {}
8118
+ try { options.signal.removeEventListener('abort', abortListener); } catch (err) { _hostLogger.debug('executeInWorker removeEventListener failed', err); }
8082
8119
  abortListener = null;
8083
8120
  }
8084
8121
  _activeWorkerJobs.delete(requestId);
@@ -8093,7 +8130,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8093
8130
  }
8094
8131
  }
8095
8132
  } else {
8096
- try { worker.terminate(); } catch (_) {}
8133
+ try { worker.terminate(); } catch (err) { _hostLogger.debug('worker.terminate failed', err); }
8097
8134
  }
8098
8135
  }
8099
8136
 
package/src/schemas.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
 
3
3
  /**
4
- * Zod Schemas and Inferred TypeScript Types for code-lab v0.1.7
4
+ * Zod Schemas and Inferred TypeScript Types for code-lab v0.1.9
5
5
  */
6
6
 
7
7
  // ── 1. Guided Step ──────────────────────────────────────────────────────────
@@ -178,3 +178,93 @@ export const WorkbenchOptionsSchema = z.object({
178
178
  });
179
179
 
180
180
  export type WorkbenchOptions = z.infer<typeof WorkbenchOptionsSchema>;
181
+
182
+ // ── 8. Search Options & Match Results ────────────────────────────────────────
183
+
184
+ export const SearchOptionsSchema = z.object({
185
+ query: z.string().default(''),
186
+ caseSensitive: z.boolean().optional().default(false),
187
+ wholeWord: z.boolean().optional().default(false),
188
+ regex: z.boolean().optional().default(false),
189
+ isRegex: z.boolean().optional().default(false),
190
+ include: z.string().optional(),
191
+ includeGlob: z.string().optional(),
192
+ includePattern: z.union([z.string(), z.array(z.string())]).optional(),
193
+ exclude: z.string().optional(),
194
+ excludeGlob: z.string().optional(),
195
+ excludePattern: z.union([z.string(), z.array(z.string())]).optional(),
196
+ maxMatches: z.number().int().positive().optional(),
197
+ maxMatchesPerFile: z.number().int().positive().optional()
198
+ });
199
+
200
+ export type SearchOptions = z.infer<typeof SearchOptionsSchema>;
201
+
202
+ // ── 9. Diagnostic Item & Problems ───────────────────────────────────────────
203
+
204
+ export const DiagnosticSeveritySchema = z.enum(['error', 'warning', 'info', 'hint']);
205
+ export type DiagnosticSeverity = z.infer<typeof DiagnosticSeveritySchema>;
206
+
207
+ export const DiagnosticItemSchema = z.object({
208
+ id: z.string(),
209
+ file: z.string(),
210
+ line: z.number().int(),
211
+ col: z.number().int().optional(),
212
+ column: z.number().int().optional(),
213
+ endLine: z.number().int().optional(),
214
+ endCol: z.number().int().optional(),
215
+ endColumn: z.number().int().optional(),
216
+ message: z.string(),
217
+ severity: DiagnosticSeveritySchema,
218
+ source: z.string().optional(),
219
+ code: z.union([z.string(), z.number()]).optional(),
220
+ tags: z.array(z.string()).optional()
221
+ });
222
+
223
+ export type DiagnosticItem = z.infer<typeof DiagnosticItemSchema>;
224
+
225
+ // ── 10. Stored Project ──────────────────────────────────────────────────────
226
+
227
+ export const StoredProjectSchema = z.object({
228
+ id: z.string(),
229
+ name: z.string(),
230
+ files: z.record(z.string()),
231
+ updatedAt: z.number(),
232
+ createdAt: z.number().optional(),
233
+ entry: z.string().optional(),
234
+ testEntry: z.string().optional(),
235
+ version: z.number().optional()
236
+ });
237
+
238
+ export type StoredProject = z.infer<typeof StoredProjectSchema>;
239
+
240
+ // ── 11. Git File Status & SCM Summary ───────────────────────────────────────
241
+
242
+ export const GitFileChangeTypeSchema = z.enum(['modified', 'added', 'deleted', 'untracked']);
243
+ export type GitFileChangeType = z.infer<typeof GitFileChangeTypeSchema>;
244
+
245
+ export const GitFileStatusSchema = z.object({
246
+ path: z.string(),
247
+ status: GitFileChangeTypeSchema,
248
+ staged: z.boolean(),
249
+ oldContent: z.string().optional(),
250
+ newContent: z.string().optional()
251
+ });
252
+
253
+ export type GitFileStatus = z.infer<typeof GitFileStatusSchema>;
254
+
255
+ export const GitStateSummarySchema = z.object({
256
+ branch: z.string().default('main'),
257
+ headCommit: z.string().optional(),
258
+ branches: z.array(z.string()).default(['main']),
259
+ staged: z.array(GitFileStatusSchema).default([]),
260
+ unstaged: z.array(GitFileStatusSchema).default([]),
261
+ untracked: z.array(GitFileStatusSchema).default([]),
262
+ modified: z.array(GitFileStatusSchema).optional(),
263
+ deleted: z.array(GitFileStatusSchema).optional(),
264
+ hasChanges: z.boolean().default(false),
265
+ isClean: z.boolean().default(true),
266
+ ahead: z.number().int().default(0),
267
+ behind: z.number().int().default(0)
268
+ });
269
+
270
+ export type GitStateSummary = z.infer<typeof GitStateSummarySchema>;
package/src/scm.ts ADDED
@@ -0,0 +1,268 @@
1
+ /**
2
+ * @innovatorved/code-lab — Interactive Git Source Control (SCM) Engine
3
+ * ============================================================================
4
+ * Pure TypeScript in-browser Git status, staging, unstaging, and commit engine
5
+ * backed by workspace VFS state. Powers both the interactive Source Control UI
6
+ * and shell/CLI Git operations.
7
+ *
8
+ * Strict leaf module: fully typed, zero explicit any, zero empty catches.
9
+ */
10
+
11
+ export type GitFileChangeType = 'modified' | 'added' | 'deleted' | 'untracked';
12
+
13
+ export interface GitFileStatus {
14
+ path: string;
15
+ status: GitFileChangeType;
16
+ staged: boolean;
17
+ oldContent?: string;
18
+ newContent?: string;
19
+ }
20
+
21
+ export interface GitCommitRecord {
22
+ hash: string;
23
+ message: string;
24
+ timestamp: number;
25
+ author?: string;
26
+ files: Record<string, string>;
27
+ }
28
+
29
+ export interface GitState {
30
+ branch: string;
31
+ branches?: string[];
32
+ headCommit: string;
33
+ headFiles: Record<string, string>;
34
+ staged: Map<string, string | null>;
35
+ commits: GitCommitRecord[];
36
+ }
37
+
38
+ export interface GitStatusResult {
39
+ branch: string;
40
+ headCommit: string;
41
+ untracked: GitFileStatus[];
42
+ modified: GitFileStatus[];
43
+ deleted: GitFileStatus[];
44
+ staged: GitFileStatus[];
45
+ unstaged: GitFileStatus[];
46
+ hasChanges: boolean;
47
+ isClean: boolean;
48
+ }
49
+
50
+ /**
51
+ * Computes a deterministic 7-character short hash for a commit payload.
52
+ */
53
+ export function computeShortCommitHash(input: string): string {
54
+ let h1 = 0xdeadbeef ^ input.length;
55
+ let h2 = 0x41c6ce57 ^ input.length;
56
+ for (let i = 0; i < input.length; i++) {
57
+ const ch = input.charCodeAt(i);
58
+ h1 = Math.imul(h1 ^ ch, 2654435761);
59
+ h2 = Math.imul(h2 ^ ch, 1597334677);
60
+ }
61
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
62
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
63
+ const combined = 4294967296 * (2097151 & h2) + (h1 >>> 0);
64
+ return combined.toString(16).padStart(7, '0').slice(0, 7);
65
+ }
66
+
67
+ /**
68
+ * Initializes a fresh in-memory Git repository state from initial VFS files.
69
+ */
70
+ export function createGitState(
71
+ initialFiles: Record<string, string> = {},
72
+ branch = 'main'
73
+ ): GitState {
74
+ const headFiles: Record<string, string> = { ...initialFiles };
75
+ const initialHash = computeShortCommitHash(JSON.stringify(headFiles) + ':init');
76
+ return {
77
+ branch,
78
+ branches: [branch],
79
+ headCommit: initialHash,
80
+ headFiles,
81
+ staged: new Map<string, string | null>(),
82
+ commits: [
83
+ {
84
+ hash: initialHash,
85
+ message: 'Initial commit',
86
+ timestamp: Date.now(),
87
+ files: { ...headFiles }
88
+ }
89
+ ]
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Computes working-tree and staging-area Git status against `gitState`.
95
+ */
96
+ export function computeGitStatus(
97
+ vfsFiles: Record<string, string>,
98
+ _repoRoot = '/workspace',
99
+ gitState?: GitState
100
+ ): GitStatusResult {
101
+ const state = gitState || createGitState({});
102
+ const headFiles = state.headFiles || {};
103
+ const currentStaged = state.staged instanceof Map ? state.staged : new Map<string, string | null>();
104
+
105
+ const untracked: GitFileStatus[] = [];
106
+ const modified: GitFileStatus[] = [];
107
+ const deleted: GitFileStatus[] = [];
108
+ const staged: GitFileStatus[] = [];
109
+
110
+ for (const [filePath, stagedContent] of currentStaged.entries()) {
111
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, filePath);
112
+ if (stagedContent === null) {
113
+ staged.push({
114
+ path: filePath,
115
+ status: 'deleted',
116
+ staged: true,
117
+ oldContent: headFiles[filePath]
118
+ });
119
+ } else {
120
+ staged.push({
121
+ path: filePath,
122
+ status: inHead ? 'modified' : 'added',
123
+ staged: true,
124
+ oldContent: inHead ? headFiles[filePath] : undefined,
125
+ newContent: stagedContent
126
+ });
127
+ }
128
+ }
129
+
130
+ for (const [filePath, content] of Object.entries(vfsFiles || {})) {
131
+ if (currentStaged.has(filePath)) {
132
+ const stagedVal = currentStaged.get(filePath);
133
+ if (stagedVal !== content) {
134
+ modified.push({
135
+ path: filePath,
136
+ status: 'modified',
137
+ staged: false,
138
+ oldContent: stagedVal ?? undefined,
139
+ newContent: content
140
+ });
141
+ }
142
+ } else if (Object.prototype.hasOwnProperty.call(headFiles, filePath)) {
143
+ if (headFiles[filePath] !== content) {
144
+ modified.push({
145
+ path: filePath,
146
+ status: 'modified',
147
+ staged: false,
148
+ oldContent: headFiles[filePath],
149
+ newContent: content
150
+ });
151
+ }
152
+ } else {
153
+ untracked.push({
154
+ path: filePath,
155
+ status: 'untracked',
156
+ staged: false,
157
+ newContent: content
158
+ });
159
+ }
160
+ }
161
+
162
+ for (const filePath of Object.keys(headFiles)) {
163
+ if (
164
+ !Object.prototype.hasOwnProperty.call(vfsFiles, filePath) &&
165
+ !currentStaged.has(filePath)
166
+ ) {
167
+ deleted.push({
168
+ path: filePath,
169
+ status: 'deleted',
170
+ staged: false,
171
+ oldContent: headFiles[filePath]
172
+ });
173
+ }
174
+ }
175
+
176
+ const unstaged: GitFileStatus[] = [...modified, ...deleted];
177
+ const isClean =
178
+ untracked.length === 0 &&
179
+ modified.length === 0 &&
180
+ deleted.length === 0 &&
181
+ staged.length === 0;
182
+
183
+ return {
184
+ branch: state.branch || 'main',
185
+ headCommit: state.headCommit || '',
186
+ untracked,
187
+ modified,
188
+ deleted,
189
+ staged,
190
+ unstaged,
191
+ hasChanges: !isClean,
192
+ isClean
193
+ };
194
+ }
195
+
196
+ /**
197
+ * Stages a file addition, modification, or deletion (`currentContent === null`).
198
+ */
199
+ export function stageFile(
200
+ gitState: GitState,
201
+ relativePath: string,
202
+ currentContent: string | null
203
+ ): void {
204
+ if (!gitState) return;
205
+ if (!(gitState.staged instanceof Map)) {
206
+ gitState.staged = new Map<string, string | null>();
207
+ }
208
+ gitState.staged.set(relativePath, currentContent === undefined ? null : currentContent);
209
+ }
210
+
211
+ /**
212
+ * Removes a file from the staging index.
213
+ */
214
+ export function unstageFile(gitState: GitState, relativePath: string): void {
215
+ if (!gitState || !(gitState.staged instanceof Map)) return;
216
+ gitState.staged.delete(relativePath);
217
+ }
218
+
219
+ /**
220
+ * Commits all staged changes to `gitState`, advancing `headCommit` and `headFiles`,
221
+ * and clearing the staging area. Throws if message is empty or staging area is empty.
222
+ */
223
+ export function commitChanges(gitState: GitState, message: string): string {
224
+ const trimmed = typeof message === 'string' ? message.trim() : '';
225
+ if (!trimmed) {
226
+ throw new Error('Commit message cannot be empty');
227
+ }
228
+ if (!gitState || !(gitState.staged instanceof Map) || gitState.staged.size === 0) {
229
+ throw new Error('Nothing to commit (staging area is empty)');
230
+ }
231
+
232
+ const newHeadFiles: Record<string, string> = { ...(gitState.headFiles || {}) };
233
+ for (const [filePath, content] of gitState.staged.entries()) {
234
+ if (content === null) {
235
+ delete newHeadFiles[filePath];
236
+ } else {
237
+ newHeadFiles[filePath] = content;
238
+ }
239
+ }
240
+
241
+ const timestamp = Date.now();
242
+ const hash = computeShortCommitHash(`${gitState.headCommit}:${trimmed}:${timestamp}`);
243
+ const commit: GitCommitRecord = {
244
+ hash,
245
+ message: trimmed,
246
+ timestamp,
247
+ files: newHeadFiles
248
+ };
249
+
250
+ if (!Array.isArray(gitState.commits)) {
251
+ gitState.commits = [];
252
+ }
253
+ gitState.commits.push(commit);
254
+ gitState.headCommit = hash;
255
+ gitState.headFiles = newHeadFiles;
256
+ gitState.staged.clear();
257
+
258
+ return hash;
259
+ }
260
+
261
+ export default {
262
+ createGitState,
263
+ computeGitStatus,
264
+ stageFile,
265
+ unstageFile,
266
+ commitChanges,
267
+ computeShortCommitHash
268
+ };