@innovatorved/code-lab 0.3.1 → 0.3.2

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 (48) hide show
  1. package/ARCHITECTURE.md +4 -2
  2. package/CHANGELOG.md +25 -0
  3. package/README.md +15 -5
  4. package/dist/code-lab.css +52 -2
  5. package/dist/code-lab.d.ts +1 -1
  6. package/dist/code-lab.esm.js +1247 -377
  7. package/dist/code-lab.js +1246 -376
  8. package/dist/diagnostics.d.ts +5 -0
  9. package/dist/extensions/cpp.esm.js +51 -9
  10. package/dist/extensions/cpp.js +51 -9
  11. package/dist/extensions/python.esm.js +116 -103
  12. package/dist/extensions/python.js +116 -103
  13. package/dist/index.d.ts +1 -1
  14. package/dist/preview-sw.js +34 -17
  15. package/dist/runtime.esm.js +38 -31
  16. package/dist/runtime.js +38 -31
  17. package/dist/schemas.d.ts +1 -1
  18. package/dist/scm.d.ts +13 -2
  19. package/dist/search.d.ts +5 -1
  20. package/dist/shell.esm.js +72 -16
  21. package/dist/shell.js +72 -16
  22. package/dist/terminal.esm.js +183 -54
  23. package/dist/terminal.js +183 -54
  24. package/dist/workbench/index.d.ts +1 -1
  25. package/dist/workbench/styles.d.ts +1 -1
  26. package/dist/zip.d.ts +4 -3
  27. package/package.json +1 -1
  28. package/src/code-lab.css +52 -2
  29. package/src/csp.ts +7 -10
  30. package/src/diagnostics.ts +42 -3
  31. package/src/extensions/cpp.ts +47 -9
  32. package/src/extensions/python.ts +128 -116
  33. package/src/index.ts +1 -1
  34. package/src/preview-sw.js +25 -5
  35. package/src/runtime.ts +36 -29
  36. package/src/schemas.ts +1 -1
  37. package/src/scm.ts +106 -19
  38. package/src/search.ts +71 -27
  39. package/src/shell.ts +70 -14
  40. package/src/terminal.ts +181 -52
  41. package/src/workbench/diff-editor.ts +41 -13
  42. package/src/workbench/drawer.ts +17 -4
  43. package/src/workbench/guided-pane.ts +12 -2
  44. package/src/workbench/share.ts +37 -8
  45. package/src/workbench/styles.ts +2 -1
  46. package/src/workbench/toolbar.ts +15 -4
  47. package/src/workbench.ts +482 -79
  48. package/src/zip.ts +29 -7
package/src/runtime.ts CHANGED
@@ -1015,22 +1015,40 @@ function __initVirtualRuntime(rootScope) {
1015
1015
  // =========================================================================
1016
1016
  // 5. VIRTUAL IN-MEMORY POSIX FILESYSTEM (node:fs)
1017
1017
  // =========================================================================
1018
- function createVirtualFs(initialFiles = {}) {
1018
+ function createVirtualFs(initialFiles = {}, vfsOptions = {}) {
1019
1019
  const dirs = new Set(['/', '/tmp', '/workspace', '/home', '/home/user']);
1020
1020
  const files = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, ctimeMs, ino }
1021
1021
  const deletedInspectorCache = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, deletedAtMs }
1022
+ const MAX_DELETED_CACHE_ENTRIES = 50;
1023
+ const MAX_DELETED_CACHE_FILE_BYTES = 65536;
1024
+ const customCwdGetter = typeof vfsOptions === 'function'
1025
+ ? vfsOptions
1026
+ : (vfsOptions && typeof vfsOptions.cwdGetter === 'function' ? vfsOptions.cwdGetter : null);
1022
1027
  const fdTable = new Map(); // fd -> { inode, path, flags, pos, isDirectory }
1023
1028
  let nextFd = 10;
1024
1029
  let nextIno = 100;
1025
1030
  let mkdtempCounter = 1;
1026
1031
 
1032
+ function recordDeletedForInspector(p, data, mtimeMs) {
1033
+ if (!data || data.byteLength <= 0 || data.byteLength > MAX_DELETED_CACHE_FILE_BYTES) return;
1034
+ if (deletedInspectorCache.has(p)) {
1035
+ deletedInspectorCache.delete(p);
1036
+ } else if (deletedInspectorCache.size >= MAX_DELETED_CACHE_ENTRIES) {
1037
+ const oldestKey = deletedInspectorCache.keys().next().value;
1038
+ if (oldestKey !== undefined) deletedInspectorCache.delete(oldestKey);
1039
+ }
1040
+ deletedInspectorCache.set(p, { data: data.slice(), mtimeMs, deletedAtMs: Date.now() });
1041
+ }
1042
+
1027
1043
  function normPath(p) {
1028
1044
  if (typeof p !== 'string' || !p) {
1029
1045
  const err = new TypeError('path must be a non-empty string');
1030
1046
  err.code = 'ERR_INVALID_ARG_TYPE';
1031
1047
  throw err;
1032
1048
  }
1033
- const baseCwd = typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace';
1049
+ const baseCwd = typeof customCwdGetter === 'function'
1050
+ ? customCwdGetter()
1051
+ : (typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace');
1034
1052
  const abs = p.startsWith('/') ? VirtualPath.normalize(p) : VirtualPath.resolve(baseCwd, p);
1035
1053
  return abs.length > 1 && abs.endsWith('/') ? abs.slice(0, -1) : abs;
1036
1054
  }
@@ -1081,9 +1099,13 @@ function __initVirtualRuntime(rootScope) {
1081
1099
  for (const [relPath, content] of Object.entries(initialFiles)) {
1082
1100
  const cleanRel = relPath.startsWith('/') ? relPath.slice(1) : relPath;
1083
1101
  const isSystemPath = /^\/(workspace|usr|tmp|lib|include|etc|bin|dev)(\/|$)/.test(relPath);
1084
- const fullPath = isSystemPath
1102
+ let fullPath = isSystemPath
1085
1103
  ? normPath(relPath)
1086
1104
  : normPath(`/workspace/${cleanRel}`);
1105
+ if (!isSystemPath && fullPath !== '/workspace' && !fullPath.startsWith('/workspace/')) {
1106
+ const safeSub = cleanRel.split('/').filter((seg) => seg && seg !== '.' && seg !== '..').join('/');
1107
+ fullPath = normPath(`/workspace/${safeSub || 'file'}`);
1108
+ }
1087
1109
  ensureParentDirs(fullPath);
1088
1110
  const bytes = typeof content === 'string' ? utf8Encode(content) : new Uint8Array(content);
1089
1111
  files.set(fullPath, {
@@ -1263,13 +1285,6 @@ function __initVirtualRuntime(rootScope) {
1263
1285
  fsyncSync(fd) {
1264
1286
  const entry = fdTable.get(fd);
1265
1287
  if (!entry) throw fsError('EBADF', 'fsync', String(fd), 'bad file descriptor');
1266
- if (!entry.isDirectory && entry.inode) {
1267
- deletedInspectorCache.set(entry.path, {
1268
- data: entry.inode.data.slice(),
1269
- mtimeMs: entry.inode.mtimeMs,
1270
- deletedAtMs: null
1271
- });
1272
- }
1273
1288
  },
1274
1289
 
1275
1290
  fdatasyncSync(fd) {
@@ -1310,12 +1325,6 @@ function __initVirtualRuntime(rootScope) {
1310
1325
  inode.mtimeMs = Date.now();
1311
1326
  entry.pos = writePos + chunk.byteLength;
1312
1327
 
1313
- deletedInspectorCache.set(entry.path, {
1314
- data: inode.data.slice(),
1315
- mtimeMs: inode.mtimeMs,
1316
- deletedAtMs: null
1317
- });
1318
-
1319
1328
  return chunk.byteLength;
1320
1329
  },
1321
1330
 
@@ -1367,7 +1376,7 @@ function __initVirtualRuntime(rootScope) {
1367
1376
  inode.mode = 0o100000 | (Number(opts.mode) & 0o777);
1368
1377
  }
1369
1378
  }
1370
- deletedInspectorCache.set(np, { data: bytes.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1379
+ deletedInspectorCache.delete(np);
1371
1380
  },
1372
1381
 
1373
1382
  chmodSync(p, mode) {
@@ -1396,7 +1405,7 @@ function __initVirtualRuntime(rootScope) {
1396
1405
  combined.set(chunk, inode.data.byteLength);
1397
1406
  inode.data = combined;
1398
1407
  inode.mtimeMs = Date.now();
1399
- deletedInspectorCache.set(np, { data: combined.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1408
+ deletedInspectorCache.delete(np);
1400
1409
  },
1401
1410
 
1402
1411
  truncateSync(p, len = 0) {
@@ -1412,7 +1421,6 @@ function __initVirtualRuntime(rootScope) {
1412
1421
  inode.data = grown;
1413
1422
  }
1414
1423
  inode.mtimeMs = Date.now();
1415
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1416
1424
  },
1417
1425
 
1418
1426
  renameSync(oldP, newP) {
@@ -1473,16 +1481,14 @@ function __initVirtualRuntime(rootScope) {
1473
1481
  if (fdEntry.path === src) fdEntry.path = dst;
1474
1482
  }
1475
1483
  deletedInspectorCache.delete(src);
1476
- deletedInspectorCache.set(dst, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1484
+ deletedInspectorCache.delete(dst);
1477
1485
  },
1478
1486
 
1479
1487
  unlinkSync(p) {
1480
1488
  const np = normPath(p);
1481
1489
  const inode = files.get(np);
1482
1490
  if (!inode) throw fsError('ENOENT', 'unlink', p, 'no such file or directory');
1483
- if (inode.data.byteLength > 0) {
1484
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
1485
- }
1491
+ recordDeletedForInspector(np, inode.data, inode.mtimeMs);
1486
1492
  files.delete(np);
1487
1493
  },
1488
1494
 
@@ -1499,9 +1505,7 @@ function __initVirtualRuntime(rootScope) {
1499
1505
  for (const [fPath, inode] of Array.from(files.entries())) {
1500
1506
  if (fPath.startsWith(prefix)) {
1501
1507
  if (!recursive) throw fsError('ENOTEMPTY', 'rm', p, 'directory not empty');
1502
- if (inode.data.byteLength > 0) {
1503
- deletedInspectorCache.set(fPath, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
1504
- }
1508
+ recordDeletedForInspector(fPath, inode.data, inode.mtimeMs);
1505
1509
  files.delete(fPath);
1506
1510
  }
1507
1511
  }
@@ -3075,6 +3079,7 @@ function __initVirtualRuntime(rootScope) {
3075
3079
  responseHeaders: {},
3076
3080
  _t0: performance.now()
3077
3081
  };
3082
+ if (httpTrace.length >= 500) httpTrace.shift();
3078
3083
  httpTrace.push(traceEntry);
3079
3084
  this._traceEntry = traceEntry;
3080
3085
 
@@ -4066,6 +4071,7 @@ function __initVirtualRuntime(rootScope) {
4066
4071
  this._peer = serverSocket;
4067
4072
  this.connecting = false;
4068
4073
 
4074
+ if (sharedTrace.length >= 500) sharedTrace.shift();
4069
4075
  sharedTrace.push({
4070
4076
  protocol: 'TCP',
4071
4077
  event: 'connect',
@@ -6358,7 +6364,10 @@ function __initVirtualRuntime(rootScope) {
6358
6364
  const activePortTable = optPortTable || portTable || _defaultPortTable;
6359
6365
  resourceTracker.pid = pid;
6360
6366
 
6361
- const vfs = optVfs || createVirtualFs(files);
6367
+ let currentCwd = '/workspace';
6368
+ _activeCwdGetter = () => currentCwd;
6369
+
6370
+ const vfs = optVfs || createVirtualFs(files, { cwdGetter: () => currentCwd });
6362
6371
  if (optVfs && files && typeof files === 'object') {
6363
6372
  for (const [fPath, content] of Object.entries(files)) {
6364
6373
  const abs = fPath.startsWith('/') ? fPath : '/workspace/' + fPath;
@@ -6752,8 +6761,6 @@ function __initVirtualRuntime(rootScope) {
6752
6761
  hrtimeFn.bigint = () => BigInt(Math.round(performance.now() * 1e6));
6753
6762
 
6754
6763
  let syncExecDepth = 0;
6755
- let currentCwd = '/workspace';
6756
- _activeCwdGetter = () => currentCwd;
6757
6764
 
6758
6765
  const sandboxProcess = Object.assign(new EventEmitter(), {
6759
6766
  env: { NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' },
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.2.0
4
+ * Zod Schemas and Inferred TypeScript Types for code-lab v0.3.2
5
5
  */
6
6
 
7
7
  // ── 1. Guided Step ──────────────────────────────────────────────────────────
package/src/scm.ts CHANGED
@@ -31,10 +31,19 @@ export interface GitState {
31
31
  branches?: string[];
32
32
  headCommit: string;
33
33
  headFiles: Record<string, string>;
34
- staged: Map<string, string | null>;
34
+ headSnapshot?: Record<string, string>;
35
+ staged: Map<string, string | null> | Set<string>;
35
36
  commits: GitCommitRecord[];
36
37
  }
37
38
 
39
+ export interface GitStatusEntry {
40
+ path: string;
41
+ status: GitFileChangeType;
42
+ staged: boolean;
43
+ index: string;
44
+ worktree: string;
45
+ }
46
+
38
47
  export interface GitStatusResult {
39
48
  branch: string;
40
49
  headCommit: string;
@@ -43,6 +52,7 @@ export interface GitStatusResult {
43
52
  deleted: GitFileStatus[];
44
53
  staged: GitFileStatus[];
45
54
  unstaged: GitFileStatus[];
55
+ entries: GitStatusEntry[];
46
56
  hasChanges: boolean;
47
57
  isClean: boolean;
48
58
  }
@@ -92,15 +102,41 @@ export function createGitState(
92
102
 
93
103
  /**
94
104
  * Computes working-tree and staging-area Git status against `gitState`.
105
+ * Supports both `computeGitStatus(vfsFiles, repoRoot, gitState)` and
106
+ * `computeGitStatus(gitState, vfsFiles)` calling conventions.
95
107
  */
96
108
  export function computeGitStatus(
97
- vfsFiles: Record<string, string>,
98
- _repoRoot = '/workspace',
109
+ arg1: Record<string, string> | GitState,
110
+ arg2: string | Record<string, string> = '/workspace',
99
111
  gitState?: GitState
100
112
  ): 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>();
113
+ let vfsFiles: Record<string, string>;
114
+ let state: GitState;
115
+
116
+ if (
117
+ arg1 &&
118
+ typeof arg1 === 'object' &&
119
+ ('headFiles' in arg1 || 'headSnapshot' in arg1 || 'staged' in arg1 || 'commits' in arg1)
120
+ ) {
121
+ state = arg1 as GitState;
122
+ vfsFiles = (arg2 && typeof arg2 === 'object' ? arg2 : {}) as Record<string, string>;
123
+ } else {
124
+ vfsFiles = (arg1 && typeof arg1 === 'object' ? arg1 : {}) as Record<string, string>;
125
+ state = gitState || createGitState({});
126
+ }
127
+
128
+ const headFiles: Record<string, string> = state.headFiles || state.headSnapshot || {};
129
+ const currentStaged = new Map<string, string | null>();
130
+ if (state.staged instanceof Map) {
131
+ for (const [k, v] of state.staged.entries()) {
132
+ currentStaged.set(k, v);
133
+ }
134
+ } else if (state.staged instanceof Set) {
135
+ for (const k of state.staged.values()) {
136
+ const existsInVfs = Object.prototype.hasOwnProperty.call(vfsFiles, k);
137
+ currentStaged.set(k, existsInVfs ? vfsFiles[k] : null);
138
+ }
139
+ }
104
140
 
105
141
  const untracked: GitFileStatus[] = [];
106
142
  const modified: GitFileStatus[] = [];
@@ -110,12 +146,14 @@ export function computeGitStatus(
110
146
  for (const [filePath, stagedContent] of currentStaged.entries()) {
111
147
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, filePath);
112
148
  if (stagedContent === null) {
113
- staged.push({
114
- path: filePath,
115
- status: 'deleted',
116
- staged: true,
117
- oldContent: headFiles[filePath]
118
- });
149
+ if (inHead) {
150
+ staged.push({
151
+ path: filePath,
152
+ status: 'deleted',
153
+ staged: true,
154
+ oldContent: headFiles[filePath]
155
+ });
156
+ }
119
157
  } else {
120
158
  staged.push({
121
159
  path: filePath,
@@ -174,6 +212,36 @@ export function computeGitStatus(
174
212
  }
175
213
 
176
214
  const unstaged: GitFileStatus[] = [...modified, ...deleted];
215
+ const entries: GitStatusEntry[] = [
216
+ ...staged.map((s) => ({
217
+ path: s.path,
218
+ status: s.status,
219
+ staged: true,
220
+ index: s.status === 'added' ? 'A' : s.status === 'deleted' ? 'D' : 'M',
221
+ worktree: ' '
222
+ })),
223
+ ...modified.map((m) => ({
224
+ path: m.path,
225
+ status: m.status,
226
+ staged: false,
227
+ index: ' ',
228
+ worktree: 'M'
229
+ })),
230
+ ...deleted.map((d) => ({
231
+ path: d.path,
232
+ status: d.status,
233
+ staged: false,
234
+ index: ' ',
235
+ worktree: 'D'
236
+ })),
237
+ ...untracked.map((u) => ({
238
+ path: u.path,
239
+ status: u.status,
240
+ staged: false,
241
+ index: '?',
242
+ worktree: '?'
243
+ }))
244
+ ];
177
245
  const isClean =
178
246
  untracked.length === 0 &&
179
247
  modified.length === 0 &&
@@ -188,6 +256,7 @@ export function computeGitStatus(
188
256
  deleted,
189
257
  staged,
190
258
  unstaged,
259
+ entries,
191
260
  hasChanges: !isClean,
192
261
  isClean
193
262
  };
@@ -205,15 +274,28 @@ export function stageFile(
205
274
  if (!(gitState.staged instanceof Map)) {
206
275
  gitState.staged = new Map<string, string | null>();
207
276
  }
208
- gitState.staged.set(relativePath, currentContent === undefined ? null : currentContent);
277
+ const normalizedContent = currentContent === undefined ? null : currentContent;
278
+ const headFiles = gitState.headFiles || gitState.headSnapshot || {};
279
+ if (
280
+ normalizedContent === null &&
281
+ !Object.prototype.hasOwnProperty.call(headFiles, relativePath) &&
282
+ !gitState.staged.has(relativePath)
283
+ ) {
284
+ return;
285
+ }
286
+ gitState.staged.set(relativePath, normalizedContent);
209
287
  }
210
288
 
211
289
  /**
212
290
  * Removes a file from the staging index.
213
291
  */
214
292
  export function unstageFile(gitState: GitState, relativePath: string): void {
215
- if (!gitState || !(gitState.staged instanceof Map)) return;
216
- gitState.staged.delete(relativePath);
293
+ if (!gitState) return;
294
+ if (gitState.staged instanceof Map) {
295
+ gitState.staged.delete(relativePath);
296
+ } else if (gitState.staged instanceof Set) {
297
+ gitState.staged.delete(relativePath);
298
+ }
217
299
  }
218
300
 
219
301
  /**
@@ -229,8 +311,10 @@ export function commitChanges(gitState: GitState, message: string): string {
229
311
  throw new Error('Nothing to commit (staging area is empty)');
230
312
  }
231
313
 
232
- const newHeadFiles: Record<string, string> = { ...(gitState.headFiles || {}) };
314
+ const newHeadFiles: Record<string, string> = { ...(gitState.headFiles || gitState.headSnapshot || {}) };
315
+ const diffSummaryParts: string[] = [];
233
316
  for (const [filePath, content] of gitState.staged.entries()) {
317
+ diffSummaryParts.push(`${filePath}:${content === null ? '<DEL>' : content}`);
234
318
  if (content === null) {
235
319
  delete newHeadFiles[filePath];
236
320
  } else {
@@ -239,12 +323,15 @@ export function commitChanges(gitState: GitState, message: string): string {
239
323
  }
240
324
 
241
325
  const timestamp = Date.now();
242
- const hash = computeShortCommitHash(`${gitState.headCommit}:${trimmed}:${timestamp}`);
326
+ const commitSeq = Array.isArray(gitState.commits) ? gitState.commits.length : 0;
327
+ const hash = computeShortCommitHash(
328
+ `${gitState.headCommit}:${trimmed}:${timestamp}:${commitSeq}:${diffSummaryParts.join('|')}`
329
+ );
243
330
  const commit: GitCommitRecord = {
244
331
  hash,
245
332
  message: trimmed,
246
333
  timestamp,
247
- files: newHeadFiles
334
+ files: { ...newHeadFiles }
248
335
  };
249
336
 
250
337
  if (!Array.isArray(gitState.commits)) {
@@ -252,7 +339,7 @@ export function commitChanges(gitState: GitState, message: string): string {
252
339
  }
253
340
  gitState.commits.push(commit);
254
341
  gitState.headCommit = hash;
255
- gitState.headFiles = newHeadFiles;
342
+ gitState.headFiles = { ...newHeadFiles };
256
343
  gitState.staged.clear();
257
344
 
258
345
  return hash;
package/src/search.ts CHANGED
@@ -10,6 +10,7 @@
10
10
 
11
11
  export interface SearchOptions {
12
12
  query?: string;
13
+ replacement?: string;
13
14
  caseSensitive?: boolean;
14
15
  wholeWord?: boolean;
15
16
  regex?: boolean;
@@ -55,8 +56,10 @@ export interface SearchResult extends Array<SearchMatchGroup> {
55
56
 
56
57
  export interface ReplaceResult {
57
58
  updatedFiles: Record<string, string>;
59
+ files: Record<string, string>;
58
60
  replacedCount: number;
59
61
  filesAffected: string[];
62
+ filesModified: number;
60
63
  }
61
64
 
62
65
  /**
@@ -82,11 +85,22 @@ export function normalizeSearchPath(filePath: string): string {
82
85
 
83
86
  /**
84
87
  * Matches a file path against a glob or literal substring filter.
88
+ * Supports comma-separated patterns (e.g. `*.ts, *.js`).
85
89
  */
86
90
  export function matchesGlob(filePath: string, pattern: string): boolean {
87
91
  if (!pattern || pattern === '*' || pattern === '**') return true;
92
+ if (pattern.includes(',')) {
93
+ const subPatterns = pattern
94
+ .split(',')
95
+ .map((s) => s.trim())
96
+ .filter(Boolean);
97
+ if (subPatterns.length > 1) {
98
+ return subPatterns.some((sub) => matchesGlob(filePath, sub));
99
+ }
100
+ }
101
+
88
102
  const normPath = normalizeSearchPath(filePath);
89
- const normPattern = normalizeSearchPath(pattern);
103
+ const normPattern = normalizeSearchPath(pattern.trim());
90
104
 
91
105
  if (normPattern === normPath) return true;
92
106
 
@@ -102,10 +116,13 @@ export function matchesGlob(filePath: string, pattern: string): boolean {
102
116
  const c = normPattern[i];
103
117
  if (c === '*') {
104
118
  if (normPattern[i + 1] === '*') {
105
- regexStr += '.*';
106
119
  i += 2;
107
120
  if (normPattern[i] === '/') {
121
+ // `/**/` or leading `**/` matches zero or more directory segments
122
+ regexStr += '(?:.*/)?';
108
123
  i++;
124
+ } else {
125
+ regexStr += '.*';
109
126
  }
110
127
  continue;
111
128
  } else {
@@ -130,7 +147,13 @@ export function matchesGlob(filePath: string, pattern: string): boolean {
130
147
 
131
148
  try {
132
149
  const re = new RegExp(regexStr);
133
- return re.test(normPath);
150
+ if (re.test(normPath)) return true;
151
+ // Also allow basename match when pattern has no directory separator (e.g. `*.ts` matching `src/app.ts`)
152
+ if (!normPattern.includes('/')) {
153
+ const baseName = normPath.split('/').pop() || normPath;
154
+ if (re.test(baseName)) return true;
155
+ }
156
+ return false;
134
157
  } catch (err) {
135
158
  void err;
136
159
  return normPath.includes(normPattern.replace(/[*?]/g, ''));
@@ -286,11 +309,11 @@ export function searchInFiles(
286
309
  export function replaceInFiles(
287
310
  files: Record<string, string>,
288
311
  arg2: string | SearchOptions,
289
- arg3: string,
312
+ arg3?: string,
290
313
  arg4?: SearchOptions | string[]
291
314
  ): ReplaceResult {
292
315
  let query = '';
293
- const replacement = typeof arg3 === 'string' ? arg3 : '';
316
+ let replacement = typeof arg3 === 'string' ? arg3 : '';
294
317
  let opts: SearchOptions = {};
295
318
  let targetFiles: string[] | undefined = undefined;
296
319
 
@@ -305,6 +328,9 @@ export function replaceInFiles(
305
328
  } else if (arg2 && typeof arg2 === 'object') {
306
329
  opts = arg2;
307
330
  query = opts.query || '';
331
+ if (typeof arg3 !== 'string' && typeof opts.replacement === 'string') {
332
+ replacement = opts.replacement;
333
+ }
308
334
  if (Array.isArray(arg4)) {
309
335
  targetFiles = arg4;
310
336
  } else {
@@ -313,10 +339,13 @@ export function replaceInFiles(
313
339
  }
314
340
 
315
341
  if (!query) {
342
+ const copy = { ...files };
316
343
  return {
317
- updatedFiles: { ...files },
344
+ updatedFiles: copy,
345
+ files: copy,
318
346
  replacedCount: 0,
319
- filesAffected: []
347
+ filesAffected: [],
348
+ filesModified: 0
320
349
  };
321
350
  }
322
351
 
@@ -337,10 +366,13 @@ export function replaceInFiles(
337
366
  regex = new RegExp(patternStr, isCaseSensitive ? 'g' : 'gi');
338
367
  } catch (err) {
339
368
  void err;
369
+ const copy = { ...files };
340
370
  return {
341
- updatedFiles: { ...files },
371
+ updatedFiles: copy,
372
+ files: copy,
342
373
  replacedCount: 0,
343
- filesAffected: []
374
+ filesAffected: [],
375
+ filesModified: 0
344
376
  };
345
377
  }
346
378
 
@@ -353,29 +385,39 @@ export function replaceInFiles(
353
385
  if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
354
386
  if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
355
387
 
356
- // Count matches safely
357
- regex.lastIndex = 0;
388
+ const lines = content.split('\n');
358
389
  let countInFile = 0;
359
- let m: RegExpExecArray | null;
360
- while ((m = regex.exec(content)) !== null) {
361
- countInFile++;
362
- if (m[0].length === 0) {
363
- regex.lastIndex++;
364
- if (regex.lastIndex > content.length) {
365
- break;
390
+ const newLines: string[] = [];
391
+
392
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
393
+ const lineText = lines[lineIdx];
394
+ regex.lastIndex = 0;
395
+ let lineMatches = 0;
396
+ let m: RegExpExecArray | null;
397
+ while ((m = regex.exec(lineText)) !== null) {
398
+ lineMatches++;
399
+ if (m[0].length === 0) {
400
+ regex.lastIndex++;
401
+ if (regex.lastIndex > lineText.length) {
402
+ break;
403
+ }
404
+ }
405
+ }
406
+ if (lineMatches > 0) {
407
+ countInFile += lineMatches;
408
+ regex.lastIndex = 0;
409
+ if (isRegex) {
410
+ newLines.push(lineText.replace(regex, replacement));
411
+ } else {
412
+ newLines.push(lineText.replace(regex, () => replacement));
366
413
  }
414
+ } else {
415
+ newLines.push(lineText);
367
416
  }
368
417
  }
369
418
 
370
419
  if (countInFile > 0) {
371
- regex.lastIndex = 0;
372
- let newContent: string;
373
- if (isRegex) {
374
- newContent = content.replace(regex, replacement);
375
- } else {
376
- newContent = content.replace(regex, () => replacement);
377
- }
378
- updatedFiles[filePath] = newContent;
420
+ updatedFiles[filePath] = newLines.join('\n');
379
421
  filesAffected.push(filePath);
380
422
  replacedCount += countInFile;
381
423
  }
@@ -383,7 +425,9 @@ export function replaceInFiles(
383
425
 
384
426
  return {
385
427
  updatedFiles,
428
+ files: updatedFiles,
386
429
  replacedCount,
387
- filesAffected
430
+ filesAffected,
431
+ filesModified: filesAffected.length
388
432
  };
389
433
  }