launch-doctor 0.3.0 → 0.4.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.
Files changed (67) hide show
  1. package/CHANGELOG.md +92 -6
  2. package/LICENSE +1 -0
  3. package/README.md +138 -22
  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 +7 -0
  13. package/dist/src/checks/costs.js +14 -6
  14. package/dist/src/checks/database.js +79 -3
  15. package/dist/src/checks/first-impressions.js +22 -2
  16. package/dist/src/checks/legal.js +3 -1
  17. package/dist/src/checks/monitoring.js +8 -5
  18. package/dist/src/checks/payments.js +10 -2
  19. package/dist/src/checks/secrets.d.ts +8 -0
  20. package/dist/src/checks/secrets.js +82 -9
  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 +175 -12
  24. package/dist/src/demo.js +1 -0
  25. package/dist/src/detect.d.ts +1 -1
  26. package/dist/src/detect.js +1 -1
  27. package/dist/src/fixes.js +8 -5
  28. package/dist/src/git.d.ts +25 -0
  29. package/dist/src/git.js +121 -0
  30. package/dist/src/github.d.ts +11 -1
  31. package/dist/src/github.js +56 -14
  32. package/dist/src/grades.d.ts +42 -0
  33. package/dist/src/grades.js +163 -0
  34. package/dist/src/history.js +17 -3
  35. package/dist/src/hook.d.ts +13 -0
  36. package/dist/src/hook.js +96 -0
  37. package/dist/src/hooks-setup.d.ts +24 -0
  38. package/dist/src/hooks-setup.js +187 -0
  39. package/dist/src/ignore.d.ts +36 -0
  40. package/dist/src/ignore.js +164 -0
  41. package/dist/src/index.js +28 -3
  42. package/dist/src/init.d.ts +32 -2
  43. package/dist/src/init.js +120 -6
  44. package/dist/src/live.d.ts +13 -1
  45. package/dist/src/live.js +111 -23
  46. package/dist/src/mcp.js +7 -2
  47. package/dist/src/net-guard.d.ts +42 -0
  48. package/dist/src/net-guard.js +147 -0
  49. package/dist/src/pinned-http.d.ts +31 -0
  50. package/dist/src/pinned-http.js +104 -0
  51. package/dist/src/project.d.ts +34 -5
  52. package/dist/src/project.js +145 -111
  53. package/dist/src/report.d.ts +4 -0
  54. package/dist/src/report.js +13 -0
  55. package/dist/src/routes.d.ts +10 -0
  56. package/dist/src/routes.js +21 -4
  57. package/dist/src/safe-fs.d.ts +19 -0
  58. package/dist/src/safe-fs.js +77 -0
  59. package/dist/src/sanitize.d.ts +17 -0
  60. package/dist/src/sanitize.js +90 -0
  61. package/dist/src/sarif.js +1 -1
  62. package/dist/src/summary.d.ts +4 -0
  63. package/dist/src/summary.js +9 -4
  64. package/dist/src/types.d.ts +24 -0
  65. package/dist/src/util.d.ts +1 -1
  66. package/dist/src/util.js +1 -1
  67. package/package.json +9 -5
@@ -0,0 +1,24 @@
1
+ export interface HookSetupResult {
2
+ created: string[];
3
+ /** Existing files that a launch-doctor hook was added to. */
4
+ updated: string[];
5
+ /** [file, why] for everything left alone. */
6
+ skipped: [string, string][];
7
+ }
8
+ /**
9
+ * The package spec every generated hook runs: the current minor range from package.json ("launch-doctor@^0.4.0"), so a
10
+ * hook never silently picks up a newer minor version (or a new major one) just because it was published to npm.
11
+ */
12
+ export declare function pinnedPackage(): string;
13
+ /**
14
+ * A value in single quotes for a POSIX shell. Nothing inside single quotes is expanded, so a folder named
15
+ * `app$(curl ...)` stays a folder name; a single quote in the value is written as '\''.
16
+ */
17
+ export declare function shellQuote(value: string): string;
18
+ /**
19
+ * The block added to the pre-commit hook. Only exit code 1 (critical problems in the staged files)
20
+ * stops the commit. If the tool itself fails (no network for npx, for example) the commit goes ahead.
21
+ */
22
+ export declare function preCommitBlock(projectDir: string): string;
23
+ /** Set up the Claude Code hook, the Cursor hook and the git pre-commit hook. Existing files are merged into, never replaced. */
24
+ export declare function setupHooks(root: string): HookSetupResult;
@@ -0,0 +1,187 @@
1
+ import { chmodSync, mkdirSync, realpathSync } from 'node:fs';
2
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
3
+ import { gitHooksDir } from './git.js';
4
+ import { CONFIG_FILE_MAX_BYTES, findGitRoot } from './project.js';
5
+ import { entryKind, readRegularFile, writeRegularFile } from './safe-fs.js';
6
+ import { version } from './version.js';
7
+ /**
8
+ * The package spec every generated hook runs: the current minor range from package.json ("launch-doctor@^0.4.0"), so a
9
+ * hook never silently picks up a newer minor version (or a new major one) just because it was published to npm.
10
+ */
11
+ export function pinnedPackage() {
12
+ const [major, minor] = version().split('.');
13
+ return `launch-doctor@^${major}.${minor}.0`;
14
+ }
15
+ /**
16
+ * `--yes` so npx never stops to ask for permission when an AI tool or git runs it without a terminal. The package is in
17
+ * double quotes because "^" means something to cmd.exe and to zsh with extended globbing.
18
+ */
19
+ const claudeCommand = () => `npx --yes "${pinnedPackage()}" hook claude`;
20
+ const cursorCommand = () => `npx --yes "${pinnedPackage()}" hook cursor`;
21
+ const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
22
+ /**
23
+ * Read a JSON file. `null` = it doesn't exist, `'invalid'` = it isn't a JSON object, `'special'` = it is a link,
24
+ * a FIFO or another special file (never opened or written through, see src/safe-fs.ts).
25
+ */
26
+ function readJson(path) {
27
+ const kind = entryKind(path);
28
+ if (kind === 'missing')
29
+ return null;
30
+ const text = kind === 'file' ? readRegularFile(path, CONFIG_FILE_MAX_BYTES) : null;
31
+ if (text === null)
32
+ return 'special';
33
+ try {
34
+ const v = JSON.parse(text);
35
+ return isObject(v) ? v : 'invalid';
36
+ }
37
+ catch {
38
+ return 'invalid';
39
+ }
40
+ }
41
+ const SPECIAL = 'it is a link or a special file, not a regular file, so it was left alone';
42
+ function writeJson(path, data) {
43
+ mkdirSync(dirname(path), { recursive: true });
44
+ writeRegularFile(path, `${JSON.stringify(data, null, 2)}\n`);
45
+ }
46
+ /**
47
+ * Does this hook list already run a launch-doctor hook command? Any version counts, including the unpinned commands
48
+ * older releases wrote: re-running init never adds a second hook, and never rewrites one the user already has.
49
+ */
50
+ const hasOurCommand = (entries, tool) => new RegExp(String.raw `\blaunch-doctor(?:@[^\s"\\]+)?\\?"? hook ${tool}\b`).test(JSON.stringify(entries ?? null));
51
+ /** .claude/settings.json: a PostToolUse hook that checks every file Claude Code writes or edits. */
52
+ function setupClaude(root, result) {
53
+ const rel = '.claude/settings.json';
54
+ const path = join(root, rel);
55
+ const settings = readJson(path);
56
+ if (settings === 'special')
57
+ return void result.skipped.push([rel, SPECIAL]);
58
+ if (settings === 'invalid')
59
+ return void result.skipped.push([rel, "it isn't a valid JSON object, so it was left alone"]);
60
+ const data = settings ?? {};
61
+ const hooks = data.hooks ?? {};
62
+ if (!isObject(hooks))
63
+ return void result.skipped.push([rel, '"hooks" has an unexpected shape, so it was left alone']);
64
+ const post = hooks.PostToolUse ?? [];
65
+ if (!Array.isArray(post))
66
+ return void result.skipped.push([rel, '"hooks.PostToolUse" has an unexpected shape, so it was left alone']);
67
+ if (hasOurCommand(post, 'claude'))
68
+ return void result.skipped.push([rel, 'already set up']);
69
+ post.push({ matcher: 'Write|Edit|MultiEdit', hooks: [{ type: 'command', command: claudeCommand(), timeout: 60 }] });
70
+ writeJson(path, { ...data, hooks: { ...hooks, PostToolUse: post } });
71
+ (settings === null ? result.created : result.updated).push(rel);
72
+ }
73
+ /** .cursor/hooks.json: a stop hook that checks the files the agent changed before it finishes. */
74
+ function setupCursor(root, result) {
75
+ const rel = '.cursor/hooks.json';
76
+ const path = join(root, rel);
77
+ const config = readJson(path);
78
+ if (config === 'special')
79
+ return void result.skipped.push([rel, SPECIAL]);
80
+ if (config === 'invalid')
81
+ return void result.skipped.push([rel, "it isn't a valid JSON object, so it was left alone"]);
82
+ const data = config ?? {};
83
+ const hooks = data.hooks ?? {};
84
+ if (!isObject(hooks))
85
+ return void result.skipped.push([rel, '"hooks" has an unexpected shape, so it was left alone']);
86
+ const stop = hooks.stop ?? [];
87
+ if (!Array.isArray(stop))
88
+ return void result.skipped.push([rel, '"hooks.stop" has an unexpected shape, so it was left alone']);
89
+ if (hasOurCommand(stop, 'cursor'))
90
+ return void result.skipped.push([rel, 'already set up']);
91
+ stop.push({ command: cursorCommand(), timeout: 60 });
92
+ writeJson(path, { version: 1, ...data, hooks: { ...hooks, stop } });
93
+ (config === null ? result.created : result.updated).push(rel);
94
+ }
95
+ const MARK_START = '# >>> launch-doctor (added by "launch-doctor init --hooks") >>>';
96
+ const MARK_END = '# <<< launch-doctor <<<';
97
+ /**
98
+ * A value in single quotes for a POSIX shell. Nothing inside single quotes is expanded, so a folder named
99
+ * `app$(curl ...)` stays a folder name; a single quote in the value is written as '\''.
100
+ */
101
+ export function shellQuote(value) {
102
+ return `'${value.replace(/'/g, `'\\''`)}'`;
103
+ }
104
+ /**
105
+ * The block added to the pre-commit hook. Only exit code 1 (critical problems in the staged files)
106
+ * stops the commit. If the tool itself fails (no network for npx, for example) the commit goes ahead.
107
+ */
108
+ export function preCommitBlock(projectDir) {
109
+ // "./" keeps a folder named like an option ("-x", "--ci") from being read as one.
110
+ const dir = projectDir ? ` ${shellQuote(projectDir.startsWith('-') ? `./${projectDir}` : projectDir)}` : '';
111
+ return [
112
+ MARK_START,
113
+ '# Quiet when everything is fine: the report is only shown if something is wrong.',
114
+ `launch_doctor_output=$(npx --yes "${pinnedPackage()}"${dir} --staged --ci --no-file 2>&1)`,
115
+ 'launch_doctor_status=$?',
116
+ 'if [ "$launch_doctor_status" -ne 0 ]; then',
117
+ ' printf "%s\\n" "$launch_doctor_output" >&2',
118
+ 'fi',
119
+ 'if [ "$launch_doctor_status" -eq 1 ]; then',
120
+ ' echo "Launch Doctor found critical problems in the files you are committing. Fix them, or commit anyway with: git commit --no-verify" >&2',
121
+ ' exit 1',
122
+ 'fi',
123
+ MARK_END,
124
+ '',
125
+ ].join('\n');
126
+ }
127
+ /** A hook script a POSIX shell can run (so the block can be added to it). */
128
+ const SHELL_SHEBANG = /^#!\s*(?:\/usr\/bin\/env\s+(?:-S\s+)?)?(?:\S*\/)?(?:sh|bash|zsh|dash|ash)\b/;
129
+ /** .git/pre-commit (or wherever core.hooksPath points): checks the staged files. */
130
+ function setupPreCommit(root, result) {
131
+ const gitRoot = findGitRoot(root);
132
+ if (!gitRoot)
133
+ return void result.skipped.push(['pre-commit hook', "this folder isn't in a git repository"]);
134
+ const hooksPath = gitHooksDir(root);
135
+ if (!hooksPath)
136
+ return void result.skipped.push(['pre-commit hook', "couldn't find the git hooks folder"]);
137
+ const file = resolve(root, hooksPath, 'pre-commit');
138
+ const shown = relative(root, file).replace(/\\/g, '/');
139
+ const label = shown.startsWith('..') || isAbsolute(shown) ? file : shown;
140
+ // When the project is a subfolder of the repository, tell the CLI which folder to check.
141
+ // Real paths on both sides: git and the shell may spell the same folder differently (symlinks, Windows short names).
142
+ const projectDir = relative(realpathSync.native(gitRoot), realpathSync.native(root)).replace(/\\/g, '/');
143
+ const block = preCommitBlock(projectDir);
144
+ const kind = entryKind(file);
145
+ if (kind === 'missing') {
146
+ mkdirSync(dirname(file), { recursive: true });
147
+ writeRegularFile(file, `#!/bin/sh\n${block}`);
148
+ try {
149
+ chmodSync(file, 0o755);
150
+ }
151
+ catch {
152
+ // Windows has no file modes; Git for Windows runs the hook anyway.
153
+ }
154
+ return void result.created.push(label);
155
+ }
156
+ // A hook that is a symlink (to a script kept in the repository, say) is left for you to edit.
157
+ const text = kind === 'file' ? readRegularFile(file, CONFIG_FILE_MAX_BYTES) : null;
158
+ if (text === null) {
159
+ return void result.skipped.push([
160
+ label,
161
+ `${SPECIAL}; add "npx launch-doctor --staged --ci --no-file" to the script it runs yourself`,
162
+ ]);
163
+ }
164
+ if (text.includes(MARK_START))
165
+ return void result.skipped.push([label, 'already set up']);
166
+ const lines = text.split('\n');
167
+ const hasShebang = lines[0].startsWith('#!');
168
+ if (hasShebang && !SHELL_SHEBANG.test(lines[0])) {
169
+ return void result.skipped.push([
170
+ label,
171
+ 'it is not a shell script, so add "npx launch-doctor --staged --ci --no-file" to it yourself',
172
+ ]);
173
+ }
174
+ // Right after the shebang, so a later "exit 0" in the existing hook can't skip it.
175
+ const head = hasShebang ? [lines[0]] : [];
176
+ const rest = hasShebang ? lines.slice(1) : lines;
177
+ writeRegularFile(file, [...head, block.trimEnd(), ...rest].join('\n'));
178
+ result.updated.push(label);
179
+ }
180
+ /** Set up the Claude Code hook, the Cursor hook and the git pre-commit hook. Existing files are merged into, never replaced. */
181
+ export function setupHooks(root) {
182
+ const result = { created: [], updated: [], skipped: [] };
183
+ setupClaude(root, result);
184
+ setupCursor(root, result);
185
+ setupPreCommit(root, result);
186
+ return result;
187
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Gitignore-style matching for .launchdoctorignore (and for .gitignore when git isn't available).
3
+ *
4
+ * Rules are compiled once. A glob is matched by stepping through the path one character at a time while keeping
5
+ * the set of places in the pattern that could be reached (no backtracking), so the time is at most the path's
6
+ * length times the pattern's length, whatever the glob looks like. A glob turned into a regular expression could
7
+ * take exponential time (`a*a*a*...b`, `**` repeated 40 times), which let a crafted ignore file hang a scan.
8
+ */
9
+ type Token = {
10
+ kind: 'char';
11
+ c: string;
12
+ } | {
13
+ kind: 'one';
14
+ } | {
15
+ kind: 'star';
16
+ } | {
17
+ kind: 'globstar';
18
+ };
19
+ interface Glob {
20
+ tokens: Token[];
21
+ /** The longest run of plain characters in the glob: a path without it can't match, which is cheap to check. */
22
+ mustContain: string;
23
+ }
24
+ export interface IgnoreRule {
25
+ glob: Glob;
26
+ negate: boolean;
27
+ anchored: boolean;
28
+ anyDepth: boolean;
29
+ }
30
+ /** Parse gitignore-style text into rules. */
31
+ export declare function compileIgnore(text: string): IgnoreRule[];
32
+ /** Is `path` (relative, with "/") ignored by these rules? The last matching rule wins, as in git. */
33
+ export declare function matchesIgnore(rules: IgnoreRule[], path: string): boolean;
34
+ /** Minimal .gitignore matching for one path, used when git isn't available. Compiles each distinct text once. */
35
+ export declare function matchesGitignore(gitignore: string, path: string): boolean;
36
+ export {};
@@ -0,0 +1,164 @@
1
+ import { basename } from 'node:path';
2
+ /** `*` matches inside one folder name, `**` across folders, `?` one character. Runs of stars collapse. */
3
+ function compileGlob(text) {
4
+ const tokens = [];
5
+ for (let i = 0; i < text.length; i++) {
6
+ const ch = text[i];
7
+ if (ch === '*') {
8
+ let n = 1;
9
+ while (text[i + 1] === '*') {
10
+ n++;
11
+ i++;
12
+ }
13
+ const tok = { kind: n >= 2 ? 'globstar' : 'star' };
14
+ const prev = tokens.at(-1);
15
+ // "**" next to "*" or "**" (also "**/**", which only adds an optional folder) is just "**".
16
+ if (prev?.kind === 'globstar' || prev?.kind === 'star') {
17
+ if (tok.kind === 'globstar')
18
+ prev.kind = 'globstar';
19
+ continue;
20
+ }
21
+ if (tok.kind === 'globstar' && prev?.kind === 'char' && prev.c === '/' && tokens.at(-2)?.kind === 'globstar') {
22
+ tokens.pop();
23
+ continue;
24
+ }
25
+ tokens.push(tok);
26
+ }
27
+ else if (ch === '?') {
28
+ tokens.push({ kind: 'one' });
29
+ }
30
+ else {
31
+ tokens.push({ kind: 'char', c: ch });
32
+ }
33
+ }
34
+ let mustContain = '';
35
+ let run = '';
36
+ for (const t of [...tokens, { kind: 'one' }]) {
37
+ if (t.kind === 'char')
38
+ run += t.c;
39
+ else {
40
+ if (run.length > mustContain.length)
41
+ mustContain = run;
42
+ run = '';
43
+ }
44
+ }
45
+ return { tokens, mustContain };
46
+ }
47
+ /** Does `s` match the whole glob? */
48
+ function globMatch(glob, s) {
49
+ if (glob.mustContain && !s.includes(glob.mustContain))
50
+ return false;
51
+ const toks = glob.tokens;
52
+ const m = toks.length;
53
+ let cur = new Uint8Array(m + 1);
54
+ let next = new Uint8Array(m + 1);
55
+ const close = (set) => {
56
+ // A star can match nothing, so being before it also means being after it.
57
+ for (let i = 0; i < m; i++) {
58
+ const k = toks[i].kind;
59
+ if (set[i] && (k === 'star' || k === 'globstar'))
60
+ set[i + 1] = 1;
61
+ }
62
+ };
63
+ cur[0] = 1;
64
+ close(cur);
65
+ for (let p = 0; p < s.length; p++) {
66
+ const ch = s[p];
67
+ next.fill(0);
68
+ let any = false;
69
+ for (let i = 0; i < m; i++) {
70
+ if (!cur[i])
71
+ continue;
72
+ const t = toks[i];
73
+ if (t.kind === 'char') {
74
+ if (t.c === ch)
75
+ next[i + 1] = 1;
76
+ }
77
+ else if (t.kind === 'one') {
78
+ if (ch !== '/')
79
+ next[i + 1] = 1;
80
+ }
81
+ else if (t.kind === 'star') {
82
+ if (ch !== '/')
83
+ next[i] = 1;
84
+ }
85
+ else {
86
+ next[i] = 1;
87
+ }
88
+ }
89
+ close(next);
90
+ for (let i = 0; i <= m; i++) {
91
+ if (next[i]) {
92
+ any = true;
93
+ break;
94
+ }
95
+ }
96
+ if (!any)
97
+ return false;
98
+ [cur, next] = [next, cur];
99
+ }
100
+ return cur[m] === 1;
101
+ }
102
+ /** Parse gitignore-style text into rules. */
103
+ export function compileIgnore(text) {
104
+ const rules = [];
105
+ for (const raw of text.split(/\r?\n/)) {
106
+ let line = raw.trim();
107
+ if (!line || line.startsWith('#'))
108
+ continue;
109
+ const negate = line.startsWith('!');
110
+ if (negate)
111
+ line = line.slice(1);
112
+ line = line.replace(/\/+$/, '');
113
+ // "**/x" means "x in any folder".
114
+ let anyDepth = false;
115
+ while (line.startsWith('**/')) {
116
+ line = line.slice(3);
117
+ anyDepth = true;
118
+ }
119
+ const anchored = line.startsWith('/') || line.includes('/');
120
+ line = line.replace(/^\//, '');
121
+ if (!line)
122
+ continue;
123
+ rules.push({ glob: compileGlob(line), negate, anchored, anyDepth });
124
+ }
125
+ return rules;
126
+ }
127
+ /** Is `path` (relative, with "/") ignored by these rules? The last matching rule wins, as in git. */
128
+ export function matchesIgnore(rules, path) {
129
+ let ignored = false;
130
+ let segments = null;
131
+ for (const rule of rules) {
132
+ // A later rule can only change the answer if it is the opposite kind.
133
+ if (rule.negate !== ignored)
134
+ continue;
135
+ let hit;
136
+ if (!rule.anchored) {
137
+ segments ??= path.split('/');
138
+ hit = globMatch(rule.glob, basename(path)) || segments.some((seg) => globMatch(rule.glob, seg));
139
+ }
140
+ else if (rule.anyDepth) {
141
+ segments ??= path.split('/');
142
+ const segs = segments;
143
+ hit = segs.some((_, i) => globMatch(rule.glob, segs.slice(i).join('/')));
144
+ }
145
+ else {
146
+ hit = globMatch(rule.glob, path);
147
+ }
148
+ if (hit)
149
+ ignored = !rule.negate;
150
+ }
151
+ return ignored;
152
+ }
153
+ const compiled = new Map();
154
+ /** Minimal .gitignore matching for one path, used when git isn't available. Compiles each distinct text once. */
155
+ export function matchesGitignore(gitignore, path) {
156
+ let rules = compiled.get(gitignore);
157
+ if (!rules) {
158
+ rules = compileIgnore(gitignore);
159
+ if (compiled.size > 32)
160
+ compiled.clear();
161
+ compiled.set(gitignore, rules);
162
+ }
163
+ return matchesIgnore(rules, path);
164
+ }
package/dist/src/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { applyBaseline, fingerprint, loadBaseline } from './baseline.js';
2
+ import { accessCheck } from './checks/access.js';
2
3
  import { costsCheck } from './checks/costs.js';
3
4
  import { databaseCheck } from './checks/database.js';
4
5
  import { emailCheck } from './checks/email.js';
@@ -10,6 +11,7 @@ import { secretsCheck } from './checks/secrets.js';
10
11
  import { overall, scoreCategory, toGrade } from './grade.js';
11
12
  import { scanHistory } from './history.js';
12
13
  import { ProjectContext } from './project.js';
14
+ import { sanitizeReport } from './sanitize.js';
13
15
  import { plural } from './util.js';
14
16
  import { version } from './version.js';
15
17
  function notRun(note) {
@@ -18,6 +20,7 @@ function notRun(note) {
18
20
  export const CHECKS = [
19
21
  secretsCheck,
20
22
  databaseCheck,
23
+ accessCheck,
21
24
  paymentsCheck,
22
25
  costsCheck,
23
26
  emailCheck,
@@ -35,9 +38,13 @@ export function isInlineIgnored(ctx, f) {
35
38
  if (!file)
36
39
  return false;
37
40
  const lines = file.content.split(/\r?\n/);
38
- for (const text of [lines[loc.line - 1], lines[loc.line - 2]]) {
41
+ for (const lineNo of [loc.line, loc.line - 1]) {
42
+ const text = lines[lineNo - 1];
39
43
  if (!text)
40
44
  continue;
45
+ // With --config-from, a comment on a line added since that ref is not trusted (a pull request could add it).
46
+ if (ctx.addedSinceConfigRef(loc.file, lineNo))
47
+ continue;
41
48
  for (const m of text.matchAll(INLINE_IGNORE)) {
42
49
  if (m[1].split(/\s*,\s*/).includes(f.id))
43
50
  return true;
@@ -51,6 +58,10 @@ export async function runDoctor(root, options = {}) {
51
58
  const unknown = [...(options.only ?? []), ...(options.skip ?? [])].filter((id) => !CATEGORY_IDS().includes(id));
52
59
  if (unknown.length)
53
60
  throw new Error(`Unknown category: ${unknown.join(', ')}. Use one of: ${CATEGORY_IDS().join(', ')}`);
61
+ // Reporting on a few files is for quick checks, so it never waits for DNS.
62
+ if (options.onlyFiles)
63
+ options = { ...options, offline: true };
64
+ const only = options.onlyFiles ? new Set(options.onlyFiles) : null;
54
65
  const ctx = new ProjectContext(root, options);
55
66
  const categories = [];
56
67
  let ignored = 0;
@@ -90,6 +101,16 @@ export async function runDoctor(root, options = {}) {
90
101
  out.passed.push('Git history scan stopped early because the history is very large');
91
102
  }
92
103
  }
104
+ // Reporting on some files only: keep findings in those files. "Passed" lines and the checklist describe
105
+ // the whole project, so they would mislead here.
106
+ if (only) {
107
+ out = {
108
+ ...out,
109
+ findings: out.findings.filter((f) => f.location && only.has(f.location.file)),
110
+ manual: [],
111
+ passed: [],
112
+ };
113
+ }
93
114
  // Inline: a "launch-doctor-ignore <id>" comment on the finding's line or the line above.
94
115
  const inline = out.findings.filter((f) => isInlineIgnored(ctx, f));
95
116
  if (inline.length) {
@@ -129,19 +150,23 @@ export async function runDoctor(root, options = {}) {
129
150
  stack: ctx.stack(),
130
151
  filesScanned: ctx.files.length,
131
152
  truncated: ctx.truncated,
153
+ ...(ctx.byteLimitReached ? { byteLimitReached: true } : {}),
132
154
  ignored,
133
155
  unknownIgnoreIds,
156
+ ...(ctx.ignoreLinesSkipped ? { ignoreLinesSkipped: ctx.ignoreLinesSkipped } : {}),
134
157
  ...(ctx.nestedRepos.length ? { nestedRepos: ctx.nestedRepos } : {}),
158
+ ...(options.onlyFiles ? { partial: { files: options.onlyFiles } } : {}),
135
159
  ...summary,
136
160
  categories,
137
161
  generatedAt: new Date().toISOString(),
138
162
  };
139
163
  if (options.baseline !== false) {
140
- const baseline = loadBaseline(ctx.root);
164
+ const baseline = loadBaseline(ctx.root, options.configFrom);
141
165
  if (baseline)
142
166
  applyBaseline(report, baseline);
143
167
  }
144
- return report;
168
+ // Text from the scanned files (names, paths) can hold terminal escape sequences; none reach any output.
169
+ return sanitizeReport(report);
145
170
  }
146
171
  export { renderFixes } from './fixes.js';
147
172
  export { postPrFeedback, prContextFromEnv, renderPrComment } from './github.js';
@@ -1,9 +1,39 @@
1
1
  /** The same workflow as the README's "CI integration" example. */
2
2
  export declare const WORKFLOW_TEMPLATE = "name: Launch Doctor\non: [pull_request]\njobs:\n check:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v7\n - uses: actions/setup-node@v7\n with:\n node-version: 22\n - run: npx launch-doctor --ci\n";
3
3
  export declare const IGNORE_TEMPLATE = "# .launchdoctorignore: things Launch Doctor should leave alone.\n# One entry per line. Lines starting with # are comments.\n\n# Finding ids (each fix in LAUNCH_FIXES.md shows its id). For example:\n# no-error-tracking\n# no-account-deletion\n\n# Folders or files to skip (anything with / * or . is a path):\n# legacy/\n# scripts/seed.ts\n# **/*.fixture.ts\n\n# To silence one finding in one place, add a comment on that line or the line above:\n# // launch-doctor-ignore stripe-test-key\n";
4
+ export declare const MONITOR_WORKFLOW = ".github/workflows/launch-doctor-monitor.yml";
5
+ /**
6
+ * The package spec the monitor runs: at least this version (it needs --record), and no newer major (or, before
7
+ * 1.0, minor) version unless you change it, like the hooks.
8
+ */
9
+ export declare function monitorPackage(): string;
10
+ /** The branch the monitor keeps the grade history and the badge on. */
11
+ export declare const GRADES_BRANCH = "launch-doctor-grades";
12
+ /** Where the README badge points: the badge file on the grades branch. */
13
+ export declare function badgeUrl(repo?: string): string;
14
+ /** "owner/repo" when `origin` is a GitHub repository, otherwise null. */
15
+ export declare function githubRepo(remoteUrl: string | null): string | null;
16
+ /**
17
+ * `init --monitor`: re-check the project every week and keep the grade history and the badge up to date.
18
+ *
19
+ * - The history is read from the launch-doctor-grades branch first, so --record adds to it.
20
+ * - The project scan runs with --record and --ci, so a new critical problem fails the run and GitHub emails you.
21
+ * - With the repository variable LAUNCH_DOCTOR_URL set, the deployed site is checked too (the URL is passed through
22
+ * an environment variable, never pasted into the script).
23
+ * - grades.json and badge.svg are committed to the launch-doctor-grades branch (an orphan branch with only those two
24
+ * files, created on the first run), even when a check failed, so the history shows the bad weeks as well. Nothing
25
+ * is ever committed to the default branch, so this works with a protected main and adds no commits to it. Pushes
26
+ * made with the workflow's token don't start other workflows.
27
+ */
28
+ export declare function monitorTemplate(): string;
4
29
  export interface InitResult {
5
30
  created: string[];
6
31
  skipped: string[];
7
32
  }
8
- /** Create the starter files in `root`. Existing files are never overwritten. */
9
- export declare function runInit(root: string): InitResult;
33
+ /**
34
+ * Create the starter files in `root`, or with `monitor` only the weekly monitoring workflow. Existing files are
35
+ * never overwritten.
36
+ */
37
+ export declare function runInit(root: string, { monitor }?: {
38
+ monitor?: boolean | undefined;
39
+ }): InitResult;