@docker-doctor/cli 0.4.3 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.cjs +2 -2
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +11 -4
- package/dist/index.d.mts +11 -4
- package/dist/index.mjs +1 -1
- package/dist/{src-TK9DRoRo.mjs → src-CvOv-hL3.mjs} +85 -69
- package/dist/src-CvOv-hL3.mjs.map +1 -0
- package/dist/{src-ILbJuJmE.cjs → src-DwuAaQcq.cjs} +89 -67
- package/dist/src-DwuAaQcq.cjs.map +1 -0
- package/package.json +1 -1
- package/dist/src-ILbJuJmE.cjs.map +0 -1
- package/dist/src-TK9DRoRo.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-CvOv-hL3.mjs","names":["parseYaml"],"sources":["../package.json","../../core/src/project-info/discover.ts","../../core/src/parsers/dockerfile-parser.ts","../../core/src/errors/config-error.ts","../../core/src/errors/parse-error.ts","../../core/src/parsers/compose-parser.ts","../../core/src/parsers/exec-form.ts","../../core/src/parsers/image-ref.ts","../../core/src/rules/create-diagnostic.ts","../../core/src/rules/best-practices.ts","../../core/src/rules/compose.ts","../../core/src/rules/image-size.ts","../../core/src/rules/performance.ts","../../core/src/rules/security.ts","../../core/src/rules/index.ts","../../core/src/runners/resolve-severity.ts","../../core/src/runners/dockerfile-runner.ts","../../core/src/runners/compose-runner.ts","../../core/src/schemas/config.ts","../../core/src/config/unknown-keys.ts","../../core/src/config/loader.ts","../../core/src/scoring.ts","../../core/src/report.ts"],"sourcesContent":["","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport type { ProjectInfo } from \"../types/index\";\n\nconst walk = async (\n dir: string,\n fileList: string[] = []\n): Promise<string[]> => {\n const files = await fs.readdir(dir, { withFileTypes: true });\n await Promise.all(\n files.map(async (file) => {\n const filePath = path.join(dir, file.name);\n if (file.isDirectory()) {\n if (\n file.name === \"node_modules\" ||\n file.name === \".git\" ||\n file.name === \".next\" ||\n file.name === \"dist\" ||\n file.name === \".turbo\"\n ) {\n return;\n }\n await walk(filePath, fileList);\n } else {\n fileList.push(filePath);\n }\n })\n );\n return fileList;\n};\n\nexport const discoverProject = async (\n rootDir: string\n): Promise<ProjectInfo> => {\n const allFiles = await walk(rootDir);\n const dockerfiles: string[] = [];\n const composeFiles: string[] = [];\n const dockerignores: string[] = [];\n\n for (const file of allFiles) {\n const base = path.basename(file).toLowerCase();\n\n if (base === \".dockerignore\") {\n dockerignores.push(path.relative(rootDir, file));\n }\n\n // Match Dockerfile, Dockerfile.*, *.dockerfile\n if (\n base === \"dockerfile\" ||\n base.startsWith(\"dockerfile.\") ||\n base.endsWith(\".dockerfile\")\n ) {\n dockerfiles.push(path.relative(rootDir, file));\n }\n\n // Match docker-compose.yml, docker-compose.*.yml, compose.yml, compose.*.yml, and yaml extensions\n if (\n base === \"docker-compose.yml\" ||\n base === \"docker-compose.yaml\" ||\n base === \"compose.yml\" ||\n base === \"compose.yaml\" ||\n ((base.startsWith(\"docker-compose.\") || base.startsWith(\"compose.\")) &&\n (base.endsWith(\".yml\") || base.endsWith(\".yaml\")))\n ) {\n composeFiles.push(path.relative(rootDir, file));\n }\n }\n\n // The traversal is concurrent, so results arrive in I/O-completion order.\n // Sort at the boundary so identical scans produce byte-identical JSON\n // reports and stable PR-comment row ordering. The default comparator is\n // deliberate: localeCompare would make the order machine-dependent, which\n // is the class of bug this sorting exists to fix.\n return {\n composeFiles: composeFiles.toSorted(),\n dockerfiles: dockerfiles.toSorted(),\n dockerignores: dockerignores.toSorted(),\n };\n};\n","import type { DockerfileInstruction } from \"../types/index\";\n\nconst DOCKERFILE_KEYWORDS = new Set([\n \"ADD\",\n \"ARG\",\n \"CMD\",\n \"COPY\",\n \"ENTRYPOINT\",\n \"ENV\",\n \"EXPOSE\",\n \"FROM\",\n \"HEALTHCHECK\",\n \"LABEL\",\n \"MAINTAINER\",\n \"ONBUILD\",\n \"RUN\",\n \"SHELL\",\n \"STOPSIGNAL\",\n \"USER\",\n \"VOLUME\",\n \"WORKDIR\",\n]);\n\n// The only instructions BuildKit supports heredocs on.\nconst HEREDOC_INSTRUCTIONS = new Set([\"ADD\", \"COPY\", \"RUN\"]);\n\nconst INSTRUCTION_LINE_RE = /^(?<inst>[A-Za-z]+)\\s+(?<args>.*)$/u;\n\n// Matches a BuildKit heredoc opener like <<EOF, <<-EOF, <<'EOF', <<\"EOF\".\n// Three constraints keep this from matching shell constructs that aren't\n// Dockerfile heredocs: (1) `<<` must be preceded by start-of-line or\n// whitespace, so `1<<3` (shell arithmetic) doesn't match and every\n// character-shifted alignment inside `<<<` (here-strings) fails too; (2) the\n// delimiter must be attached directly to `<<` with no whitespace, so\n// `$((1 << 3))` and shell `cat << EOF` (both redirection, not a Dockerfile\n// heredoc) don't match; (3) callers only invoke this for RUN/COPY/ADD, the\n// only instructions BuildKit supports heredocs on. Known accepted\n// limitation: `RUN echo \"text <<EOF more\"` still matches inside a quoted\n// string — correctly rejecting that needs a shell lexer, out of scope here.\n// Global so a single line (e.g. `COPY <<FILE1 <<FILE2 /dest/`) can open more\n// than one.\nconst HEREDOC_OPENER_RE =\n /(?<=^|\\s)<<-?(?<quote>['\"]?)(?<delim>\\w+)\\k<quote>/gu;\n\ninterface ParserState {\n instructions: DockerfileInstruction[];\n currentInstruction: string;\n currentArgs: string;\n startLine: number;\n rawAccumulator: string[];\n // FIFO of heredoc delimiters still open for the current instruction, in\n // the order they were opened (closed in the same order).\n heredocQueue: string[];\n}\n\nconst createParserState = (): ParserState => ({\n currentArgs: \"\",\n currentInstruction: \"\",\n heredocQueue: [],\n instructions: [],\n rawAccumulator: [],\n startLine: 0,\n});\n\nconst closeInstruction = (state: ParserState): void => {\n if (state.currentInstruction) {\n state.instructions.push({\n args: state.currentArgs,\n instruction: state.currentInstruction,\n line: state.startLine,\n raw: state.rawAccumulator.join(\"\\n\"),\n });\n }\n state.currentInstruction = \"\";\n state.currentArgs = \"\";\n state.rawAccumulator = [];\n};\n\nconst matchInstructionKeyword = (\n lineContent: string\n): { instruction: string; args: string } | null => {\n const match = lineContent.match(INSTRUCTION_LINE_RE);\n const matchedWord = match?.groups?.inst.toUpperCase();\n if (matchedWord && DOCKERFILE_KEYWORDS.has(matchedWord)) {\n return { args: match?.groups?.args ?? \"\", instruction: matchedWord };\n }\n\n const word = lineContent.trim().toUpperCase();\n if (DOCKERFILE_KEYWORDS.has(word)) {\n return { args: \"\", instruction: word };\n }\n\n return null;\n};\n\nconst findHeredocDelimiters = (lineContent: string): string[] =>\n [...lineContent.matchAll(HEREDOC_OPENER_RE)].map(\n (m) => m.groups?.delim ?? \"\"\n );\n\n// Heredoc body lines are never treated as instructions (not even comment\n// lines, which are shell-comment content here) — they are folded verbatim\n// into the owning instruction's args until the delimiter line closes the\n// (possibly multiple) open heredoc(s), in the order they were opened.\nconst processHeredocLine = (state: ParserState, trimmed: string): void => {\n if (trimmed === state.heredocQueue[0]) {\n state.heredocQueue.shift();\n } else {\n state.currentArgs += (state.currentArgs ? \" \" : \"\") + trimmed;\n }\n\n if (state.heredocQueue.length === 0) {\n // Last open heredoc just closed: the instruction ends here.\n closeInstruction(state);\n }\n};\n\nconst processInstructionLine = (\n state: ParserState,\n trimmed: string,\n lineNum: number\n): void => {\n let lineContent = trimmed;\n\n const hasContinuation = lineContent.endsWith(\"\\\\\");\n if (hasContinuation) {\n lineContent = lineContent.slice(0, -1).trim();\n }\n\n if (state.currentInstruction) {\n state.currentArgs += (state.currentArgs ? \" \" : \"\") + lineContent;\n } else {\n state.startLine = lineNum;\n // Match the first instruction word (e.g. FROM, RUN, COPY)\n const matched = matchInstructionKeyword(lineContent);\n if (matched) {\n state.currentInstruction = matched.instruction;\n state.currentArgs = matched.args;\n }\n }\n\n if (HEREDOC_INSTRUCTIONS.has(state.currentInstruction)) {\n state.heredocQueue.push(...findHeredocDelimiters(lineContent));\n }\n\n if (state.heredocQueue.length > 0) {\n // A heredoc opener implies continuation even without a trailing\n // backslash — keep accumulating until every opened delimiter closes.\n return;\n }\n\n if (!hasContinuation) {\n closeInstruction(state);\n }\n};\n\nexport const parseDockerfile = (content: string): DockerfileInstruction[] => {\n const state = createParserState();\n const lines = content.split(/\\r?\\n/u);\n\n for (const [i, rawLine] of lines.entries()) {\n const trimmed = rawLine.trim();\n const lineNum = i + 1;\n const insideHeredoc = state.heredocQueue.length > 0;\n\n // Comment lines are dropped by Docker's parser even mid-continuation, so\n // keep them out of args AND `raw` — raw-based rules must not see them.\n // Heredoc bodies are exempt: a leading `#` there is shell content.\n if (!insideHeredoc && trimmed.startsWith(\"#\")) {\n continue;\n }\n\n // Skip empty lines if not in a multi-line block\n if (!state.currentInstruction && !insideHeredoc && trimmed === \"\") {\n continue;\n }\n\n state.rawAccumulator.push(rawLine);\n\n if (insideHeredoc) {\n processHeredocLine(state, trimmed);\n } else {\n processInstructionLine(state, trimmed, lineNum);\n }\n }\n\n // EOF: an unterminated heredoc (or a trailing backslash continuation)\n // still emits whatever was accumulated so far, rather than dropping it.\n closeInstruction(state);\n\n return state.instructions;\n};\n","export class ConfigError extends Error {\n readonly _tag = \"ConfigError\" as const;\n\n constructor(options: { readonly message: string }) {\n super(options.message);\n this.name = \"ConfigError\";\n }\n}\n","export class ParseError extends Error {\n readonly _tag = \"ParseError\" as const;\n readonly file: string;\n\n constructor(options: { readonly file: string; readonly message: string }) {\n super(options.message);\n this.name = \"ParseError\";\n this.file = options.file;\n }\n}\n","import {\n isAlias,\n isMap,\n isScalar,\n isSeq,\n LineCounter,\n parse,\n parseDocument,\n} from \"yaml\";\n\nimport { ParseError } from \"../errors\";\nimport type { ComposeLocator } from \"../types/index\";\n\nexport const parseCompose = (content: string, filepath: string): unknown => {\n try {\n // Compose files rely on YAML 1.1 merge keys (`<<: *anchor`); yaml's\n // default 1.2 schema leaves `<<` as a literal key without this option.\n return parse(content, { merge: true });\n } catch (error: unknown) {\n throw new ParseError({\n file: filepath,\n message: error instanceof Error ? error.message : String(error),\n });\n }\n};\n\n/**\n * Builds a {@link ComposeLocator} over the same source text a compose object\n * was parsed from, so rules can attach line numbers to their diagnostics.\n *\n * Keys pulled in via YAML merge keys (`<<: *anchor`) have no concrete node\n * at the merge site, so paths through them resolve to `undefined` — callers\n * fall back to an unnumbered diagnostic, which matches the old behavior.\n */\nexport const createComposeLocator = (content: string): ComposeLocator => {\n const lineCounter = new LineCounter();\n const doc = parseDocument(content, { lineCounter, merge: true });\n\n return (path) => {\n let node: unknown = doc.contents;\n let offset: number | undefined;\n\n for (const segment of path) {\n if (isAlias(node)) {\n node = node.resolve(doc);\n }\n if (isMap(node)) {\n const pair = node.items.find(\n (item) =>\n isScalar(item.key) && String(item.key.value) === String(segment)\n );\n if (!pair || !isScalar(pair.key)) {\n return;\n }\n offset = pair.key.range?.[0];\n node = pair.value;\n } else if (isSeq(node) && typeof segment === \"number\") {\n const item = node.items[segment];\n if (item === undefined || item === null) {\n return;\n }\n offset = (item as { range?: [number, number, number] | null })\n .range?.[0];\n node = item;\n } else {\n return;\n }\n }\n\n return offset === undefined ? undefined : lineCounter.linePos(offset).line;\n };\n};\n","// Exec form is a JSON array of strings: CMD [\"node\", \"index.js\"]. Docker only\n// treats bracket-wrapped args as exec form when they parse as one — anything\n// else (e.g. CMD [node, index.js], whose tokens are unquoted) falls back to\n// shell form under `/bin/sh -c`.\n//\n// An array holding a non-string element (CMD [1, 2]) is null here too. Docker\n// rejects that outright rather than falling back, so the Dockerfile is broken\n// either way and a shell-form diagnostic still points at the offending line.\nexport const parseExecForm = (args: string): string[] | null => {\n const trimmed = args.trim();\n // Cheap reject first: most instructions are shell form, and reaching them\n // through a thrown JSON.parse would be far more expensive.\n if (!trimmed.startsWith(\"[\")) {\n return null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n return null;\n }\n\n if (!Array.isArray(parsed)) {\n return null;\n }\n if (!parsed.every((el): el is string => typeof el === \"string\")) {\n return null;\n }\n\n return parsed;\n};\n","import type { DockerfileInstruction } from \"../types/index\";\n\nexport interface ImageRef {\n registry?: string;\n name: string;\n tag?: string;\n digest?: string;\n isVariable: boolean;\n}\n\nexport const parseImageRef = (ref: string): ImageRef => {\n if (ref.includes(\"${\") || ref.startsWith(\"$\")) {\n return { isVariable: true, name: ref };\n }\n\n let remainder = ref;\n let digest: string | undefined;\n\n const atIndex = remainder.indexOf(\"@\");\n if (atIndex !== -1) {\n digest = remainder.slice(atIndex + 1);\n remainder = remainder.slice(0, atIndex);\n }\n\n let tag: string | undefined;\n const lastColonIndex = remainder.lastIndexOf(\":\");\n const lastSlashIndex = remainder.lastIndexOf(\"/\");\n\n if (lastColonIndex !== -1 && lastColonIndex > lastSlashIndex) {\n tag = remainder.slice(lastColonIndex + 1);\n remainder = remainder.slice(0, lastColonIndex);\n }\n\n let registry: string | undefined;\n const firstSlashIndex = remainder.indexOf(\"/\");\n if (firstSlashIndex !== -1) {\n const firstSegment = remainder.slice(0, firstSlashIndex);\n if (\n firstSegment.includes(\".\") ||\n firstSegment.includes(\":\") ||\n firstSegment === \"localhost\"\n ) {\n registry = firstSegment;\n remainder = remainder.slice(firstSlashIndex + 1);\n }\n }\n\n return {\n digest,\n isVariable: false,\n name: remainder,\n registry,\n tag,\n };\n};\n\nexport interface FromArgs {\n base: string | null;\n stage: string | null;\n}\n\n// FROM [--flags] <image|stage> [AS <stage>], flags in any position.\nexport const parseFromArgs = (args: string): FromArgs => {\n const parts = args.split(/\\s+/u).filter(Boolean);\n const asIndex = parts.findIndex((p) => p.toLowerCase() === \"as\");\n const imageParts = asIndex === -1 ? parts : parts.slice(0, asIndex);\n return {\n base: imageParts.find((p) => !p.startsWith(\"--\")) ?? null,\n stage: asIndex === -1 ? null : (parts[asIndex + 1] ?? null),\n };\n};\n\n// The reserved empty base, not a real image: nothing to pin a tag on, no\n// distribution to slim down, and no image config to inherit. One definition\n// so the rules cannot disagree about a given FROM line.\nexport const isScratch = (base: string | null): boolean =>\n base?.toLowerCase() === \"scratch\";\n\nexport const collectStageAliases = (\n instructions: DockerfileInstruction[]\n): Set<string> => {\n const aliases = new Set<string>();\n\n for (const inst of instructions) {\n if (inst.instruction !== \"FROM\") {\n continue;\n }\n\n const { stage } = parseFromArgs(inst.args);\n if (stage) {\n aliases.add(stage.toLowerCase());\n }\n }\n\n return aliases;\n};\n","import type { Diagnostic, DiagnosticSeverity } from \"../types/index\";\n\nexport const createDiagnostic = (\n file: string,\n ruleKey: string,\n severity: DiagnosticSeverity,\n message: string,\n help: string,\n line?: number\n): Diagnostic => ({ file, help, line, message, rule: ruleKey, severity });\n","import { parseExecForm } from \"../parsers/exec-form\";\nimport { isScratch, parseFromArgs } from \"../parsers/image-ref\";\nimport type { Diagnostic, DockerfileRule } from \"../types/index\";\nimport { createDiagnostic } from \"./create-diagnostic\";\n\nexport const requireHealthcheck: DockerfileRule = {\n category: \"Best Practices\",\n check(instructions, file) {\n const hasHealthcheck = instructions.some(\n (inst) => inst.instruction === \"HEALTHCHECK\"\n );\n\n // Only suggest healthcheck if it has exposed ports or command lines indicating it runs an app\n const hasExposedPortsOrEntry = instructions.some(\n (inst) =>\n inst.instruction === \"EXPOSE\" ||\n inst.instruction === \"CMD\" ||\n inst.instruction === \"ENTRYPOINT\"\n );\n\n if (!hasHealthcheck && hasExposedPortsOrEntry) {\n return [\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n \"No HEALTHCHECK instruction found. Containers running services should expose healthchecks to enable auto-healing.\",\n this.help,\n 1\n ),\n ];\n }\n return [];\n },\n defaultSeverity: \"info\",\n help: \"Use HEALTHCHECK (e.g., `HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost/ || exit 1`) so Docker can monitor the container's live status.\",\n key: \"docker-doctor/require-healthcheck\",\n message: \"Add a HEALTHCHECK instruction\",\n};\n\nexport const preferCopyOverAdd: DockerfileRule = {\n category: \"Best Practices\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n\n for (const inst of instructions) {\n if (inst.instruction === \"ADD\") {\n const parts = inst.args.split(/\\s+/u);\n const src = parts.find((p) => !p.startsWith(\"--\"));\n\n if (!src) {\n continue;\n }\n\n // If it's not a remote url (handled by security/no-add-remote) and not a compressed file\n const isRemote =\n src.startsWith(\"http://\") || src.startsWith(\"https://\");\n const isArchive =\n src.endsWith(\".tar\") ||\n src.endsWith(\".tar.gz\") ||\n src.endsWith(\".tgz\") ||\n src.endsWith(\".zip\");\n\n if (!isRemote && !isArchive) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `ADD instruction used for regular files: '${inst.args}'. COPY is simpler and less prone to magic side effects.`,\n this.help,\n inst.line\n )\n );\n }\n }\n }\n\n return diagnostics;\n },\n defaultSeverity: \"warning\",\n help: \"Use COPY instead of ADD unless you explicitly need auto-extraction of local compressed archives (tar, zip, etc.).\",\n key: \"docker-doctor/prefer-copy-over-add\",\n message: \"Prefer COPY over ADD\",\n};\n\nexport const useExecForm: DockerfileRule = {\n category: \"Best Practices\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n\n for (const inst of instructions) {\n const takesExecForm =\n inst.instruction === \"CMD\" || inst.instruction === \"ENTRYPOINT\";\n // Bracket-wrapped args that are not a JSON string array still run under\n // /bin/sh -c, so they count as shell form.\n if (takesExecForm && parseExecForm(inst.args) === null) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `${inst.instruction} instruction uses shell form instead of exec form. In shell form, the command runs under '/bin/sh -c', which does not pass signals to child processes.`,\n this.help,\n inst.line\n )\n );\n }\n }\n\n return diagnostics;\n },\n defaultSeverity: \"warning\",\n help: 'Write CMD/ENTRYPOINT instructions as JSON arrays (e.g. `ENTRYPOINT [\"node\", \"index.js\"]`) so OS signals (like SIGTERM) are forwarded correctly.',\n key: \"docker-doctor/use-exec-form\",\n message: \"Use exec form for CMD and ENTRYPOINT\",\n};\n\nexport const requireLabels: DockerfileRule = {\n category: \"Best Practices\",\n check(instructions, file) {\n const hasLabel = instructions.some((inst) => inst.instruction === \"LABEL\");\n if (!hasLabel) {\n return [\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n \"No LABEL metadata was found in this Dockerfile. Adding labels helps identify build information, maintainers, and descriptions.\",\n this.help,\n 1\n ),\n ];\n }\n return [];\n },\n defaultSeverity: \"info\",\n help: 'Use LABEL instructions (e.g. `LABEL org.opencontainers.image.authors=\"...\"`) to document ownership, license, version, and build info.',\n key: \"docker-doctor/require-labels\",\n message: \"Add LABEL metadata to images\",\n};\n\nexport const combineAptUpdateInstall: DockerfileRule = {\n category: \"Best Practices\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n for (const inst of instructions) {\n if (inst.instruction === \"RUN\") {\n const hasUpdate = inst.args.includes(\"apt-get update\");\n const hasInstall = inst.args.includes(\"apt-get install\");\n\n if (hasUpdate && !hasInstall) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n \"RUN apt-get update used without apt-get install in the same instruction. This can cause caching issues and build failures.\",\n this.help,\n inst.line\n )\n );\n } else if (hasInstall && !hasUpdate) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n \"RUN apt-get install used without apt-get update in the same instruction. Always combine them to ensure up-to-date package installation.\",\n this.help,\n inst.line\n )\n );\n }\n }\n }\n return diagnostics;\n },\n defaultSeverity: \"warning\",\n help: \"Combine `apt-get update` and `apt-get install` in the same RUN instruction (e.g. `RUN apt-get update && apt-get install -y --no-install-recommends <package> && rm -rf /var/lib/apt/lists/*`).\",\n key: \"docker-doctor/combine-apt-update-install\",\n message: \"Combine apt-get update and apt-get install\",\n};\n\n// An actual pipefail setting: the option must appear adjacent to its flag\n// (`-o pipefail`, `-euo pipefail`, repeated `-o errexit -o pipefail`, or a\n// shell invoked with `-o pipefail`). Matching the flag directly (rather than\n// a shell name) also works inside joined exec-form argv, and cannot backtrack\n// pathologically. Known limitation: the word inside quotes (e.g.\n// `echo \"set -o pipefail\" >> .bashrc`) still matches — same class as the\n// existing test.todo for quoted pipes.\nexport const PIPEFAIL_SETTING_RE = /(?:^|\\s)-[A-Za-z]*o\\s+pipefail\\b/u;\n\n// A RUN line uses a pipe: a single `|` not part of `||`.\nconst HAS_PIPE_RE = /(?<!\\|)\\|(?!\\|)/u;\n\n// SHELL takes exec form; joined, its argv is the prefix every shell-form RUN\n// is wrapped in (e.g. /bin/bash -o pipefail -c). Any other spelling is\n// rejected by Docker, so it cannot be enabling pipefail.\nconst shellDirectiveEnablesPipefail = (args: string): boolean => {\n const argv = parseExecForm(args);\n return argv !== null && PIPEFAIL_SETTING_RE.test(argv.join(\" \"));\n};\n\nexport const usePipefail: DockerfileRule = {\n category: \"Best Practices\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n // FROM <previous stage> inherits that stage's image config — SHELL\n // included (verified against BuildKit); FROM a fresh base image, or the\n // reserved empty stage `scratch`, resets it to the Docker default. A\n // SHELL instruction replaces it for the rest of the current stage.\n // NOTE: FROM ${VAR} (variable base) misses the map lookup and silently\n // resets — fails safe (extra warning, never a missed one).\n const stagePipefail = new Map<string, boolean>();\n let shellHasPipefail = false;\n let currentStage: string | null = null;\n for (const inst of instructions) {\n if (inst.instruction === \"FROM\") {\n const { base, stage } = parseFromArgs(inst.args);\n // Only a reference to an earlier stage carries state forward; a real\n // base image, scratch, or a variable we cannot resolve resets it.\n const parentStage = isScratch(base)\n ? null\n : (base?.toLowerCase() ?? null);\n shellHasPipefail =\n parentStage !== null && stagePipefail.get(parentStage) === true;\n currentStage = stage?.toLowerCase() ?? null;\n if (currentStage) {\n stagePipefail.set(currentStage, shellHasPipefail);\n }\n continue;\n }\n if (inst.instruction === \"SHELL\") {\n shellHasPipefail = shellDirectiveEnablesPipefail(inst.args);\n if (currentStage) {\n stagePipefail.set(currentStage, shellHasPipefail);\n }\n continue;\n }\n if (inst.instruction !== \"RUN\") {\n continue;\n }\n const { args } = inst;\n if (!HAS_PIPE_RE.test(args)) {\n continue;\n }\n // SHELL only applies to shell-form RUN; exec-form RUN runs its own\n // argv directly, so check the argv for pipefail instead.\n const execArgv = parseExecForm(args);\n const pipefailConfigured =\n execArgv === null\n ? shellHasPipefail || PIPEFAIL_SETTING_RE.test(args)\n : PIPEFAIL_SETTING_RE.test(execArgv.join(\" \"));\n if (!pipefailConfigured) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n \"RUN instruction uses a pipe (|) but does not configure 'pipefail'. If a command in the pipe fails, the step may still succeed silently.\",\n this.help,\n inst.line\n )\n );\n }\n }\n return diagnostics;\n },\n defaultSeverity: \"warning\",\n help: 'Prepend `set -o pipefail &&` to pipe commands, use exec form with a shell that supports it (e.g., `RUN [\"/bin/bash\", \"-c\", \"set -o pipefail && ...\"]`), or set `SHELL [\"/bin/bash\", \"-o\", \"pipefail\", \"-c\"]` at the top of the stage.',\n key: \"docker-doctor/use-pipefail\",\n message: \"Use pipefail to catch pipeline command failures\",\n};\n\nexport const absoluteWorkdir: DockerfileRule = {\n category: \"Best Practices\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n for (const inst of instructions) {\n if (inst.instruction === \"WORKDIR\") {\n const path = inst.args.trim();\n const isAbsolute = /^(?:\\/|\\\\|\\$|[a-zA-Z]:)/u.test(path);\n\n if (!isAbsolute) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `WORKDIR specifies a relative path '${path}'. For clarity and reliability, always use absolute paths.`,\n this.help,\n inst.line\n )\n );\n }\n }\n }\n return diagnostics;\n },\n defaultSeverity: \"warning\",\n help: \"Always specify absolute paths for WORKDIR instructions (e.g. `WORKDIR /app`).\",\n key: \"docker-doctor/absolute-workdir\",\n message: \"Use absolute paths for WORKDIR\",\n};\n\nexport const avoidRunCd: DockerfileRule = {\n category: \"Best Practices\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n for (const inst of instructions) {\n if (inst.instruction === \"RUN\" && /\\bcd\\b/u.test(inst.args)) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n \"Avoid using 'cd' in RUN instructions. Use WORKDIR instead to change the working directory stably across layers.\",\n this.help,\n inst.line\n )\n );\n }\n }\n return diagnostics;\n },\n defaultSeverity: \"info\",\n help: \"Use the WORKDIR instruction instead of `cd` inside RUN to establish directory context.\",\n key: \"docker-doctor/avoid-run-cd\",\n message: \"Avoid changing directories with cd in RUN\",\n};\n\nexport const sortMultilineArgs: DockerfileRule = {\n category: \"Best Practices\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n for (const inst of instructions) {\n if (inst.instruction === \"RUN\") {\n const { raw } = inst;\n const isPackageInstall =\n raw.includes(\"apt-get install\") ||\n raw.includes(\"apk add\") ||\n raw.includes(\"yum install\") ||\n raw.includes(\"dnf install\");\n\n const hasContinuation = raw.includes(\"\\\\\\n\") || raw.includes(\"\\\\\\r\\n\");\n\n if (isPackageInstall && hasContinuation) {\n const lines = raw.split(/\\r?\\n/u);\n const packages = lines\n .slice(1)\n .map((line) => line.trim())\n .filter(\n (line) =>\n line !== \"\" &&\n !line.startsWith(\"&&\") &&\n !line.startsWith(\"-\") &&\n !line.includes(\"rm -rf\")\n )\n .map((line) =>\n line.endsWith(\"\\\\\") ? line.slice(0, -1).trim() : line\n )\n .filter(Boolean);\n\n if (packages.length > 1) {\n const sorted = packages.toSorted((a, b) => a.localeCompare(b));\n const isSorted = packages.every((val, idx) => val === sorted[idx]);\n if (!isSorted) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n \"Multi-line package arguments are not sorted alphanumerically. Keeping them sorted makes maintenance easier and prevents duplicates.\",\n this.help,\n inst.line\n )\n );\n }\n }\n }\n }\n }\n return diagnostics;\n },\n defaultSeverity: \"info\",\n help: \"Sort multi-line package installation lists (e.g. apk/apt package lists) alphabetically.\",\n key: \"docker-doctor/sort-multiline-args\",\n message: \"Sort multi-line arguments alphanumerically\",\n};\n\nexport const useraddNoLogInit: DockerfileRule = {\n category: \"Best Practices\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n for (const inst of instructions) {\n if (\n inst.instruction === \"RUN\" &&\n /\\buseradd\\b/u.test(inst.args) &&\n !inst.args.includes(\"--no-log-init\")\n ) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n \"RUN instruction runs 'useradd' without '--no-log-init'. This can cause excessive disk space usage / exhaustion under Go's sparse tar archive bug when large UIDs are used.\",\n this.help,\n inst.line\n )\n );\n }\n }\n return diagnostics;\n },\n defaultSeverity: \"warning\",\n help: \"Pass `--no-log-init` flag to useradd (e.g., `RUN useradd --no-log-init -r -g mygroup myuser`).\",\n key: \"docker-doctor/useradd-no-log-init\",\n message: \"Use --no-log-init with useradd\",\n};\n\nexport const bestPracticesRules = [\n requireHealthcheck,\n preferCopyOverAdd,\n useExecForm,\n requireLabels,\n combineAptUpdateInstall,\n usePipefail,\n absoluteWorkdir,\n avoidRunCd,\n sortMultilineArgs,\n useraddNoLogInit,\n];\n","import type { ComposeRule, Diagnostic } from \"../types/index\";\nimport { createDiagnostic } from \"./create-diagnostic\";\n\nexport const noVersionKey: ComposeRule = {\n category: \"Compose\",\n check(composeContent, file, context) {\n if (\n composeContent &&\n typeof composeContent === \"object\" &&\n \"version\" in composeContent\n ) {\n return [\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n \"The 'version' property is deprecated. Remove it to use standard Compose spec behavior.\",\n this.help,\n context?.locate?.([\"version\"])\n ),\n ];\n }\n return [];\n },\n defaultSeverity: \"warning\",\n help: \"The `version` key is obsolete in the Compose specification. Omitting it defaults to the latest specification.\",\n key: \"docker-doctor/no-version-key\",\n message: \"Remove the `version` key from the Compose file\",\n};\n\nexport const requireResourceLimits: ComposeRule = {\n category: \"Compose\",\n check(composeContent, file, context) {\n const diagnostics: Diagnostic[] = [];\n\n if (\n composeContent &&\n typeof composeContent === \"object\" &&\n \"services\" in composeContent\n ) {\n const { services } = composeContent;\n if (services && typeof services === \"object\") {\n for (const [name, config] of Object.entries(services)) {\n if (config && typeof config === \"object\") {\n const deploy = (config as Record<string, unknown>).deploy as\n | Record<string, unknown>\n | undefined;\n const resources = deploy?.resources as\n | Record<string, unknown>\n | undefined;\n const limits = resources?.limits as\n | Record<string, unknown>\n | undefined;\n\n if (!limits || (!limits.cpus && !limits.memory)) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `Service '${name}' does not have CPU or memory limits defined. A resource leak in this service could crash the host.`,\n this.help,\n context?.locate?.([\"services\", name])\n )\n );\n }\n }\n }\n }\n }\n\n return diagnostics;\n },\n defaultSeverity: \"warning\",\n help: \"Add resource limits (e.g. `deploy.resources.limits`) to prevent a single service from starving host resources in production.\",\n key: \"docker-doctor/require-resource-limits\",\n message: \"Define resource limits for services\",\n};\n\nexport const requireRestartPolicy: ComposeRule = {\n category: \"Compose\",\n check(composeContent, file, context) {\n const diagnostics: Diagnostic[] = [];\n\n if (\n composeContent &&\n typeof composeContent === \"object\" &&\n \"services\" in composeContent\n ) {\n const { services } = composeContent;\n if (services && typeof services === \"object\") {\n for (const [name, config] of Object.entries(services)) {\n if (config && typeof config === \"object\") {\n const hasRestart = \"restart\" in config;\n const deploy = (config as Record<string, unknown>).deploy as\n | Record<string, unknown>\n | undefined;\n const hasDeployRestart = deploy?.restart_policy !== undefined;\n\n if (!hasRestart && !hasDeployRestart) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `Service '${name}' has no restart policy configured. It will not restart if it crashes or if the host reboots.`,\n this.help,\n context?.locate?.([\"services\", name])\n )\n );\n }\n }\n }\n }\n }\n\n return diagnostics;\n },\n defaultSeverity: \"warning\",\n help: \"Define `restart: always` or `restart: unless-stopped` (or `deploy.restart_policy`) so services restart on crashes or host reboot.\",\n key: \"docker-doctor/require-restart-policy\",\n message: \"Set restart policy for services\",\n};\n\nexport const useDependsOnCondition: ComposeRule = {\n category: \"Compose\",\n check(composeContent, file, context) {\n const diagnostics: Diagnostic[] = [];\n\n if (\n composeContent &&\n typeof composeContent === \"object\" &&\n \"services\" in composeContent\n ) {\n const { services } = composeContent;\n if (services && typeof services === \"object\") {\n for (const [name, config] of Object.entries(services)) {\n if (config && typeof config === \"object\") {\n const dependsOn = (config as Record<string, unknown>).depends_on;\n if (dependsOn && Array.isArray(dependsOn)) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `Service '${name}' uses shorthand depends_on list. This only checks if containers are started, not if they are ready/healthy.`,\n this.help,\n context?.locate?.([\"services\", name, \"depends_on\"]) ??\n context?.locate?.([\"services\", name])\n )\n );\n }\n }\n }\n }\n }\n\n return diagnostics;\n },\n defaultSeverity: \"info\",\n help: \"Instead of a simple service list, use `depends_on: { dependency: { condition: service_healthy } }` to ensure dependencies are fully ready before starting.\",\n key: \"docker-doctor/use-depends-on-condition\",\n message: \"Use long-form depends_on with healthcheck conditions\",\n};\n\nexport const composeRules = [\n noVersionKey,\n requireResourceLimits,\n requireRestartPolicy,\n useDependsOnCondition,\n];\n","import {\n collectStageAliases,\n isScratch,\n parseFromArgs,\n parseImageRef,\n} from \"../parsers/image-ref\";\nimport type {\n Diagnostic,\n DockerfileInstruction,\n DockerfileRule,\n} from \"../types/index\";\nimport { createDiagnostic } from \"./create-diagnostic\";\n\nexport const preferSlimBase: DockerfileRule = {\n category: \"Image Size\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n const stageAliases = collectStageAliases(instructions);\n\n for (const inst of instructions) {\n if (inst.instruction === \"FROM\") {\n const imagePart = parseFromArgs(inst.args).base;\n if (!imagePart || isScratch(imagePart)) {\n continue;\n }\n\n const ref = parseImageRef(imagePart);\n\n if (ref.isVariable || stageAliases.has(imagePart.toLowerCase())) {\n continue;\n }\n\n // Digest pins are already fully deterministic; not our concern here.\n if (ref.digest) {\n continue;\n }\n\n // No tag: pin-image-version owns the untagged case, don't double-report.\n if (!ref.tag) {\n continue;\n }\n\n // Minimal bases identify themselves either in the name (alpine,\n // busybox, gcr.io/distroless/*) or in the tag (node:22-slim,\n // python:3.13-alpine). Judging by tag alone flagged `alpine:3.19`.\n const haystack = `${ref.name} ${ref.tag}`.toLowerCase();\n const isSlim =\n haystack.includes(\"alpine\") ||\n haystack.includes(\"slim\") ||\n haystack.includes(\"distroless\") ||\n haystack.includes(\"busybox\");\n\n if (!isSlim) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `Base image '${imagePart}' may be a full-OS distribution. Consider using a slim or alpine alternative.`,\n this.help,\n inst.line\n )\n );\n }\n }\n }\n\n return diagnostics;\n },\n defaultSeverity: \"info\",\n help: \"Prefer tags with `-slim`, `-alpine`, or use distroless base images to minimize the default operating system footprint.\",\n key: \"docker-doctor/prefer-slim-base\",\n message: \"Prefer slim, alpine, or distroless base images\",\n};\n\nconst BUILDKIT_MOUNT_FLAG_RE = /--mount=(?<spec>\\S+)/gu;\n\n// BuildKit accepts `target`, `dst` and `destination` as synonyms.\nconst CACHE_TARGET_KEY_RE = /^(?:target|dst|destination)=/u;\n\n// A `RUN --mount=type=cache,target=<dir>` keeps <dir> in the cache mount, not\n// in the image layer — cleanup commands for that dir are unnecessary (and the\n// Docker-documented apt pattern deliberately omits them).\nconst cacheMountTargets = (args: string): string[] =>\n [...args.matchAll(BUILDKIT_MOUNT_FLAG_RE)]\n .map((match) => (match.groups?.spec ?? \"\").split(\",\"))\n .filter((options) => options.includes(\"type=cache\"))\n .flatMap((options) =>\n options\n .filter((option) => CACHE_TARGET_KEY_RE.test(option))\n .map((option) => option.slice(option.indexOf(\"=\") + 1))\n );\n\nconst APT_CACHE_DIRS = [\"/var/lib/apt\", \"/var/cache/apt\"];\nconst APK_CACHE_DIRS = [\"/var/cache/apk\", \"/etc/apk/cache\"];\n\nconst hasCacheMountFor = (args: string, cacheDirs: string[]): boolean =>\n cacheMountTargets(args).some((target) =>\n cacheDirs.some((dir) => target === dir || target.startsWith(`${dir}/`))\n );\n\nexport const cleanPackageCache: DockerfileRule = {\n category: \"Image Size\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n\n for (const inst of instructions) {\n if (inst.instruction === \"RUN\") {\n const { args } = inst;\n\n // check apt-get install without cleanup\n if (\n args.includes(\"apt-get install\") &&\n !args.includes(\"rm -rf /var/lib/apt/lists\") &&\n !hasCacheMountFor(args, APT_CACHE_DIRS)\n ) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `Running 'apt-get install' without removing package lists afterwards. This keeps metadata caches inside the image layer.`,\n this.help,\n inst.line\n )\n );\n }\n\n // check apk add without --no-cache\n if (\n args.includes(\"apk add\") &&\n !args.includes(\"--no-cache\") &&\n !args.includes(\"rm -rf /var/cache/apk\") &&\n !hasCacheMountFor(args, APK_CACHE_DIRS)\n ) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `Running 'apk add' without '--no-cache' or cleaning the apk cache. This increases layer size.`,\n this.help,\n inst.line\n )\n );\n }\n }\n }\n\n return diagnostics;\n },\n defaultSeverity: \"warning\",\n help: \"For apt-get, append `&& rm -rf /var/lib/apt/lists/*`. For apk, use `apk add --no-cache`. For dnf/yum, run `yum clean all`.\",\n key: \"docker-doctor/clean-package-cache\",\n message: \"Clean up package manager cache in the same RUN layer\",\n};\n\nconst installsDevDependencies = (args: string): boolean =>\n (args.includes(\"npm install\") ||\n args.includes(\"npm ci\") ||\n args.includes(\"yarn install\")) &&\n !args.includes(\"--production\") &&\n !args.includes(\"--omit=dev\") &&\n !args.includes(\"prune\");\n\nexport const avoidDevDependencies: DockerfileRule = {\n category: \"Image Size\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n\n const stages: {\n name: string | null;\n base: string;\n runs: DockerfileInstruction[];\n }[] = [];\n for (const inst of instructions) {\n if (inst.instruction === \"FROM\") {\n const { base, stage } = parseFromArgs(inst.args);\n stages.push({\n base: base?.toLowerCase() ?? \"\",\n name: stage?.toLowerCase() ?? null,\n runs: [],\n });\n } else if (inst.instruction === \"RUN\" && stages.length > 0) {\n stages.at(-1)?.runs.push(inst);\n }\n }\n if (stages.length === 0) {\n return diagnostics;\n }\n\n // The default build target is the last stage, and its image contains\n // every layer of the local stages it builds FROM — so a dev install in\n // an inherited stage ships just like one in the final stage itself.\n const auditedIndices: number[] = [];\n let index = stages.length - 1;\n while (index >= 0) {\n auditedIndices.push(index);\n const { base } = stages[index];\n index = stages\n .slice(0, index)\n .findIndex((s) => s.name !== null && s.name === base);\n }\n\n const finalIndex = stages.length - 1;\n for (const stageIndex of auditedIndices.toReversed()) {\n const stage = stages[stageIndex];\n for (const inst of stage.runs) {\n if (!installsDevDependencies(inst.args)) {\n continue;\n }\n const where =\n stageIndex === finalIndex\n ? \"in the final stage\"\n : `in stage '${stage.name}', whose layers the final stage inherits,`;\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `Running package install '${inst.args}' ${where} without omitting devDependencies.`,\n this.help,\n inst.line\n )\n );\n }\n }\n\n return diagnostics;\n },\n defaultSeverity: \"warning\",\n help: \"For Node.js, run `npm prune --production` or install only production dependencies (`npm ci --omit=dev`) in the runtime stage.\",\n key: \"docker-doctor/avoid-dev-dependencies\",\n message: \"Avoid installing dev dependencies in the final stage\",\n};\n\nexport const imageSizeRules = [\n preferSlimBase,\n cleanPackageCache,\n avoidDevDependencies,\n];\n","import type { Diagnostic, DockerfileRule } from \"../types/index\";\nimport { createDiagnostic } from \"./create-diagnostic\";\n\nexport const useMultiStage: DockerfileRule = {\n category: \"Performance\",\n check(instructions, file) {\n const fromCount = instructions.filter(\n (inst) => inst.instruction === \"FROM\"\n ).length;\n if (fromCount === 1) {\n // Check if it's not a trivial/short Dockerfile (e.g., has some build steps)\n const hasBuildSteps = instructions.some(\n (inst) =>\n inst.instruction === \"RUN\" &&\n (inst.args.includes(\"npm run build\") ||\n inst.args.includes(\"yarn build\") ||\n inst.args.includes(\"bun run build\") ||\n inst.args.includes(\"cargo build\") ||\n inst.args.includes(\"make\"))\n );\n\n if (hasBuildSteps) {\n return [\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n \"Only one build stage (FROM) was detected, but build instructions were found. Multi-stage builds can significantly reduce final image size.\",\n this.help,\n instructions.find((inst) => inst.instruction === \"FROM\")?.line || 1\n ),\n ];\n }\n }\n return [];\n },\n defaultSeverity: \"info\",\n help: \"Use multi-stage builds (multiple FROM statements) to separate build dependencies from the runtime image and reduce size.\",\n key: \"docker-doctor/use-multi-stage\",\n message: \"Use multi-stage builds\",\n};\n\nexport const orderLayers: DockerfileRule = {\n category: \"Performance\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n let copyAllLine = -1;\n\n for (const inst of instructions) {\n if (inst.instruction === \"FROM\") {\n copyAllLine = -1;\n }\n\n if (inst.instruction === \"COPY\" || inst.instruction === \"ADD\") {\n const parts = inst.args.split(/\\s+/u);\n const src = parts.find((p) => !p.startsWith(\"--\"));\n\n if (!src) {\n continue;\n }\n\n const normalized = src.replace(/^\\.\\//u, \"\");\n const isCopyAll =\n normalized === \".\" ||\n normalized === \"\" ||\n normalized === \"*\" ||\n normalized === \"src\" ||\n normalized.startsWith(\"src/\");\n\n if (isCopyAll && copyAllLine === -1) {\n copyAllLine = inst.line;\n }\n }\n\n if (inst.instruction === \"RUN\" && copyAllLine !== -1) {\n const args = inst.args.toLowerCase();\n if (\n args.includes(\"npm install\") ||\n args.includes(\"npm ci\") ||\n args.includes(\"yarn install\") ||\n args.includes(\"bun install\") ||\n args.includes(\"pip install\") ||\n args.includes(\"cargo fetch\")\n ) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `Running package installation command '${inst.args}' after copying application files (at line ${copyAllLine}). This invalidates the cache on any code changes.`,\n this.help,\n inst.line\n )\n );\n }\n }\n }\n\n return diagnostics;\n },\n defaultSeverity: \"warning\",\n help: \"Copy dependency definition files (like package.json, lockfiles) and run install commands BEFORE copying the rest of the application source code.\",\n key: \"docker-doctor/order-layers\",\n message: \"Order layers to maximize build cache utility\",\n};\n\nexport const minimizeLayers: DockerfileRule = {\n category: \"Performance\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n let consecutiveRunCount = 0;\n let firstRunLine = -1;\n\n for (const inst of instructions) {\n if (inst.instruction === \"RUN\") {\n if (consecutiveRunCount === 0) {\n firstRunLine = inst.line;\n }\n consecutiveRunCount += 1;\n } else {\n if (consecutiveRunCount > 2) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `Found ${consecutiveRunCount} consecutive RUN instructions starting at line ${firstRunLine}. Consider combining them into a single RUN layer.`,\n this.help,\n firstRunLine\n )\n );\n }\n consecutiveRunCount = 0;\n }\n }\n\n if (consecutiveRunCount > 2) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `Found ${consecutiveRunCount} consecutive RUN instructions starting at line ${firstRunLine}. Consider combining them into a single RUN layer.`,\n this.help,\n firstRunLine\n )\n );\n }\n\n return diagnostics;\n },\n defaultSeverity: \"info\",\n help: \"Combine consecutive RUN instructions using `&&` and `\\\\` to reduce the total layer count and image size.\",\n key: \"docker-doctor/minimize-layers\",\n message: \"Minimize the number of image layers\",\n};\n\n// Docker reads .dockerignore from the build-context root, which we cannot know\n// statically. Accept the two locations that cover real usage: next to the\n// Dockerfile, or at the scan root (the common monorepo-root build context).\n// Paths here are scan-root-relative and always \"/\"-separated.\nconst hasDockerignoreFor = (\n dockerfilePath: string,\n projectFiles: string[]\n): boolean => {\n const lastSlash = dockerfilePath.lastIndexOf(\"/\");\n const dir = lastSlash === -1 ? \"\" : dockerfilePath.slice(0, lastSlash);\n const adjacent = dir === \"\" ? \".dockerignore\" : `${dir}/.dockerignore`;\n return projectFiles.some((f) => f === adjacent || f === \".dockerignore\");\n};\n\nexport const useDockerignore: DockerfileRule = {\n category: \"Performance\",\n check(instructions, file, context) {\n // If copying everything, we definitely need .dockerignore\n const hasCopyAll = instructions.some((inst) => {\n if (inst.instruction === \"COPY\" || inst.instruction === \"ADD\") {\n // COPY --from=<stage> reads from a previous build stage, not the\n // build context, so .dockerignore is irrelevant to it.\n const isStageCopy = /(?:^|\\s)--from=/u.test(inst.args);\n if (isStageCopy) {\n return false;\n }\n\n const parts = inst.args.split(/\\s+/u);\n const src = parts.find((p) => !p.startsWith(\"--\"));\n if (!src) {\n return false;\n }\n return src === \".\" || src === \"./\" || src === \"*\";\n }\n return false;\n });\n\n if (\n hasCopyAll &&\n context?.projectFiles &&\n !hasDockerignoreFor(file, context.projectFiles)\n ) {\n return [\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n \"Using COPY/ADD with a wildcard or directory, but no .dockerignore file was found next to the Dockerfile or at the project root. This can copy local build folders and secrets.\",\n this.help,\n 1\n ),\n ];\n }\n return [];\n },\n defaultSeverity: \"warning\",\n help: \"Create a .dockerignore file in the same directory as the Dockerfile to prevent copying unnecessary files (like node_modules, logs, build artifacts).\",\n key: \"docker-doctor/use-dockerignore\",\n message: \"Add a .dockerignore file\",\n};\n\nexport const performanceRules = [\n useMultiStage,\n orderLayers,\n minimizeLayers,\n useDockerignore,\n];\n","import {\n collectStageAliases,\n isScratch,\n parseFromArgs,\n parseImageRef,\n} from \"../parsers/image-ref\";\nimport type { Diagnostic, DockerfileRule } from \"../types/index\";\nimport { createDiagnostic } from \"./create-diagnostic\";\n\n// USER accepts \"user\", \"uid\", \"user:group\" and \"uid:gid\". Only the user half\n// decides whether the container runs as root; the group half is irrelevant.\nconst isRootUser = (value: string): boolean => {\n const [user] = value.split(\":\");\n return user === \"root\" || user === \"0\";\n};\n\nexport const noRootUser: DockerfileRule = {\n category: \"Security\",\n check(instructions, file) {\n // A stage built FROM a previous stage inherits that stage's image\n // config, USER included; a fresh base image resets it to root.\n const stageUser = new Map<string, string>();\n let currentStage: string | null = null;\n let lastUser = \"root\";\n let lastUserLine = 1;\n\n for (const inst of instructions) {\n if (inst.instruction === \"FROM\") {\n const { base, stage } = parseFromArgs(inst.args);\n lastUser = stageUser.get(base?.toLowerCase() ?? \"\") ?? \"root\";\n lastUserLine = inst.line;\n currentStage = stage?.toLowerCase() ?? null;\n if (currentStage) {\n stageUser.set(currentStage, lastUser);\n }\n } else if (inst.instruction === \"USER\") {\n lastUser = inst.args.trim().toLowerCase();\n lastUserLine = inst.line;\n if (currentStage) {\n stageUser.set(currentStage, lastUser);\n }\n }\n }\n\n if (isRootUser(lastUser)) {\n return [\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n \"The container runs as root. Running as root allows potential container breakout vulnerabilities.\",\n this.help,\n lastUserLine\n ),\n ];\n }\n\n return [];\n },\n defaultSeverity: \"warning\",\n help: \"Add a non-root user (e.g., `USER node` or `USER 1000`) to improve security.\",\n key: \"docker-doctor/no-root-user\",\n message: \"Run the container as a non-root user\",\n};\n\nexport const noSecretsInEnv: DockerfileRule = {\n category: \"Security\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n const secretKeywords = [\n /(?:^|[_-])password(?:[_-]|$)/iu,\n /(?:^|[_-])secret(?:[_-]|$)/iu,\n /(?:^|[_-])token(?:[_-]|$)/iu,\n /(?:^|[_-])api_key(?:[_-]|$)/iu,\n /(?:^|[_-])private_key(?:[_-]|$)/iu,\n /(?:^|[_-])auth(?:[_-]|$)/iu,\n ];\n\n for (const inst of instructions) {\n if (inst.instruction === \"ENV\" || inst.instruction === \"ARG\") {\n const args = inst.args.trim();\n if (inst.instruction === \"ENV\" && !args.includes(\"=\")) {\n // KEY VALUE format\n const match = args.match(/^(?<key>[^\\s]+)\\s+(?<value>.*)$/u);\n if (match?.groups) {\n const { key, value } = match.groups;\n const isSecretKey = secretKeywords.some((regex) => regex.test(key));\n if (\n isSecretKey &&\n value &&\n !value.startsWith(\"$\") &&\n !value.startsWith(\"{\")\n ) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `Potential secret found in ${inst.instruction}: '${key}'. Secrets baked into images can be extracted easily by anyone with image access.`,\n this.help,\n inst.line\n )\n );\n }\n }\n } else {\n // Existing KEY=VALUE logic\n const parts = args.split(/\\s+/u);\n for (const part of parts) {\n const eqIndex = part.indexOf(\"=\");\n let key = \"\";\n let value = \"\";\n\n if (eqIndex > 0) {\n key = part.slice(0, eqIndex);\n value = part.slice(eqIndex + 1);\n } else {\n key = part;\n }\n\n const isSecretKey = secretKeywords.some((regex) => regex.test(key));\n if (\n isSecretKey &&\n value &&\n !value.startsWith(\"$\") &&\n !value.startsWith(\"{\")\n ) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `Potential secret found in ${inst.instruction}: '${key}'. Secrets baked into images can be extracted easily by anyone with image access.`,\n this.help,\n inst.line\n )\n );\n }\n }\n }\n }\n }\n\n return diagnostics;\n },\n defaultSeverity: \"error\",\n help: \"Use Docker Secrets, build arguments passed at runtime, or environment variables at runtime instead of baking them into the image.\",\n key: \"docker-doctor/no-secrets-in-env\",\n message: \"Avoid storing secrets in ENV or ARG instructions\",\n};\n\nexport const pinImageVersion: DockerfileRule = {\n category: \"Security\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n const stageAliases = collectStageAliases(instructions);\n\n for (const inst of instructions) {\n if (inst.instruction === \"FROM\") {\n // FROM image or FROM image:tag or FROM image@sha256:hash\n // Also respect multi-stage builds (AS stageName)\n const imagePart = parseFromArgs(inst.args).base;\n\n if (!imagePart || isScratch(imagePart)) {\n continue;\n }\n\n const ref = parseImageRef(imagePart);\n\n if (ref.isVariable || stageAliases.has(imagePart.toLowerCase())) {\n continue;\n }\n\n if (!(ref.tag || ref.digest)) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `Base image '${imagePart}' does not specify a tag. This makes builds non-deterministic.`,\n this.help,\n inst.line\n )\n );\n } else if (ref.tag === \"latest\" && !ref.digest) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `Base image '${imagePart}' uses the mutable 'latest' tag. This makes builds non-deterministic.`,\n this.help,\n inst.line\n )\n );\n }\n }\n }\n\n return diagnostics;\n },\n defaultSeverity: \"warning\",\n help: \"Specify a concrete tag instead of `latest` or no tag (e.g., `node:22.2.0-alpine` instead of `node`).\",\n key: \"docker-doctor/pin-image-version\",\n message: \"Pin base images to a specific tag or digest\",\n};\n\nexport const noAddRemote: DockerfileRule = {\n category: \"Security\",\n check(instructions, file) {\n const diagnostics: Diagnostic[] = [];\n\n for (const inst of instructions) {\n if (inst.instruction === \"ADD\") {\n const parts = inst.args.split(/\\s+/u);\n const src = parts.find((p) => !p.startsWith(\"--\"));\n\n if (!src) {\n continue;\n }\n\n if (src.startsWith(\"http://\") || src.startsWith(\"https://\")) {\n diagnostics.push(\n createDiagnostic(\n file,\n this.key,\n this.defaultSeverity,\n `ADD instruction uses a remote URL '${src}'. Remote files added via ADD cannot be cleaned up in later layers, increasing image size.`,\n this.help,\n inst.line\n )\n );\n }\n }\n }\n\n return diagnostics;\n },\n defaultSeverity: \"warning\",\n help: \"Use `RUN curl` or `RUN wget` instead of ADD for remote URLs, and delete the downloaded archive in the same layer to minimize size.\",\n key: \"docker-doctor/no-add-remote\",\n message: \"Avoid using ADD with remote URLs\",\n};\n\nexport const securityRules = [\n noRootUser,\n noSecretsInEnv,\n pinImageVersion,\n noAddRemote,\n];\n","import type {\n DockerfileRule,\n ComposeRule,\n RuleDefinition,\n} from \"../types/index\";\nimport { bestPracticesRules } from \"./best-practices\";\nimport { composeRules } from \"./compose\";\nimport { imageSizeRules } from \"./image-size\";\nimport { performanceRules } from \"./performance\";\nimport { securityRules } from \"./security\";\n\nexport const allDockerfileRules: DockerfileRule[] = [\n ...securityRules,\n ...performanceRules,\n ...bestPracticesRules,\n ...imageSizeRules,\n];\n\nexport const allComposeRules: ComposeRule[] = [...composeRules];\n\nexport const allRules: RuleDefinition[] = [\n ...allDockerfileRules,\n ...allComposeRules,\n];\n\nexport const findRule = (key: string): RuleDefinition | undefined =>\n allRules.find((rule) => rule.key === key);\n","import type { RuleDefinition, RuleSeverity } from \"../types/index\";\n\n// Precedence: per-rule config > category config > the rule's default.\nexport const resolveSeverity = (\n rule: RuleDefinition,\n rulesConfig?: Record<string, RuleSeverity>,\n categoriesConfig?: Record<string, RuleSeverity>\n): RuleSeverity =>\n rulesConfig?.[rule.key] ??\n categoriesConfig?.[rule.category] ??\n rule.defaultSeverity;\n","import { allDockerfileRules } from \"../rules/index\";\nimport type {\n DockerfileInstruction,\n Diagnostic,\n RuleSeverity,\n} from \"../types/index\";\nimport { resolveSeverity } from \"./resolve-severity\";\n\nexport const runDockerfileRules = (\n instructions: DockerfileInstruction[],\n file: string,\n projectFiles: string[],\n rulesConfig?: Record<string, RuleSeverity>,\n categoriesConfig?: Record<string, RuleSeverity>\n): Diagnostic[] => {\n const diagnostics: Diagnostic[] = [];\n\n for (const rule of allDockerfileRules) {\n const severity = resolveSeverity(rule, rulesConfig, categoriesConfig);\n if (severity === \"off\") {\n continue;\n }\n\n const ruleDiagnostics = rule.check(instructions, file, { projectFiles });\n\n // Override severity if config resolved to something other than default\n if (severity !== rule.defaultSeverity) {\n for (const diag of ruleDiagnostics) {\n diag.severity = severity;\n }\n }\n\n diagnostics.push(...ruleDiagnostics);\n }\n\n return diagnostics;\n};\n","import { allComposeRules } from \"../rules/index\";\nimport type { ComposeLocator, Diagnostic, RuleSeverity } from \"../types/index\";\nimport { resolveSeverity } from \"./resolve-severity\";\n\nexport const runComposeRules = (\n composeContent: unknown,\n file: string,\n rulesConfig?: Record<string, RuleSeverity>,\n categoriesConfig?: Record<string, RuleSeverity>,\n locate?: ComposeLocator\n): Diagnostic[] => {\n const diagnostics: Diagnostic[] = [];\n\n for (const rule of allComposeRules) {\n const severity = resolveSeverity(rule, rulesConfig, categoriesConfig);\n if (severity === \"off\") {\n continue;\n }\n\n const ruleDiagnostics = rule.check(composeContent, file, { locate });\n\n // Override severity if config resolved to something other than default\n if (severity !== rule.defaultSeverity) {\n for (const diag of ruleDiagnostics) {\n diag.severity = severity;\n }\n }\n\n diagnostics.push(...ruleDiagnostics);\n }\n\n return diagnostics;\n};\n","import type {\n DockerDoctorConfig,\n RuleCategory,\n RuleSeverity,\n} from \"../types/index\";\n\nexport type { DockerDoctorConfig } from \"../types/index\";\n\nconst RULE_SEVERITIES: readonly RuleSeverity[] = [\n \"error\",\n \"warning\",\n \"info\",\n \"off\",\n];\n\nconst RULE_CATEGORIES: readonly RuleCategory[] = [\n \"Best Practices\",\n \"Compose\",\n \"Image Size\",\n \"Performance\",\n \"Security\",\n];\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isRuleSeverity = (value: unknown): value is RuleSeverity =>\n typeof value === \"string\" &&\n (RULE_SEVERITIES as readonly string[]).includes(value);\n\nconst validateRules = (value: unknown): Record<string, RuleSeverity> => {\n if (!isPlainObject(value)) {\n throw new Error(\n `Invalid config: \"rules\" must be an object, got ${typeof value}`\n );\n }\n\n for (const [key, severity] of Object.entries(value)) {\n if (!isRuleSeverity(severity)) {\n throw new Error(\n `Invalid severity ${JSON.stringify(severity)} for rule \"${key}\"`\n );\n }\n }\n\n return value as Record<string, RuleSeverity>;\n};\n\nconst validateCategories = (\n value: unknown\n): Partial<Record<RuleCategory, RuleSeverity>> => {\n if (!isPlainObject(value)) {\n throw new Error(\n `Invalid config: \"categories\" must be an object, got ${typeof value}`\n );\n }\n\n const result: Partial<Record<RuleCategory, RuleSeverity>> = {};\n for (const [key, severity] of Object.entries(value)) {\n if (!(RULE_CATEGORIES as readonly string[]).includes(key)) {\n // Unknown category keys are silently dropped (matches the\n // legacy schema's excess-property behavior).\n continue;\n }\n if (!isRuleSeverity(severity)) {\n throw new Error(\n `Invalid severity ${JSON.stringify(severity)} for category \"${key}\"`\n );\n }\n result[key as RuleCategory] = severity;\n }\n\n return result;\n};\n\nconst validateIgnore = (value: unknown): { files?: string[] } => {\n if (!isPlainObject(value)) {\n throw new Error(\n `Invalid config: \"ignore\" must be an object, got ${typeof value}`\n );\n }\n\n const result: { files?: string[] } = {};\n if (\"files\" in value && value.files !== undefined) {\n if (\n !Array.isArray(value.files) ||\n !value.files.every((item) => typeof item === \"string\")\n ) {\n throw new Error(\n 'Invalid config: \"ignore.files\" must be an array of strings'\n );\n }\n result.files = value.files;\n }\n\n return result;\n};\n\nconst describeInvalidTopLevel = (input: unknown): string => {\n if (input === null) {\n return \"null\";\n }\n if (Array.isArray(input)) {\n return \"array\";\n }\n return typeof input;\n};\n\n/**\n * Validates and normalizes a raw config object, throwing on invalid input.\n *\n * Mirrors the legacy schema's behavior exactly, including silently\n * dropping unknown top-level (and nested) keys rather than throwing\n * or preserving them.\n */\nexport const validateConfig = (input: unknown): DockerDoctorConfig => {\n if (!isPlainObject(input)) {\n throw new Error(\n `Invalid config: expected an object, got ${describeInvalidTopLevel(input)}`\n );\n }\n\n const result: DockerDoctorConfig = {};\n\n if (\"rules\" in input && input.rules !== undefined) {\n result.rules = validateRules(input.rules);\n }\n\n if (\"categories\" in input && input.categories !== undefined) {\n result.categories = validateCategories(input.categories);\n }\n\n if (\"ignore\" in input && input.ignore !== undefined) {\n result.ignore = validateIgnore(input.ignore);\n }\n\n return result;\n};\n","import { allRules } from \"../rules/index\";\nimport type { RuleCategory } from \"../types/index\";\n\nconst KNOWN_CATEGORIES: readonly RuleCategory[] = [\n \"Best Practices\",\n \"Compose\",\n \"Image Size\",\n \"Performance\",\n \"Security\",\n];\n\nexport interface UnknownConfigKeys {\n categories: string[];\n rules: string[];\n}\n\nconst keysOf = (value: unknown): string[] =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? Object.keys(value)\n : [];\n\n// Config keys are matched exactly, so a typo'd rule key -- or a category\n// written as \"security\" instead of \"Security\" -- passes validation and then\n// matches no rule: a suppression the user believes is active silently does\n// nothing. Reported so the caller can warn, deliberately not an error,\n// because a config naming a rule that a later release removed should still\n// scan. Takes the raw config because validation drops unknown category keys\n// before they reach the typed result.\nexport const collectUnknownConfigKeys = (raw: unknown): UnknownConfigKeys => {\n if (typeof raw !== \"object\" || raw === null) {\n return { categories: [], rules: [] };\n }\n\n const knownRuleKeys = new Set(allRules.map((rule) => rule.key));\n const knownCategories = new Set<string>(KNOWN_CATEGORIES);\n const { categories, rules } = raw as {\n categories?: unknown;\n rules?: unknown;\n };\n\n return {\n categories: keysOf(categories).filter((key) => !knownCategories.has(key)),\n rules: keysOf(rules).filter((key) => !knownRuleKeys.has(key)),\n };\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { parse as parseYaml } from \"yaml\";\n\nimport { ConfigError } from \"../errors\";\nimport type { DockerDoctorConfig } from \"../schemas/config\";\nimport { validateConfig } from \"../schemas/config\";\nimport { collectUnknownConfigKeys } from \"./unknown-keys\";\n\nconst fileExists = async (filePath: string): Promise<boolean> => {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n};\n\nconst parseConfigFile = async (\n filePath: string,\n format: \"JSON\" | \"YAML\",\n parse: (content: string) => unknown\n): Promise<unknown> => {\n try {\n const content = await fs.readFile(filePath, \"utf-8\");\n return parse(content);\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n throw new ConfigError({\n message: `Failed to parse config ${format}: ${msg}`,\n });\n }\n};\n\nconst importConfig = async (filePath: string): Promise<unknown> => {\n if (filePath.endsWith(\".json\")) {\n return parseConfigFile(filePath, \"JSON\", JSON.parse);\n }\n\n if (filePath.endsWith(\".yaml\") || filePath.endsWith(\".yml\")) {\n return parseConfigFile(filePath, \"YAML\", parseYaml);\n }\n\n try {\n const configModule = await import(filePath);\n return configModule.default || configModule;\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n throw new ConfigError({\n message: `Failed to load config file ${filePath}: ${msg}`,\n });\n }\n};\n\nconst warnUnknownKeys = (\n raw: unknown,\n onWarning: (message: string) => void\n): void => {\n const unknown = collectUnknownConfigKeys(raw);\n for (const key of unknown.rules) {\n onWarning(\n `Unknown rule \"${key}\" in config — it matches no rule and has no effect.`\n );\n }\n for (const key of unknown.categories) {\n onWarning(\n `Unknown category \"${key}\" in config — categories are case-sensitive (e.g. \"Best Practices\", \"Security\").`\n );\n }\n};\n\nexport const loadConfig = async (\n rootDir: string,\n customPath?: string,\n // Called once per unrecognized config key. Optional so existing callers are\n // unaffected; without it, unknown keys stay silent as before.\n onWarning?: (message: string) => void\n): Promise<DockerDoctorConfig> => {\n let configObject: unknown = null;\n\n if (customPath) {\n const fullPath = path.resolve(rootDir, customPath);\n if (!(await fileExists(fullPath))) {\n throw new ConfigError({\n message: `Specified config file not found at ${fullPath}`,\n });\n }\n configObject = await importConfig(fullPath);\n } else {\n const candidates = [\n \"docker-doctor.config.ts\",\n \"docker-doctor.config.js\",\n \"docker-doctor.config.mjs\",\n \"docker-doctor.config.cjs\",\n \"docker-doctor.config.json\",\n \"docker-doctor.config.yaml\",\n \"docker-doctor.config.yml\",\n ];\n\n /* eslint-disable no-await-in-loop */\n for (const cand of candidates) {\n const fullPath = path.join(rootDir, cand);\n if (await fileExists(fullPath)) {\n configObject = await importConfig(fullPath);\n break;\n }\n }\n /* eslint-enable no-await-in-loop */\n\n if (!configObject) {\n const pkgPath = path.join(rootDir, \"package.json\");\n if (await fileExists(pkgPath)) {\n try {\n const pkgContent = await fs.readFile(pkgPath, \"utf-8\");\n const pkgJson = JSON.parse(pkgContent);\n if (pkgJson.dockerDoctor) {\n configObject = pkgJson.dockerDoctor;\n }\n } catch {\n // ignore package.json read/parse failures\n }\n }\n }\n }\n\n if (!configObject) {\n return {};\n }\n\n try {\n const config = validateConfig(configObject);\n if (onWarning) {\n warnUnknownKeys(configObject, onWarning);\n }\n return config;\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n throw new ConfigError({\n message: `Invalid configuration format: ${msg}`,\n });\n }\n};\n","import type { Diagnostic } from \"./types/index\";\n\nexport const SCORE_BUCKETS = [\n { emoji: \"🏆\", label: \"Excellent\", min: 90 },\n { emoji: \"✅\", label: \"Good\", min: 75 },\n { emoji: \"⚠️\", label: \"Needs Work\", min: 50 },\n { emoji: \"🚨\", label: \"Critical\", min: 0 },\n] as const;\n\nexport const getScoreBucket = (\n score: number\n): (typeof SCORE_BUCKETS)[number] => {\n for (const bucket of SCORE_BUCKETS) {\n if (score >= bucket.min) {\n return bucket;\n }\n }\n return SCORE_BUCKETS.at(-1) as (typeof SCORE_BUCKETS)[number];\n};\n\nexport const calculateScore = (\n diagnostics: Diagnostic[]\n): {\n score: number;\n label: string;\n} => {\n let penalty = 0;\n\n for (const diag of diagnostics) {\n if (diag.severity === \"error\") {\n penalty += 10;\n } else if (diag.severity === \"warning\") {\n penalty += 4;\n } else if (diag.severity === \"info\") {\n penalty += 1;\n }\n }\n\n // Asymptotic decay curve: score = round(100 * e^(-penalty / K)).\n //\n // The old `max(0, 100 - penalty)` formula saturates at 0 once penalty\n // reaches 100 (e.g. ~10 errors), so a messy project and a catastrophic\n // one are indistinguishable and the score can never register a fix.\n // This curve approaches (but never reaches) 0, so it stays monotonic\n // and responsive across the whole range instead of going inert.\n //\n // K=70 was chosen so a single warning (penalty 4) still scores ~94,\n // comfortably inside the \"Excellent\" (>=90) bucket, while errors and\n // repeated warnings still meaningfully erode the score. K=40 (the\n // naive \"half-life at penalty ~28\" choice) was tried first and pushed\n // a single warning down to ~90 - right on the Excellent/Good boundary,\n // which is too harsh a penalty for one warning.\n const K = 70;\n const score = Math.round(100 * Math.exp(-penalty / K));\n const bucket = getScoreBucket(score);\n const label = `${bucket.label} ${bucket.emoji}`;\n\n return { label, score };\n};\n","import type { Diagnostic, ProjectInfo } from \"./types/index\";\n\n// Bump whenever the JSON report shape or the score formula/weights change.\n// The unversioned shape shipped before this field existed is implicitly 1.\nexport const REPORT_SCHEMA_VERSION = 2;\n\nexport interface JsonReport {\n diagnostics: {\n column?: number;\n file: string;\n help: string;\n line?: number;\n message: string;\n rule: string;\n severity: \"error\" | \"warning\" | \"info\";\n }[];\n label: string;\n project: ProjectInfo;\n schemaVersion: number;\n score: number;\n timestamp: string;\n}\n\nexport const toJsonReport = (\n diagnostics: Diagnostic[],\n score: number,\n label: string,\n project: ProjectInfo\n): JsonReport => ({\n diagnostics: diagnostics.map((d) => ({\n column: d.column,\n file: d.file,\n help: d.help,\n line: d.line,\n message: d.message,\n rule: d.rule,\n severity: d.severity,\n })),\n label,\n project,\n schemaVersion: REPORT_SCHEMA_VERSION,\n score,\n timestamp: new Date().toISOString(),\n});\n"],"mappings":";;;;;;;;;;ACKA,MAAM,OAAO,OACX,KACA,WAAqB,CAAC,MACA;CACtB,MAAM,QAAQ,MAAM,GAAG,QAAQ,KAAK,EAAE,eAAe,KAAK,CAAC;CAC3D,MAAM,QAAQ,IACZ,MAAM,IAAI,OAAO,SAAS;EACxB,MAAM,WAAW,KAAK,KAAK,KAAK,KAAK,IAAI;EACzC,IAAI,KAAK,YAAY,GAAG;GACtB,IACE,KAAK,SAAS,kBACd,KAAK,SAAS,UACd,KAAK,SAAS,WACd,KAAK,SAAS,UACd,KAAK,SAAS,UAEd;GAEF,MAAM,KAAK,UAAU,QAAQ;EAC/B,OACE,SAAS,KAAK,QAAQ;CAE1B,CAAC,CACH;CACA,OAAO;AACT;AAEA,MAAa,kBAAkB,OAC7B,YACyB;CACzB,MAAM,WAAW,MAAM,KAAK,OAAO;CACnC,MAAM,cAAwB,CAAC;CAC/B,MAAM,eAAyB,CAAC;CAChC,MAAM,gBAA0B,CAAC;CAEjC,KAAK,MAAM,QAAQ,UAAU;EAC3B,MAAM,OAAO,KAAK,SAAS,IAAI,CAAC,CAAC,YAAY;EAE7C,IAAI,SAAS,iBACX,cAAc,KAAK,KAAK,SAAS,SAAS,IAAI,CAAC;EAIjD,IACE,SAAS,gBACT,KAAK,WAAW,aAAa,KAC7B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