@ywldan/kiro 0.2.12 → 0.3.1

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.
@@ -43,6 +43,7 @@ export async function buildSystemPrompt(cwd) {
43
43
  '- Use apply_patch for coordinated changes across multiple files, or when you already have a unified diff. Patches are validated before anything is written.',
44
44
  '- Use write_file only for new files or complete rewrites.',
45
45
  '- All file paths are resolved relative to the working directory. Paths escaping it require user approval.',
46
+ '- A path written as @path in a user message points at a file in the working directory. Read it with read_file before relying on its contents.',
46
47
  '- Prefer run_command for builds, tests, and quick checks so you can verify your work. Commands run in the working directory.',
47
48
  '- Tool output may be truncated. Use read_file offsets, narrower grep patterns/globs, or smaller result limits if you need more detail.',
48
49
  '- If a tool returns an error, read it carefully and adjust; edit_file/multi_edit errors include a hint about the closest line or whitespace mismatch.',
package/dist/doctor.js ADDED
@@ -0,0 +1,251 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { stat } from 'node:fs/promises';
3
+ import { configPath, ConfigError, loadConfig, } from './config.js';
4
+ import { envPath, keyStatus, loadEnvFile } from './env.js';
5
+ import { discoverModels, testConnection } from './model/discovery.js';
6
+ import { redactSecrets, registerSecretEnv } from './secrets.js';
7
+ import { formatDuration } from './ui/text.js';
8
+ import { VERSION } from './version.js';
9
+ const DOCTOR_HELP = `Kiro doctor
10
+
11
+ Usage:
12
+ kiro doctor [options]
13
+
14
+ Checks the Node version, config file, where the key is stored, and the active
15
+ endpoint. Prints one line per check and exits 1 when a check fails.
16
+
17
+ Options:
18
+ --profile <name> inspect a profile other than the active one
19
+ --offline skip the network checks
20
+ --test send a small chat completion to verify the key and model
21
+ -h, --help show this help
22
+ `;
23
+ class DoctorUsageError extends Error {
24
+ }
25
+ function parseOptions(argv) {
26
+ const options = { offline: false, test: false, help: false };
27
+ for (let index = 0; index < argv.length; index++) {
28
+ const arg = argv[index];
29
+ if (arg === '-h' || arg === '--help') {
30
+ options.help = true;
31
+ continue;
32
+ }
33
+ if (arg === '--offline') {
34
+ options.offline = true;
35
+ continue;
36
+ }
37
+ if (arg === '--test') {
38
+ options.test = true;
39
+ continue;
40
+ }
41
+ if (arg === '--profile' || arg.startsWith('--profile=')) {
42
+ const value = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : argv[++index];
43
+ if (!value)
44
+ throw new DoctorUsageError('Option --profile requires a value.');
45
+ options.profile = value;
46
+ continue;
47
+ }
48
+ throw new DoctorUsageError(`Unknown option: ${arg}`);
49
+ }
50
+ return options;
51
+ }
52
+ function nodeCheck() {
53
+ const major = Number(process.versions.node.split('.')[0]);
54
+ const text = `Node v${process.versions.node} (requires >= 20)`;
55
+ return major >= 20
56
+ ? { level: 'ok', text }
57
+ : {
58
+ level: 'fail',
59
+ text,
60
+ hint: 'Upgrade Node to 20 or newer, then run kiro again.',
61
+ };
62
+ }
63
+ async function configChecks(profileName) {
64
+ const file = configPath();
65
+ if (!existsSync(file)) {
66
+ return {
67
+ checks: [
68
+ {
69
+ level: 'fail',
70
+ text: `Config ${file} does not exist`,
71
+ hint: 'Run "kiro model" to create a profile.',
72
+ },
73
+ ],
74
+ };
75
+ }
76
+ let config;
77
+ try {
78
+ ({ config } = await loadConfig());
79
+ }
80
+ catch (error) {
81
+ return {
82
+ checks: [
83
+ {
84
+ level: 'fail',
85
+ text: `Config ${file} is invalid`,
86
+ hint: error instanceof ConfigError ? error.message : String(error),
87
+ },
88
+ ],
89
+ };
90
+ }
91
+ const checks = [{ level: 'ok', text: `Config ${file}` }];
92
+ const name = profileName ?? config.activeProfile;
93
+ const profile = config.profiles[name];
94
+ if (!profile) {
95
+ checks.push({
96
+ level: 'fail',
97
+ text: `Profile "${name}" is not configured`,
98
+ hint: `Available profiles: ${Object.keys(config.profiles).join(', ')}.`,
99
+ });
100
+ return { checks };
101
+ }
102
+ checks.push({
103
+ level: 'ok',
104
+ text: `Profile ${name}: ${profile.model} @ ${profile.baseUrl}`,
105
+ });
106
+ const status = keyStatus(profile);
107
+ if (profile.apiKeyEnv && !process.env[profile.apiKeyEnv]) {
108
+ checks.push({
109
+ level: 'fail',
110
+ text: `Key ${status}`,
111
+ hint: `Store it with "kiro model" (Edit a model) or export ${profile.apiKeyEnv}=...`,
112
+ });
113
+ }
114
+ else {
115
+ checks.push({ level: 'ok', text: `Key ${status}` });
116
+ }
117
+ const apiKey = profile.apiKeyEnv ? process.env[profile.apiKeyEnv] : undefined;
118
+ if (profile.apiKeyEnv)
119
+ registerSecretEnv(profile.apiKeyEnv, apiKey, true);
120
+ return { checks, profile, apiKey };
121
+ }
122
+ async function envCheck() {
123
+ const file = envPath();
124
+ let missing = false;
125
+ try {
126
+ const result = await loadEnvFile();
127
+ missing = result.missing;
128
+ }
129
+ catch (error) {
130
+ return {
131
+ level: 'fail',
132
+ text: `Key file ${file} could not be read`,
133
+ hint: error.message,
134
+ };
135
+ }
136
+ if (missing) {
137
+ return {
138
+ level: 'warn',
139
+ text: `Key file ${file} does not exist`,
140
+ hint: 'Keys can still come from the environment. Run "kiro model" to store one.',
141
+ };
142
+ }
143
+ if (process.platform !== 'win32') {
144
+ try {
145
+ const mode = (await stat(file)).mode & 0o777;
146
+ if ((mode & 0o077) !== 0) {
147
+ return {
148
+ level: 'warn',
149
+ text: `Key file ${file} is readable by other users (mode ${mode.toString(8)})`,
150
+ hint: `Run: chmod 600 ${file}`,
151
+ };
152
+ }
153
+ }
154
+ catch (error) {
155
+ return {
156
+ level: 'fail',
157
+ text: `Key file ${file} could not be inspected`,
158
+ hint: error.message,
159
+ };
160
+ }
161
+ }
162
+ return { level: 'ok', text: `Key file ${file}` };
163
+ }
164
+ async function networkChecks(profile, apiKey, test) {
165
+ const checks = [];
166
+ const started = performance.now();
167
+ const result = await discoverModels({
168
+ baseUrl: profile.baseUrl,
169
+ apiKey,
170
+ timeoutMs: 5000,
171
+ });
172
+ const latency = formatDuration(Math.max(0, Math.round(performance.now() - started)));
173
+ if (!result.ok) {
174
+ const transient = result.status === 404 || result.status === 429;
175
+ checks.push({
176
+ level: transient ? 'warn' : 'fail',
177
+ text: redactSecrets(result.message),
178
+ hint: result.status === 404
179
+ ? 'Some servers do not implement GET /models. The profile can still work.'
180
+ : undefined,
181
+ });
182
+ return checks;
183
+ }
184
+ checks.push({
185
+ level: 'ok',
186
+ text: `GET ${result.url} returned ${result.models.length} model${result.models.length === 1 ? '' : 's'} in ${latency}`,
187
+ });
188
+ if (!result.models.includes(profile.model)) {
189
+ checks.push({
190
+ level: 'warn',
191
+ text: `Model "${profile.model}" is not in the endpoint's list`,
192
+ hint: 'Check the model id; some servers hide models from /models.',
193
+ });
194
+ }
195
+ if (test) {
196
+ const tested = await testConnection(profile, apiKey);
197
+ checks.push({
198
+ level: tested.ok ? 'ok' : 'fail',
199
+ text: redactSecrets(tested.message),
200
+ });
201
+ }
202
+ return checks;
203
+ }
204
+ function printChecks(checks) {
205
+ for (const check of checks) {
206
+ process.stdout.write(`${check.level.padEnd(4)} ${redactSecrets(check.text)}\n`);
207
+ if (check.hint) {
208
+ process.stdout.write(` ${redactSecrets(check.hint)}\n`);
209
+ }
210
+ }
211
+ }
212
+ export async function runDoctor(argv) {
213
+ let options;
214
+ try {
215
+ options = parseOptions(argv);
216
+ }
217
+ catch (error) {
218
+ if (error instanceof DoctorUsageError) {
219
+ console.error(`Kiro doctor: ${error.message}`);
220
+ console.error('Run "kiro doctor --help" for usage.');
221
+ return 2;
222
+ }
223
+ throw error;
224
+ }
225
+ if (options.help) {
226
+ process.stdout.write(DOCTOR_HELP);
227
+ return 0;
228
+ }
229
+ if (options.offline && options.test) {
230
+ console.error('Kiro doctor: --test needs the network; drop --offline or --test.');
231
+ return 2;
232
+ }
233
+ const checks = [nodeCheck()];
234
+ const keyFile = await envCheck();
235
+ const configResult = await configChecks(options.profile);
236
+ checks.push(...configResult.checks);
237
+ if (configResult.profile)
238
+ checks.push(keyFile);
239
+ if (configResult.profile) {
240
+ if (options.offline) {
241
+ checks.push({ level: 'skip', text: 'Network checks skipped (--offline)' });
242
+ }
243
+ else {
244
+ checks.push(...(await networkChecks(configResult.profile, configResult.apiKey, options.test)));
245
+ }
246
+ }
247
+ process.stdout.write(`Kiro ${VERSION} doctor\n\n`);
248
+ printChecks(checks);
249
+ return checks.some((check) => check.level === 'fail') ? 1 : 0;
250
+ }
251
+ //# sourceMappingURL=doctor.js.map
package/dist/index.js CHANGED
@@ -12,47 +12,52 @@ import { latestSession, loadSession } from './sessions.js';
12
12
  import { MOUSE_OFF } from './ui/mouse.js';
13
13
  import { App } from './ui/App.js';
14
14
  import { runCheck, runUpdate } from './update.js';
15
+ import { runDoctor } from './doctor.js';
15
16
  import { VERSION } from './version.js';
16
- const HELP = `Kiro: a small terminal coding agent
17
-
18
- Usage: kiro [options]
19
- kiro model [command]
20
-
21
- Options:
22
- --profile <name> Use a profile from ~/.kiro/config.json
23
- --base-url <url> Override the active profile's OpenAI-compatible base URL
24
- --model <name> Override the active profile's model name
25
- -c, --continue Resume the most recent session for this directory
26
- --resume <id> Resume a specific saved session
27
- -p, --prompt <text>
28
- Run one turn without a TUI ("-" or no text reads the
29
- prompt from stdin); replies stream to stdout, notices
30
- and reasoning to stderr
31
- --yolo Skip all approval prompts (use with care)
32
- --mouse Mouse reporting is on by default: the wheel scrolls the
33
- transcript, Shift+drag selects text for copying.
34
- --no-mouse Disable mouse reporting so plain click-drag selection works.
35
- --no-alt-screen Do not switch to the terminal's alternate screen
36
- --no-skills Do not load skills from .kiro/skills, .claude/skills, or
37
- ~/.kiro/skills (KIRO_NO_SKILLS=1 does the same)
38
- -h, --help Show this help
39
- -v, --version Show the version
40
-
41
- Model commands:
42
- kiro model Interactive wizard: select, add, edit, or remove models
43
- kiro model list List configured profiles
44
- kiro model add ... Add a profile without prompts (see "kiro model --help")
45
- kiro model use <n> Make a profile active
46
- kiro model remove <n>
47
- kiro model test [n]
48
-
49
- Update commands:
50
- kiro check Compare the installed version with the latest on npm
51
- kiro update Install the latest version from npm globally
52
-
53
- Config: ~/.kiro/config.json (created with a template on first run)
54
- Keys: ~/.kiro/.env (mode 0600), or the environment variable named by "apiKeyEnv".
55
- Sessions: ~/.kiro/sessions (one directory per working directory)
17
+ const HELP = `Kiro: a small terminal coding agent
18
+
19
+ Usage: kiro [options]
20
+ kiro model [command]
21
+ kiro doctor [options]
22
+
23
+ Options:
24
+ --profile <name> Use a profile from ~/.kiro/config.json
25
+ --base-url <url> Override the active profile's OpenAI-compatible base URL
26
+ --model <name> Override the active profile's model name
27
+ -c, --continue Resume the most recent session for this directory
28
+ --resume <id> Resume a specific saved session
29
+ -p, --prompt <text>
30
+ Run one turn without a TUI ("-" or no text reads the
31
+ prompt from stdin); replies stream to stdout, notices
32
+ and reasoning to stderr
33
+ --yolo Skip all approval prompts (use with care)
34
+ --mouse Mouse reporting is on by default: the wheel scrolls the
35
+ transcript, Shift+drag selects text for copying.
36
+ --no-mouse Disable mouse reporting so plain click-drag selection works.
37
+ --no-alt-screen Do not switch to the terminal's alternate screen
38
+ --no-skills Do not load skills from .kiro/skills, .claude/skills, or
39
+ ~/.kiro/skills (KIRO_NO_SKILLS=1 does the same)
40
+ -h, --help Show this help
41
+ -v, --version Show the version
42
+
43
+ Model commands:
44
+ kiro model Interactive wizard: select, add, edit, or remove models
45
+ kiro model list List configured profiles
46
+ kiro model add ... Add a profile without prompts (see "kiro model --help")
47
+ kiro model use <n> Make a profile active
48
+ kiro model remove <n>
49
+ kiro model test [n]
50
+
51
+ Update commands:
52
+ kiro check Compare the installed version with the latest on npm
53
+ kiro update Install the latest version from npm globally
54
+
55
+ Diagnostics:
56
+ kiro doctor Check Node, config, key storage, and the active endpoint
57
+
58
+ Config: ~/.kiro/config.json (created with a template on first run)
59
+ Keys: ~/.kiro/.env (mode 0600), or the environment variable named by "apiKeyEnv".
60
+ Sessions: ~/.kiro/sessions (one directory per working directory)
56
61
  `;
57
62
  const ENTER_ALT_SCREEN = '\x1b[?1049h\x1b[H\x1b[2J';
58
63
  const LEAVE_ALT_SCREEN = '\x1b[?1049l';
@@ -201,6 +206,10 @@ async function main() {
201
206
  process.exitCode = await runUpdate();
202
207
  return;
203
208
  }
209
+ if (rawArgs[0] === 'doctor') {
210
+ process.exitCode = await runDoctor(rawArgs.slice(1));
211
+ return;
212
+ }
204
213
  let options;
205
214
  try {
206
215
  options = parseArgs(rawArgs);
package/dist/sessions.js CHANGED
@@ -159,18 +159,7 @@ export async function saveSession(input) {
159
159
  }
160
160
  return record;
161
161
  }
162
- export async function loadSession(cwd, id) {
163
- const file = sessionFile(cwd, id);
164
- let raw;
165
- try {
166
- raw = await readFile(file, 'utf8');
167
- }
168
- catch (error) {
169
- if (error.code === 'ENOENT') {
170
- throw new SessionError(`Session "${id}" was not found for this directory.`);
171
- }
172
- throw new SessionError(`Could not read session "${id}": ${error.message}`);
173
- }
162
+ function parseSessionRecord(raw, id, expectedCwd) {
174
163
  let parsed;
175
164
  try {
176
165
  parsed = JSON.parse(raw);
@@ -183,7 +172,8 @@ export async function loadSession(cwd, id) {
183
172
  if (parsed.version !== SESSION_VERSION) {
184
173
  throw new SessionError(`Session "${id}" uses unsupported version ${String(parsed.version)}; expected ${SESSION_VERSION}.`);
185
174
  }
186
- if (typeof parsed.cwd !== 'string' || path.resolve(parsed.cwd) !== path.resolve(cwd)) {
175
+ if (typeof parsed.cwd !== 'string' ||
176
+ (expectedCwd !== undefined && path.resolve(parsed.cwd) !== path.resolve(expectedCwd))) {
187
177
  throw new SessionError(`Session "${id}" belongs to a different working directory.`);
188
178
  }
189
179
  const messages = normalizeMessages(parsed.messages);
@@ -191,7 +181,7 @@ export async function loadSession(cwd, id) {
191
181
  return {
192
182
  version: SESSION_VERSION,
193
183
  id,
194
- cwd: path.resolve(cwd),
184
+ cwd: path.resolve(parsed.cwd),
195
185
  profile: typeof parsed.profile === 'string' ? parsed.profile : '',
196
186
  model: typeof parsed.model === 'string' ? parsed.model : '',
197
187
  title: typeof parsed.title === 'string' && parsed.title ? parsed.title : titleFromMessages(messages),
@@ -201,9 +191,24 @@ export async function loadSession(cwd, id) {
201
191
  usage: normalizeUsage(parsed.usage),
202
192
  };
203
193
  }
194
+ export async function loadSession(cwd, id) {
195
+ const file = sessionFile(cwd, id);
196
+ let raw;
197
+ try {
198
+ raw = await readFile(file, 'utf8');
199
+ }
200
+ catch (error) {
201
+ if (error.code === 'ENOENT') {
202
+ throw new SessionError(`Session "${id}" was not found for this directory.`);
203
+ }
204
+ throw new SessionError(`Could not read session "${id}": ${error.message}`);
205
+ }
206
+ return parseSessionRecord(raw, id, cwd);
207
+ }
204
208
  function summarize(record) {
205
209
  return {
206
210
  id: record.id,
211
+ cwd: record.cwd,
207
212
  profile: record.profile,
208
213
  model: record.model,
209
214
  title: record.title,
@@ -243,6 +248,83 @@ export async function listSessions(cwd, limit = 20) {
243
248
  sessions.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
244
249
  return { sessions: sessions.slice(0, limit), skipped };
245
250
  }
251
+ /** Reads one project directory straight from disk, for cross-directory listing. */
252
+ async function summarizeProjectDir(dir, limit) {
253
+ let entries;
254
+ try {
255
+ entries = await readdir(dir, { withFileTypes: true });
256
+ }
257
+ catch (error) {
258
+ if (error.code === 'ENOENT')
259
+ return { sessions: [], skipped: 0 };
260
+ return { sessions: [], skipped: 1 };
261
+ }
262
+ const sessions = [];
263
+ let skipped = 0;
264
+ for (const entry of entries) {
265
+ if (!entry.isFile() || !entry.name.endsWith('.json'))
266
+ continue;
267
+ const id = entry.name.slice(0, -'.json'.length);
268
+ if (!isSessionId(id)) {
269
+ skipped++;
270
+ continue;
271
+ }
272
+ try {
273
+ const raw = await readFile(path.join(dir, entry.name), 'utf8');
274
+ sessions.push(summarize(parseSessionRecord(raw, id)));
275
+ }
276
+ catch {
277
+ skipped++;
278
+ }
279
+ }
280
+ sessions.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
281
+ return { sessions: sessions.slice(0, limit), skipped };
282
+ }
283
+ /**
284
+ * Lists sessions for `cwd` and every other directory found under the sessions
285
+ * root. Sessions are grouped by the cwd stored in each record, so a moved or
286
+ * copied project folder still lists under its recorded directory.
287
+ */
288
+ export async function listAllSessions(cwd, limitPerDir = 20) {
289
+ const root = sessionsRoot();
290
+ let entries;
291
+ try {
292
+ entries = await readdir(root, { withFileTypes: true });
293
+ }
294
+ catch (error) {
295
+ if (error.code === 'ENOENT') {
296
+ return { current: [], others: [], skipped: 0 };
297
+ }
298
+ throw new SessionError(`Could not list sessions: ${error.message}`);
299
+ }
300
+ const groups = new Map();
301
+ let skipped = 0;
302
+ for (const entry of entries) {
303
+ if (!entry.isDirectory())
304
+ continue;
305
+ const result = await summarizeProjectDir(path.join(root, entry.name), limitPerDir);
306
+ skipped += result.skipped;
307
+ for (const session of result.sessions) {
308
+ const list = groups.get(session.cwd);
309
+ if (list)
310
+ list.push(session);
311
+ else
312
+ groups.set(session.cwd, [session]);
313
+ }
314
+ }
315
+ const resolved = path.resolve(cwd);
316
+ const byUpdated = (left, right) => right.updatedAt.localeCompare(left.updatedAt);
317
+ const current = (groups.get(resolved) ?? []).sort(byUpdated).slice(0, limitPerDir);
318
+ groups.delete(resolved);
319
+ const others = [...groups.entries()]
320
+ .filter(([, sessions]) => sessions.length > 0)
321
+ .map(([dirCwd, sessions]) => ({
322
+ cwd: dirCwd,
323
+ sessions: sessions.sort(byUpdated).slice(0, limitPerDir),
324
+ }))
325
+ .sort((left, right) => (right.sessions[0]?.updatedAt ?? '').localeCompare(left.sessions[0]?.updatedAt ?? ''));
326
+ return { current, others, skipped };
327
+ }
246
328
  export async function latestSession(cwd) {
247
329
  const { sessions } = await listSessions(cwd, 1);
248
330
  const newest = sessions[0];
@@ -1,72 +1,14 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { readFile, readdir, stat } from 'node:fs/promises';
2
+ import { readFile, stat } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { denied, ok, toolError } from './types.js';
5
5
  import { matchGlob } from './glob.js';
6
- import { isIgnored, parseIgnoreFile } from './ignore.js';
7
6
  import { booleanArg, displayPath, integerArg, resolvePath, stringArg } from './paths.js';
7
+ import { ALWAYS_SKIP, walkTree } from './walk.js';
8
8
  const GLOB_LIMIT = 200;
9
- const MAX_WALK_ENTRIES = 200_000;
10
9
  const MAX_GREP_FILE_BYTES = 2 * 1024 * 1024;
11
10
  const MAX_GREP_LINE_CHARS = 500;
12
11
  const MAX_CAPTURE_CHARS = 4_000_000;
13
- const ALWAYS_SKIP = new Set(['node_modules', '.git', 'dist', 'build']);
14
- async function readIgnoreRules(dirAbs, baseRel) {
15
- try {
16
- return parseIgnoreFile(await readFile(path.join(dirAbs, '.gitignore'), 'utf8'), baseRel);
17
- }
18
- catch {
19
- return [];
20
- }
21
- }
22
- /** Depth-first walk that honours .gitignore and always skips heavy directories. */
23
- async function walkTree(options) {
24
- const { cwd, rootAbs, signal, visit } = options;
25
- const rootRel = path.relative(cwd, rootAbs).split(path.sep).join('/');
26
- let visited = 0;
27
- let stopped = false;
28
- const visitDir = async (dirAbs, relDir, inherited) => {
29
- if (stopped || signal.aborted)
30
- return;
31
- const rules = [...inherited, ...(await readIgnoreRules(dirAbs, relDir))];
32
- let entries;
33
- try {
34
- entries = await readdir(dirAbs, { withFileTypes: true });
35
- }
36
- catch {
37
- return;
38
- }
39
- entries.sort((left, right) => left.name.localeCompare(right.name));
40
- for (const entry of entries) {
41
- if (stopped || signal.aborted)
42
- return;
43
- if (entry.isSymbolicLink())
44
- continue;
45
- const rel = relDir ? `${relDir}/${entry.name}` : entry.name;
46
- const isDir = entry.isDirectory();
47
- if (isDir && ALWAYS_SKIP.has(entry.name))
48
- continue;
49
- if (isIgnored(rules, rel, isDir))
50
- continue;
51
- visited++;
52
- if (visited > MAX_WALK_ENTRIES) {
53
- stopped = true;
54
- return;
55
- }
56
- const abs = path.join(dirAbs, entry.name);
57
- if ((await visit({ abs, rel, isDir })) === false) {
58
- stopped = true;
59
- return;
60
- }
61
- if (isDir) {
62
- await visitDir(abs, rel, rules);
63
- if (stopped)
64
- return;
65
- }
66
- }
67
- };
68
- await visitDir(rootAbs, rootRel, []);
69
- }
70
12
  const globTool = {
71
13
  readOnly: true,
72
14
  definition: {
@@ -0,0 +1,62 @@
1
+ import { readFile, readdir } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { isIgnored, parseIgnoreFile } from './ignore.js';
4
+ export const MAX_WALK_ENTRIES = 200_000;
5
+ export const ALWAYS_SKIP = new Set(['node_modules', '.git', 'dist', 'build']);
6
+ async function readIgnoreRules(dirAbs, baseRel) {
7
+ try {
8
+ return parseIgnoreFile(await readFile(path.join(dirAbs, '.gitignore'), 'utf8'), baseRel);
9
+ }
10
+ catch {
11
+ return [];
12
+ }
13
+ }
14
+ /** Depth-first walk that honours .gitignore and always skips heavy directories. */
15
+ export async function walkTree(options) {
16
+ const { cwd, rootAbs, signal, visit } = options;
17
+ const rootRel = path.relative(cwd, rootAbs).split(path.sep).join('/');
18
+ let visited = 0;
19
+ let stopped = false;
20
+ const visitDir = async (dirAbs, relDir, inherited) => {
21
+ if (stopped || signal.aborted)
22
+ return;
23
+ const rules = [...inherited, ...(await readIgnoreRules(dirAbs, relDir))];
24
+ let entries;
25
+ try {
26
+ entries = await readdir(dirAbs, { withFileTypes: true });
27
+ }
28
+ catch {
29
+ return;
30
+ }
31
+ entries.sort((left, right) => left.name.localeCompare(right.name));
32
+ for (const entry of entries) {
33
+ if (stopped || signal.aborted)
34
+ return;
35
+ if (entry.isSymbolicLink())
36
+ continue;
37
+ const rel = relDir ? `${relDir}/${entry.name}` : entry.name;
38
+ const isDir = entry.isDirectory();
39
+ if (isDir && ALWAYS_SKIP.has(entry.name))
40
+ continue;
41
+ if (isIgnored(rules, rel, isDir))
42
+ continue;
43
+ visited++;
44
+ if (visited > MAX_WALK_ENTRIES) {
45
+ stopped = true;
46
+ return;
47
+ }
48
+ const abs = path.join(dirAbs, entry.name);
49
+ if ((await visit({ abs, rel, isDir })) === false) {
50
+ stopped = true;
51
+ return;
52
+ }
53
+ if (isDir) {
54
+ await visitDir(abs, rel, rules);
55
+ if (stopped)
56
+ return;
57
+ }
58
+ }
59
+ };
60
+ await visitDir(rootAbs, rootRel, []);
61
+ }
62
+ //# sourceMappingURL=walk.js.map