launch-doctor 0.2.1 → 0.4.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 (66) hide show
  1. package/CHANGELOG.md +105 -4
  2. package/LICENSE +1 -0
  3. package/README.md +239 -39
  4. package/dist/src/access.d.ts +52 -0
  5. package/dist/src/access.js +482 -0
  6. package/dist/src/baseline.d.ts +6 -3
  7. package/dist/src/baseline.js +15 -8
  8. package/dist/src/changed.d.ts +12 -0
  9. package/dist/src/changed.js +34 -0
  10. package/dist/src/checks/access.d.ts +7 -0
  11. package/dist/src/checks/access.js +868 -0
  12. package/dist/src/checks/costs.d.ts +8 -0
  13. package/dist/src/checks/costs.js +54 -11
  14. package/dist/src/checks/database.js +201 -6
  15. package/dist/src/checks/first-impressions.js +247 -117
  16. package/dist/src/checks/legal.js +29 -13
  17. package/dist/src/checks/monitoring.js +47 -15
  18. package/dist/src/checks/payments.js +141 -6
  19. package/dist/src/checks/secrets.d.ts +8 -0
  20. package/dist/src/checks/secrets.js +185 -16
  21. package/dist/src/checks/supabase-storage.d.ts +31 -0
  22. package/dist/src/checks/supabase-storage.js +216 -0
  23. package/dist/src/cli.js +201 -12
  24. package/dist/src/demo.d.ts +13 -0
  25. package/dist/src/demo.js +59 -2
  26. package/dist/src/detect.d.ts +1 -1
  27. package/dist/src/detect.js +5 -2
  28. package/dist/src/fixes.js +10 -7
  29. package/dist/src/git.d.ts +25 -0
  30. package/dist/src/git.js +121 -0
  31. package/dist/src/github.d.ts +90 -0
  32. package/dist/src/github.js +330 -0
  33. package/dist/src/history.js +17 -3
  34. package/dist/src/hook.d.ts +13 -0
  35. package/dist/src/hook.js +96 -0
  36. package/dist/src/hooks-setup.d.ts +24 -0
  37. package/dist/src/hooks-setup.js +187 -0
  38. package/dist/src/ignore.d.ts +36 -0
  39. package/dist/src/ignore.js +164 -0
  40. package/dist/src/index.d.ts +1 -0
  41. package/dist/src/index.js +30 -3
  42. package/dist/src/init.d.ts +1 -1
  43. package/dist/src/init.js +2 -2
  44. package/dist/src/live.d.ts +9 -0
  45. package/dist/src/live.js +73 -22
  46. package/dist/src/mcp.d.ts +140 -0
  47. package/dist/src/mcp.js +386 -0
  48. package/dist/src/net-guard.d.ts +34 -0
  49. package/dist/src/net-guard.js +144 -0
  50. package/dist/src/project.d.ts +42 -5
  51. package/dist/src/project.js +237 -107
  52. package/dist/src/report.d.ts +4 -0
  53. package/dist/src/report.js +23 -1
  54. package/dist/src/routes.d.ts +10 -0
  55. package/dist/src/routes.js +21 -4
  56. package/dist/src/safe-fs.d.ts +19 -0
  57. package/dist/src/safe-fs.js +77 -0
  58. package/dist/src/sanitize.d.ts +17 -0
  59. package/dist/src/sanitize.js +90 -0
  60. package/dist/src/sarif.js +1 -1
  61. package/dist/src/summary.d.ts +7 -0
  62. package/dist/src/summary.js +26 -17
  63. package/dist/src/types.d.ts +26 -0
  64. package/dist/src/util.d.ts +2 -0
  65. package/dist/src/util.js +2 -0
  66. package/package.json +9 -5
@@ -1,8 +1,14 @@
1
- import { execFileSync } from 'node:child_process';
2
1
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
3
2
  import { homedir } from 'node:os';
4
- import { basename, extname, join, resolve } from 'node:path';
3
+ import { basename, dirname, extname, join, resolve } from 'node:path';
5
4
  import { stripComments } from './comments.js';
5
+ import { git, gitStatus, SAFE_DIFF } from './git.js';
6
+ import { compileIgnore, matchesGitignore, matchesIgnore } from './ignore.js';
7
+ import { entryKind, readRegularFile } from './safe-fs.js';
8
+ /** Largest .launchdoctorignore or baseline file read; anything bigger is treated as missing. */
9
+ export const CONFIG_FILE_MAX_BYTES = 16 * 1024 * 1024;
10
+ /** Lines of .launchdoctorignore used; the rest are skipped and the report says so. */
11
+ export const MAX_IGNORE_LINES = 1000;
6
12
  const SKIP_DIRS = new Set([
7
13
  'node_modules',
8
14
  'dist',
@@ -49,6 +55,7 @@ const TEXT_EXT = new Set([
49
55
  '.mdx',
50
56
  '.txt',
51
57
  '.xml',
58
+ '.plist',
52
59
  ]);
53
60
  const SPECIAL_NAMES = new Set([
54
61
  'firestore.rules',
@@ -70,6 +77,8 @@ const SKIP_FILES = new Set([
70
77
  ]);
71
78
  const MAX_FILES = 20_000;
72
79
  const MAX_FILE_SIZE = 1_000_000;
80
+ /** Total size of the text files read in one scan (128 MB). Past it, the rest are skipped and the report says so. */
81
+ export const MAX_TOTAL_BYTES = 128 * 1024 * 1024;
73
82
  export function isCodeFile(file) {
74
83
  const p = typeof file === 'string' ? file : file.path;
75
84
  return CODE_EXT.has(extname(p).toLowerCase());
@@ -79,7 +88,8 @@ export function isEnvPath(p) {
79
88
  return name === '.env' || name.startsWith('.env.') || name.endsWith('.env');
80
89
  }
81
90
  export function isExampleEnvPath(p) {
82
- return isEnvPath(p) && /(example|sample|template|defaults|dist|schema|tpl)$/i.test(basename(p));
91
+ // .env.example, .env.sample, and .example.env (the word can come before or after "env")
92
+ return (isEnvPath(p) && /(?:^|[._-])(?:example|sample|template|defaults?|dist|schema|tpl)(?:[._-]|$)/i.test(basename(p)));
83
93
  }
84
94
  export function isRealEnvPath(p) {
85
95
  return isEnvPath(p) && !isExampleEnvPath(p);
@@ -106,6 +116,26 @@ export function isRouteLike(f) {
106
116
  /\b(?:app|router)\.(?:post|get|all)\s*\(|Deno\.serve\s*\(|\bserve\s*\(\s*async/.test(f.content) ||
107
117
  /@(?:app|router|bp|blueprint|api)\.(?:route|get|post|put|patch|delete)\s*\(|\burlpatterns\s*=/.test(f.content));
108
118
  }
119
+ /** Mobile app frameworks: their code ships inside the app people install. */
120
+ const MOBILE_PACKAGES = ['expo', 'react-native'];
121
+ /** Web frameworks that make a React Native / Expo project a website too (react and react-dom alone don't). */
122
+ const WEB_FRAMEWORKS = [
123
+ 'next',
124
+ 'vite',
125
+ 'react-scripts',
126
+ 'vue',
127
+ 'svelte',
128
+ 'nuxt',
129
+ 'astro',
130
+ '@sveltejs/kit',
131
+ 'solid-js',
132
+ 'preact',
133
+ '@angular/core',
134
+ '@remix-run/react',
135
+ 'lit',
136
+ ];
137
+ /** Files in a mobile app's folder that don't ship inside the app. */
138
+ const MOBILE_NOT_SHIPPED = /(^|\/)(server|api|backend|functions|scripts|supabase|e2e|__tests__)\/|\+api\.[cm]?[jt]sx?$|\.server\.[cm]?[jt]sx?$|(^|\/)(metro|babel|jest|eslint|tailwind|postcss|webpack|vitest)\.config\./;
109
139
  const FRONTEND_PACKAGES = [
110
140
  'react',
111
141
  'react-dom',
@@ -121,6 +151,8 @@ const FRONTEND_PACKAGES = [
121
151
  '@remix-run/react',
122
152
  'lit',
123
153
  ];
154
+ /** Server frameworks: a command-line tool that depends on one may well be serving a website. */
155
+ const SERVER_FRAMEWORKS = ['express', 'fastify', 'hono', '@hono/node-server', 'koa', '@nestjs/core', '@hapi/hapi'];
124
156
  /** Turn an import specifier into a package name ("@scope/pkg/sub@1" -> "@scope/pkg"). */
125
157
  export function packageNameOf(spec) {
126
158
  let s = spec
@@ -135,10 +167,15 @@ export function packageNameOf(spec) {
135
167
  s = s.replace(/(?<=.)@.*$/, '');
136
168
  return s || null;
137
169
  }
138
- const IMPORT_RE = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|^\s*import\s+)["']([^"'\n]+)["']/gm;
170
+ // "^[ \t]*import", not "^\s*import": with the m flag, \s* ran across every following newline from each line start,
171
+ // so a file of blank lines took quadratic time (100 KB of newlines hung the scan).
172
+ const IMPORT_RE = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|^[ \t]*import\s+)["']([^"'\n]+)["']/gm;
139
173
  const PY_IMPORT_RE = /^[ \t]*(?:from|import)[ \t]+([A-Za-z_][\w.]*)/gm;
140
174
  /** Python package/module names mapped to the npm names the checks look for. */
141
175
  const PY_ALIASES = {
176
+ fastapi: 'fastapi',
177
+ flask: 'flask',
178
+ django: 'django',
142
179
  supabase: '@supabase/supabase-js',
143
180
  stripe: 'stripe',
144
181
  openai: 'openai',
@@ -172,6 +209,10 @@ const PY_ALIASES = {
172
209
  'flask-limiter': 'limiter',
173
210
  slowapi: 'limiter',
174
211
  'django-ratelimit': 'limiter',
212
+ jwt: 'pyjwt',
213
+ pyjwt: 'pyjwt',
214
+ jose: 'python-jose',
215
+ 'python-jose': 'python-jose',
175
216
  };
176
217
  function pythonDep(name) {
177
218
  const lower = name.toLowerCase();
@@ -186,6 +227,11 @@ export class ProjectContext {
186
227
  /** Text files we read. */
187
228
  files = [];
188
229
  truncated = false;
230
+ /** Did the scan stop reading files because MAX_TOTAL_BYTES were read? */
231
+ byteLimitReached = false;
232
+ bytesRead = 0;
233
+ /** Folders left out because they are separate git repositories (they have their own .git folder). */
234
+ nestedRepos = [];
189
235
  deps = new Set();
190
236
  imports = new Set();
191
237
  scripts = [];
@@ -196,19 +242,32 @@ export class ProjectContext {
196
242
  * Monitoring, legal pages and first impressions only matter for web apps.
197
243
  */
198
244
  isWebApp;
245
+ /** Is this a React Native / Expo app (or does it contain one)? */
246
+ isMobileApp;
247
+ /** Every package.json folder ("" for the root), and whether it is a mobile app. */
248
+ packageDirs = [];
249
+ /** Does the root package.json declare a "bin" (is this a command-line tool)? */
250
+ rootIsCli = false;
199
251
  /** Finding / checklist ids silenced in .launchdoctorignore. */
200
252
  ignoredIds = new Set();
201
- ignoredPathRules = '';
253
+ /** Lines of .launchdoctorignore past the first MAX_IGNORE_LINES, which were not used. */
254
+ ignoreLinesSkipped = 0;
255
+ ignoredPathRules = [];
202
256
  tracked;
203
257
  byPath = new Map();
204
258
  clientCache = new Map();
205
259
  lineStarts = new Map();
206
260
  codeCache = new Map();
261
+ addedCache = new Map();
207
262
  maxFiles;
263
+ maxBytes;
208
264
  constructor(root, options = {}) {
209
265
  this.root = resolve(root);
210
266
  this.options = options;
211
267
  this.maxFiles = options.maxFiles ?? MAX_FILES;
268
+ this.maxBytes = options.maxBytes ?? MAX_TOTAL_BYTES;
269
+ // Known before the walk, so folders that are separate git repositories can be left out.
270
+ this.gitRoot = options.useGit === false ? null : findGitRoot(this.root);
212
271
  this.readIgnoreFile();
213
272
  this.walk();
214
273
  this.readPackages();
@@ -226,7 +285,6 @@ export class ProjectContext {
226
285
  }
227
286
  }
228
287
  this.name = name;
229
- this.gitRoot = options.useGit === false ? null : findGitRoot(this.root);
230
288
  this.tracked = this.gitRoot ? gitLsFiles(this.root) : null;
231
289
  const fullStack = [
232
290
  'next',
@@ -242,11 +300,20 @@ export class ProjectContext {
242
300
  'vike',
243
301
  ];
244
302
  this.isSpa = (this.uses('vite') || this.uses('react-scripts')) && !fullStack.some((p) => this.uses(p));
303
+ this.isMobileApp = this.packageDirs.some((p) => p.mobile);
304
+ const indexHtml = this.paths.some((p) => /^(?:public\/)?index\.html?$/i.test(p));
245
305
  // HTML under docs/ (and coverage/, node_modules/, which are never read) doesn't make a project a website.
246
- this.isWebApp =
247
- this.usesAny(FRONTEND_PACKAGES) ||
248
- this.files.some((f) => isCodeFile(f) && !isTestPath(f.path) && !/(^|\/)docs\//.test(f.path) && isRouteLike(f)) ||
249
- this.paths.some((p) => /^(?:public\/)?index\.html?$/i.test(p));
306
+ // A React Native app uses react too, and its server folder is the app's backend, not a website.
307
+ // A command-line tool (package.json "bin") often contains route-like text as data, such as
308
+ // regexes or sample code, so that alone doesn't make it a website unless it also depends on a
309
+ // server framework. Frontend packages and an index.html still count.
310
+ const routeEvidence = !this.rootIsCli || this.usesAny(SERVER_FRAMEWORKS);
311
+ this.isWebApp = this.isMobileApp
312
+ ? this.usesAny(WEB_FRAMEWORKS) || indexHtml
313
+ : this.usesAny(FRONTEND_PACKAGES) ||
314
+ (routeEvidence &&
315
+ this.files.some((f) => isCodeFile(f) && !isTestPath(f.path) && !/(^|\/)docs\//.test(f.path) && isRouteLike(f))) ||
316
+ indexHtml;
250
317
  }
251
318
  // ---------- reading the project ----------
252
319
  /**
@@ -257,27 +324,43 @@ export class ProjectContext {
257
324
  */
258
325
  readIgnoreFile() {
259
326
  let text;
260
- try {
261
- text = readFileSync(join(this.root, '.launchdoctorignore'), 'utf8');
327
+ if (this.options.configFrom) {
328
+ assertConfigRef(this.root, this.options.configFrom);
329
+ const atRef = readAtRef(this.root, this.options.configFrom, '.launchdoctorignore');
330
+ if (atRef === null)
331
+ return;
332
+ text = atRef;
262
333
  }
263
- catch {
264
- return;
334
+ else {
335
+ // Only a regular file in the project: a symlink (to a file outside it, or /dev/zero) or a FIFO is skipped.
336
+ const read = readRegularFile(join(this.root, '.launchdoctorignore'), CONFIG_FILE_MAX_BYTES);
337
+ if (read === null)
338
+ return;
339
+ text = read;
265
340
  }
266
341
  const pathRules = [];
342
+ let used = 0;
267
343
  for (const raw of text.split(/\r?\n/)) {
268
344
  const line = raw.replace(/#.*$/, '').trim();
269
345
  if (!line)
270
346
  continue;
347
+ // Real ignore files are a few dozen lines. A huge one is cut off (and the report says so), so it can't
348
+ // slow every scan down.
349
+ if (used >= MAX_IGNORE_LINES) {
350
+ this.ignoreLinesSkipped++;
351
+ continue;
352
+ }
353
+ used++;
271
354
  // A bare word is a finding id, unless a file or folder with that name exists (then it's a path).
272
355
  if (/^[a-z0-9-]+$/.test(line) && !existsSync(join(this.root, line)))
273
356
  this.ignoredIds.add(line);
274
357
  else
275
358
  pathRules.push(line);
276
359
  }
277
- this.ignoredPathRules = pathRules.join('\n');
360
+ this.ignoredPathRules = compileIgnore(pathRules.join('\n'));
278
361
  }
279
362
  isIgnoredPath(relPath) {
280
- return this.ignoredPathRules !== '' && matchesGitignore(this.ignoredPathRules, relPath);
363
+ return this.ignoredPathRules.length > 0 && matchesIgnore(this.ignoredPathRules, relPath);
281
364
  }
282
365
  walk() {
283
366
  const stack = [''];
@@ -300,6 +383,11 @@ export class ProjectContext {
300
383
  continue;
301
384
  if (entry.name.startsWith('.') && entry.name !== '.github')
302
385
  continue;
386
+ // Another project cloned inside this one (like a tool you're trying out) isn't part of this app.
387
+ if (this.gitRoot && isSeparateRepo(join(abs, entry.name))) {
388
+ this.nestedRepos.push(relPath);
389
+ continue;
390
+ }
303
391
  stack.push(relPath);
304
392
  continue;
305
393
  }
@@ -314,8 +402,16 @@ export class ProjectContext {
314
402
  continue;
315
403
  try {
316
404
  const full = join(abs, entry.name);
317
- if (statSync(full).size > MAX_FILE_SIZE)
405
+ const size = statSync(full).size;
406
+ if (size > MAX_FILE_SIZE)
318
407
  continue;
408
+ // A cap on the total read keeps memory bounded (1 GB of source used about 2 GB). The largest of the 50
409
+ // corpus apps reads 12.7 MB, so real projects are far below it.
410
+ if (this.bytesRead + size > this.maxBytes) {
411
+ this.byteLimitReached = true;
412
+ continue;
413
+ }
414
+ this.bytesRead += size;
319
415
  // Strip the byte-order mark some Windows editors add, or JSON.parse fails.
320
416
  const file = { path: relPath, content: readFileSync(full, 'utf8').replace(/^/, '') };
321
417
  this.files.push(file);
@@ -335,10 +431,18 @@ export class ProjectContext {
335
431
  if (name === 'package.json') {
336
432
  try {
337
433
  const pkg = JSON.parse(file.content);
434
+ let mobile = false;
338
435
  for (const field of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {
339
- for (const dep of Object.keys(pkg[field] ?? {}))
436
+ for (const dep of Object.keys(pkg[field] ?? {})) {
340
437
  this.deps.add(dep);
438
+ if (MOBILE_PACKAGES.includes(dep))
439
+ mobile = true;
440
+ }
341
441
  }
442
+ const dir = dirname(file.path);
443
+ this.packageDirs.push({ dir: dir === '.' ? '' : dir, mobile });
444
+ if (dir === '.' && pkg.bin)
445
+ this.rootIsCli = true;
342
446
  for (const script of Object.values(pkg.scripts ?? {})) {
343
447
  if (typeof script === 'string')
344
448
  this.scripts.push(script);
@@ -431,6 +535,23 @@ export class ProjectContext {
431
535
  file(path) {
432
536
  return this.byPath.get(path);
433
537
  }
538
+ /**
539
+ * With `configFrom`: was this line added or changed since that git ref? Used so an inline
540
+ * "launch-doctor-ignore" comment a pull request adds can't silence the pull request's own finding.
541
+ * Without `configFrom` this is always false. If git can't tell (it fails, or the file is new),
542
+ * the answer is true, so the comment is not trusted.
543
+ */
544
+ addedSinceConfigRef(relPath, line) {
545
+ const ref = this.options.configFrom;
546
+ if (!ref)
547
+ return false;
548
+ let added = this.addedCache.get(relPath);
549
+ if (!added) {
550
+ added = addedLinesSince(this.root, ref, relPath);
551
+ this.addedCache.set(relPath, added);
552
+ }
553
+ return added === 'all' || added.has(line);
554
+ }
434
555
  hasPath(re) {
435
556
  return this.paths.some((p) => re.test(p));
436
557
  }
@@ -520,8 +641,28 @@ export class ProjectContext {
520
641
  this.clientCache.set(file.path, result);
521
642
  return result;
522
643
  }
644
+ /** Is this file part of a React Native / Expo app (the closest package.json is a mobile one)? */
645
+ isMobileFile(path) {
646
+ if (!this.isMobileApp)
647
+ return false;
648
+ let best;
649
+ for (const pkg of this.packageDirs) {
650
+ const inside = pkg.dir === '' || path === pkg.dir || path.startsWith(`${pkg.dir}/`);
651
+ if (inside && (!best || pkg.dir.length > best.dir.length))
652
+ best = pkg;
653
+ }
654
+ return best?.mobile ?? false;
655
+ }
523
656
  computeIsClient(file) {
524
657
  const p = file.path;
658
+ // Everything in a mobile app ships inside the app people install, including Expo's app config ("extra" values).
659
+ if (this.isMobileFile(p)) {
660
+ if (/(^|\/)app\.(?:json|config\.[cm]?[jt]s)$/.test(p))
661
+ return true;
662
+ if (isCodeFile(p) && !/\.(py|rb|php|go|html?)$/i.test(p) && !MOBILE_NOT_SHIPPED.test(p) && !isTestPath(p)) {
663
+ return !looksLikeServerCode(file.content);
664
+ }
665
+ }
525
666
  if (!isCodeFile(p) || /\.(py|rb|php|go)$/i.test(p))
526
667
  return false;
527
668
  if (/\.html?$/i.test(p))
@@ -565,6 +706,8 @@ export class ProjectContext {
565
706
  ['@sveltejs/kit', 'SvelteKit'],
566
707
  ['astro', 'Astro'],
567
708
  ['@remix-run/react', 'Remix'],
709
+ ['expo', 'Expo'],
710
+ ['react-native', 'React Native'],
568
711
  ['vite', 'Vite'],
569
712
  ['react', 'React'],
570
713
  ['vue', 'Vue'],
@@ -572,6 +715,9 @@ export class ProjectContext {
572
715
  ['express', 'Express'],
573
716
  ['hono', 'Hono'],
574
717
  ['fastify', 'Fastify'],
718
+ ['fastapi', 'FastAPI'],
719
+ ['flask', 'Flask'],
720
+ ['django', 'Django'],
575
721
  ['@supabase/supabase-js', 'Supabase'],
576
722
  ['firebase', 'Firebase'],
577
723
  ['@prisma/client', 'Prisma'],
@@ -580,10 +726,16 @@ export class ProjectContext {
580
726
  ['convex', 'Convex'],
581
727
  ['stripe', 'Stripe'],
582
728
  ['razorpay', 'Razorpay'],
729
+ ['@paddle/paddle-node-sdk', 'Paddle'],
730
+ ['@lemonsqueezy/lemonsqueezy.js', 'Lemon Squeezy'],
731
+ ['appwrite', 'Appwrite'],
732
+ ['node-appwrite', 'Appwrite'],
583
733
  ['@clerk/nextjs', 'Clerk'],
584
734
  ['next-auth', 'NextAuth'],
585
735
  ['openai', 'OpenAI'],
586
736
  ['@anthropic-ai/sdk', 'Anthropic'],
737
+ ['@google/genai', 'Gemini'],
738
+ ['@google/generative-ai', 'Gemini'],
587
739
  ['ai', 'Vercel AI SDK'],
588
740
  ];
589
741
  const out = [];
@@ -608,30 +760,73 @@ function looksLikeServerCode(content) {
608
760
  return (/(?:from\s*|require\s*\(\s*)["'](?:node:)?(express|fastify|hono|koa|http|https|fs|child_process|@hono\/node-server)["']/.test(content) || /\.listen\s*\(\s*(?:\d|port|process\.env)/i.test(content));
609
761
  }
610
762
  // ---------- git helpers ----------
763
+ // Every git call goes through src/git.ts, which stops the scanned repository's config from running programs.
764
+ export { git, gitArgs } from './git.js';
765
+ /** A ref is a branch, tag or commit name. A leading "-" would be read by git as an option. */
766
+ const SAFE_REF = /^[\w][\w./@^~-]*$/;
767
+ /** Throws unless `ref` names a commit in the git repository that holds `root`. */
768
+ export function assertConfigRef(root, ref) {
769
+ if (!SAFE_REF.test(ref))
770
+ throw new Error(`"${ref}" is not a valid git ref`);
771
+ const gitRoot = findGitRoot(resolve(root));
772
+ if (!gitRoot)
773
+ throw new Error('--config-from needs a folder inside a git repository');
774
+ if (git(gitRoot, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]) === null) {
775
+ throw new Error(`Git ref "${ref}" was not found. On GitHub Actions, fetch the base commit first (git fetch --depth=1 origin <sha>).`);
776
+ }
777
+ }
611
778
  /**
612
- * Every git call goes through here. core.fsmonitor=false stops a scanned folder's .git/config
613
- * from making git run a command of its choosing (fsmonitor can be set to any program).
779
+ * The line numbers (in the working copy) of `file` that were added or changed since git ref `ref`,
780
+ * or 'all' when the file is new or git can't say. `file` is relative to `root`.
614
781
  */
615
- export function gitArgs(args) {
616
- return ['-c', 'core.fsmonitor=false', ...args];
617
- }
618
- function git(cwd, args) {
619
- try {
620
- return execFileSync('git', gitArgs(args), {
621
- cwd,
622
- stdio: ['ignore', 'pipe', 'ignore'],
623
- maxBuffer: 64 * 1024 * 1024,
624
- }).toString();
625
- }
626
- catch {
627
- return null;
782
+ export function addedLinesSince(root, ref, file) {
783
+ const cwd = resolve(root);
784
+ // A file that isn't at the ref is new: every line is added.
785
+ if (git(cwd, ['cat-file', '-e', `${ref}:./${file}`]) === null)
786
+ return 'all';
787
+ const diff = git(cwd, ['diff', ...SAFE_DIFF, '--no-color', '--unified=0', '--no-renames', ref, '--', file]);
788
+ if (diff === null)
789
+ return 'all';
790
+ const out = new Set();
791
+ for (const m of diff.matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm)) {
792
+ const start = Number(m[1]);
793
+ const count = m[2] === undefined ? 1 : Number(m[2]);
794
+ for (let i = 0; i < count; i++)
795
+ out.add(start + i);
628
796
  }
797
+ return out;
798
+ }
799
+ /** The text of `file` (a name inside `root`) as it was at git ref `ref`, or null if it didn't exist there. */
800
+ export function readAtRef(root, ref, file) {
801
+ // "<ref>:./<file>" is resolved against the folder git runs in, so a project in a subfolder
802
+ // reads its own file, and short Windows paths (C:\Users\NAME~1) don't confuse it.
803
+ // cat-file prints the stored bytes and, unlike git show, applies no filter or textconv.
804
+ return git(resolve(root), ['cat-file', 'blob', `${ref}:./${file}`]);
629
805
  }
630
806
  function samePath(a, b) {
631
807
  const norm = (p) => resolve(p).replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
632
808
  return norm(a) === norm(b);
633
809
  }
634
- function findGitRoot(root) {
810
+ /**
811
+ * Does this folder hold a different git repository? A .git folder means a separate clone.
812
+ * A .git file means a submodule (part of this project, so it's scanned) or a worktree
813
+ * (a second checkout of the same code, so it's not).
814
+ */
815
+ function isSeparateRepo(dir) {
816
+ const dotGit = join(dir, '.git');
817
+ const kind = entryKind(dotGit);
818
+ if (kind === 'missing')
819
+ return false;
820
+ if (kind === 'dir')
821
+ return true;
822
+ // Anything but a regular file (a FIFO, a device, a symlink) is never opened: the folder is skipped as if it
823
+ // were another repository. A real .git file is one short line ("gitdir: ...").
824
+ if (kind === 'other')
825
+ return true;
826
+ const text = readRegularFile(dotGit, 64 * 1024);
827
+ return text === null || /[\\/]worktrees[\\/]/.test(text);
828
+ }
829
+ export function findGitRoot(root) {
635
830
  const out = git(root, ['rev-parse', '--show-toplevel']);
636
831
  if (!out)
637
832
  return null;
@@ -648,77 +843,12 @@ function gitLsFiles(root) {
648
843
  return new Set(out.split('\0').filter(Boolean));
649
844
  }
650
845
  function gitCheckIgnore(root, paths) {
651
- try {
652
- // -z keeps unusual file names (spaces, accents) unquoted in the output.
653
- const out = execFileSync('git', gitArgs(['check-ignore', '-z', '--', ...paths]), {
654
- cwd: root,
655
- stdio: ['ignore', 'pipe', 'ignore'],
656
- }).toString();
657
- return new Set(out.split('\0').filter(Boolean));
658
- }
659
- catch (err) {
660
- const e = err;
661
- // Exit code 1 means "none of these are ignored".
662
- if (e.status === 1)
663
- return new Set();
664
- return null;
665
- }
666
- }
667
- function globToRegex(glob) {
668
- let re = '';
669
- for (let i = 0; i < glob.length; i++) {
670
- const ch = glob[i];
671
- if (ch === '*') {
672
- if (glob[i + 1] === '*') {
673
- re += '.*';
674
- i++;
675
- }
676
- else {
677
- re += '[^/]*';
678
- }
679
- }
680
- else if (ch === '?') {
681
- re += '[^/]';
682
- }
683
- else {
684
- re += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
685
- }
686
- }
687
- return new RegExp(`^${re}$`);
688
- }
689
- /** Minimal .gitignore matching, used when git isn't available. */
690
- export function matchesGitignore(gitignore, path) {
691
- let ignored = false;
692
- const name = basename(path);
693
- for (const raw of gitignore.split(/\r?\n/)) {
694
- let line = raw.trim();
695
- if (!line || line.startsWith('#'))
696
- continue;
697
- const negate = line.startsWith('!');
698
- if (negate)
699
- line = line.slice(1);
700
- line = line.replace(/\/+$/, '');
701
- // "**/x" means "x in any folder".
702
- let anyDepth = false;
703
- while (line.startsWith('**/')) {
704
- line = line.slice(3);
705
- anyDepth = true;
706
- }
707
- const anchored = line.startsWith('/') || line.includes('/');
708
- line = line.replace(/^\//, '');
709
- if (!line)
710
- continue;
711
- const re = globToRegex(line);
712
- const segments = path.split('/');
713
- let hit;
714
- if (!anchored)
715
- hit = re.test(name) || segments.some((seg) => re.test(seg));
716
- else if (anyDepth)
717
- hit = segments.some((_, i) => re.test(segments.slice(i).join('/')));
718
- else
719
- hit = re.test(path);
720
- if (hit)
721
- ignored = !negate;
722
- }
723
- return ignored;
846
+ // -z keeps unusual file names (spaces, accents) unquoted in the output.
847
+ const { stdout, status } = gitStatus(root, ['check-ignore', '-z', '--', ...paths]);
848
+ if (stdout !== null)
849
+ return new Set(stdout.split('\0').filter(Boolean));
850
+ // Exit code 1 means "none of these are ignored".
851
+ return status === 1 ? new Set() : null;
724
852
  }
853
+ /** Minimal .gitignore matching, used when git isn't available (see src/ignore.ts). */
854
+ export { matchesGitignore };
@@ -1,6 +1,10 @@
1
1
  import type { Report } from './types.js';
2
2
  export declare const bold: (s: string) => string;
3
3
  export declare const dim: (s: string) => string;
4
+ /** Shown when the scan hit MAX_TOTAL_BYTES (terminal report and MCP). */
5
+ export declare const BYTE_LIMIT_NOTE = "Very large project: only the first 128 MB of source files were read, so some files were not checked.";
6
+ /** "Left out Twin/: a separate git repository inside this folder. Scan it on its own." */
7
+ export declare function nestedReposNote(repos: string[]): string;
4
8
  export declare function renderReport(report: Report, opts?: {
5
9
  fixFile?: string;
6
10
  }): string;
@@ -1,5 +1,5 @@
1
1
  import { shortWhere } from './checks/common.js';
2
- import { plural } from './util.js';
2
+ import { ISSUES_URL, plural } from './util.js';
3
3
  const useColor = !process.env.NO_COLOR && (process.env.FORCE_COLOR ? process.env.FORCE_COLOR !== '0' : !!process.stdout.isTTY);
4
4
  const paint = (code) => (s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : s);
5
5
  export const bold = paint('1');
@@ -8,6 +8,16 @@ const red = paint('31');
8
8
  const green = paint('32');
9
9
  const yellow = paint('33');
10
10
  const cyan = paint('36');
11
+ /** Shown when the scan hit MAX_TOTAL_BYTES (terminal report and MCP). */
12
+ export const BYTE_LIMIT_NOTE = 'Very large project: only the first 128 MB of source files were read, so some files were not checked.';
13
+ /** "Left out Twin/: a separate git repository inside this folder. Scan it on its own." */
14
+ export function nestedReposNote(repos) {
15
+ const names = repos.slice(0, 3).map((p) => `${p}/`);
16
+ const more = repos.length > 3 ? ` and ${repos.length - 3} more` : '';
17
+ return repos.length === 1
18
+ ? `Left out ${names[0]}: a separate git repository inside this folder. Scan it on its own.`
19
+ : `Left out ${repos.length} separate git repositories inside this folder (${names.join(', ')}${more}). Scan them on their own.`;
20
+ }
11
21
  function gradeColor(grade) {
12
22
  if (grade === 'A' || grade === 'B')
13
23
  return green;
@@ -73,8 +83,19 @@ export function renderReport(report, opts = {}) {
73
83
  const stack = report.stack.length ? ` · ${report.stack.join(', ')}` : '';
74
84
  const unit = report.mode === 'live' ? 'request' : 'file';
75
85
  lines.push(` ${dim(`Checked ${report.projectName} · ${plural(report.filesScanned, unit)}${stack}`)}`);
86
+ if (report.partial) {
87
+ const n = report.partial.files.length;
88
+ lines.push(` ${yellow(`Only ${plural(n, 'changed file')} ${n === 1 ? 'was' : 'were'} reported on, not the whole project. Run without --changed or --staged for the full grade.`)}`);
89
+ }
76
90
  if (report.truncated)
77
91
  lines.push(` ${yellow('Very large project: only the first 20,000 files were checked.')}`);
92
+ if (report.byteLimitReached)
93
+ lines.push(` ${yellow(BYTE_LIMIT_NOTE)}`);
94
+ if (report.ignoreLinesSkipped) {
95
+ lines.push(` ${yellow(`.launchdoctorignore is very long: only its first 1,000 lines were used (${plural(report.ignoreLinesSkipped, 'line')} skipped).`)}`);
96
+ }
97
+ if (report.nestedRepos?.length)
98
+ lines.push(` ${dim(nestedReposNote(report.nestedRepos))}`);
78
99
  lines.push('');
79
100
  lines.push(` ${bold('Overall grade')} ${badge(report.grade)} ${report.verdict}`);
80
101
  lines.push('');
@@ -132,5 +153,6 @@ export function renderReport(report, opts = {}) {
132
153
  lines.push(` ${dim('Paste them one at a time into Claude Code, Cursor, Lovable or Bolt, then run launch-doctor again.')}`);
133
154
  lines.push('');
134
155
  }
156
+ lines.push(` ${dim(`Wrong finding or a missed problem? Please report it: ${ISSUES_URL}`)}`, '');
135
157
  return `${lines.join('\n')}\n`;
136
158
  }
@@ -23,6 +23,11 @@ export declare function matchBracket(code: string, open: number): number;
23
23
  export declare function urlPathOf(file: string): string | null;
24
24
  /** Resolve a local import ("./x", "../lib/ai", "@/lib/ai", "~/lib/ai") to a project file. */
25
25
  export declare function resolveImport(ctx: ProjectContext, from: SourceFile, spec: string): SourceFile | null;
26
+ /** Local modules reachable from `text` (a handler body) through imports of `from`, up to MAX_DEPTH hops. */
27
+ export declare function reach(ctx: ProjectContext, from: SourceFile, text: string): {
28
+ files: SourceFile[];
29
+ unresolved: boolean;
30
+ };
26
31
  /** Per-handler view of a file, for Next.js-style route files. Empty for files with no exported handlers. */
27
32
  export declare function handlersOf(ctx: ProjectContext, file: SourceFile): RouteHandler[];
28
33
  export interface HandlerEvidence {
@@ -34,6 +39,11 @@ export interface HandlerEvidence {
34
39
  }
35
40
  export declare function evidenceOf(ctx: ProjectContext, h: RouteHandler): HandlerEvidence;
36
41
  export declare function authIsUsed(authRe: RegExp, ev: HandlerEvidence): boolean;
42
+ /**
43
+ * `code` without its import and require statements (JavaScript and Python). A sign-in helper that is only imported
44
+ * checks nothing, so a sign-in pattern must not count the import line. Every bound is fixed, so this stays linear.
45
+ */
46
+ export declare function withoutImports(code: string): string;
37
47
  /** Turn one Next.js matcher string into a RegExp, or null if we can't understand it. */
38
48
  export declare function matcherToRegExp(entry: string): RegExp | null;
39
49
  /** Does any matcher entry cover this URL path? `undefined` means "could not tell". */