cve-lite-cli 1.39.0 → 1.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +28 -22
  2. package/dist/advisory/local-advisory-source.js +9 -5
  3. package/dist/advisory/local-db.js +91 -13
  4. package/dist/advisory/osv-sync.js +187 -56
  5. package/dist/advisory/staging-directory.js +112 -0
  6. package/dist/cli/advisories-sync.js +16 -2
  7. package/dist/cli/args.js +46 -35
  8. package/dist/cli/config.js +4 -1
  9. package/dist/cli/help.js +5 -3
  10. package/dist/cli/validate.js +23 -1
  11. package/dist/constants.js +15 -28
  12. package/dist/index.js +8 -3
  13. package/dist/osv/severity.js +1 -1
  14. package/dist/output/cyclonedx.js +24 -15
  15. package/dist/output/debug.js +68 -18
  16. package/dist/output/formatters.js +35 -7
  17. package/dist/output/html-reporter.js +68 -12
  18. package/dist/output/multi-folder-html-reporter.js +71 -11
  19. package/dist/output/output-dir.js +193 -7
  20. package/dist/output/override-findings-html.js +3 -6
  21. package/dist/output/override-findings-terminal.js +7 -12
  22. package/dist/output/override-fix-command.js +13 -0
  23. package/dist/output/printers.js +27 -12
  24. package/dist/output/sarif.js +168 -57
  25. package/dist/output/sbom-dependency-edges.js +16 -10
  26. package/dist/output/sbom-file.js +14 -6
  27. package/dist/output/scan-json.js +46 -3
  28. package/dist/output/spdx.js +61 -23
  29. package/dist/output/spinner.js +2 -1
  30. package/dist/output/write-outputs.js +143 -41
  31. package/dist/overrides/context-builder.js +23 -70
  32. package/dist/overrides/parsing/registry.js +1 -1
  33. package/dist/parsers/bun-lock.js +1 -2
  34. package/dist/parsers/index.js +22 -1
  35. package/dist/parsers/npm-lock-graph.js +39 -1
  36. package/dist/parsers/package-lock.js +25 -5
  37. package/dist/parsers/pnpm-lock.js +26 -12
  38. package/dist/parsers/utils.js +5 -3
  39. package/dist/parsers/yarn-lock-graph.js +5 -2
  40. package/dist/parsers/yarn-lock.js +1 -2
  41. package/dist/remediation/fix-commands.js +140 -50
  42. package/dist/remediation/npm-registry.js +56 -7
  43. package/dist/remediation/npm-transitive-graph.js +30 -72
  44. package/dist/remediation/npm-transitive-resolution.js +35 -107
  45. package/dist/remediation/parent-candidate-resolver.js +65 -0
  46. package/dist/remediation/parent-upgrade-blockers.js +51 -0
  47. package/dist/remediation/parent-upgrade.js +11 -116
  48. package/dist/remediation/registry-parent-ranges.js +21 -0
  49. package/dist/remediation/transitive-chain-resolver.js +3 -3
  50. package/dist/scan/completeness.js +17 -11
  51. package/dist/scan/multi-folder-scan.js +154 -59
  52. package/dist/scan/override-audit.js +11 -1
  53. package/dist/scan/single-scan.js +123 -67
  54. package/dist/scanner.js +288 -66
  55. package/dist/skills/content.js +12 -12
  56. package/dist/usage/scanner.js +19 -8
  57. package/dist/utils/array.js +11 -3
  58. package/dist/utils/contextual-signals.js +1 -1
  59. package/dist/utils/debug-bundle.js +118 -0
  60. package/dist/utils/debug-project.js +102 -0
  61. package/dist/utils/debug-redaction.js +117 -0
  62. package/dist/utils/effective-options.js +55 -0
  63. package/dist/utils/file.js +2 -1
  64. package/dist/utils/finding.js +1 -1
  65. package/dist/utils/fix-runner.js +98 -15
  66. package/dist/utils/import-type-queries.js +322 -0
  67. package/dist/utils/network.js +14 -10
  68. package/dist/utils/npm-lockfile.js +12 -0
  69. package/dist/utils/osv-fetch.js +70 -0
  70. package/dist/utils/package-identity.js +43 -0
  71. package/dist/utils/package-manager-source.js +24 -0
  72. package/dist/utils/purl.js +37 -0
  73. package/dist/utils/registry-config.js +129 -0
  74. package/dist/utils/severity.js +8 -0
  75. package/dist/utils/string.js +8 -0
  76. package/dist/utils/validate-url.js +4 -4
  77. package/dist/utils/version.js +47 -8
  78. package/dist/utils/versions/osv-range.js +191 -0
  79. package/dist/utils/versions/pep440.js +246 -0
  80. package/dist/utils/versions/scheme.js +10 -0
  81. package/dist/utils/vuln.js +75 -0
  82. package/package.json +3 -2
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Whether a scan source is an npm lockfile. `npm-shrinkwrap.json` has the same
3
+ * format as `package-lock.json` and npm reads it in preference, so every
4
+ * npm-specific path must accept both.
5
+ */
6
+ export function isNpmLockSource(source) {
7
+ return source === "package-lock" || source === "npm-shrinkwrap";
8
+ }
9
+ /**
10
+ * Which package manager a lockfile source implies, so callers that know the scan
11
+ * source do not each repeat the mapping. Returns null for the package.json fallback,
12
+ * which has no lockfile and therefore no manager.
13
+ */
14
+ export function packageManagerForSource(source) {
15
+ if (isNpmLockSource(source))
16
+ return "npm";
17
+ if (source === "pnpm-lock")
18
+ return "pnpm";
19
+ if (source === "yarn-lock")
20
+ return "yarn";
21
+ if (source === "bun-lock")
22
+ return "bun";
23
+ return null;
24
+ }
@@ -1,3 +1,4 @@
1
+ import { registryPackageName } from "./package-identity.js";
1
2
  /**
2
3
  * Builds a Package URL (purl) for an npm package.
3
4
  *
@@ -8,3 +9,39 @@ export function buildPurl(name, version) {
8
9
  const encodedName = name.startsWith("@") ? `%40${name.slice(1)}` : name;
9
10
  return `pkg:npm/${encodedName}@${version}`;
10
11
  }
12
+ /**
13
+ * Percent-encode a purl version the way the spec requires.
14
+ *
15
+ * Unreserved characters and `:` stay literal. `/` stays literal because the
16
+ * reference encoder treats it as safe. `!` and `+` are reserved, so an epoch
17
+ * `1!2.0` is `1%212.0` and a local label `1.2.3+local` is `1.2.3%2Blocal`.
18
+ */
19
+ function encodePurlVersion(version) {
20
+ return encodeURIComponent(version)
21
+ .replace(/[!'()*]/g, character => `%${character.charCodeAt(0).toString(16).toUpperCase()}`)
22
+ .replace(/%3A/g, ":")
23
+ .replace(/%2F/g, "/");
24
+ }
25
+ /**
26
+ * PyPI follows the purl type rule: lowercase, and `_` becomes `-`. Dots stay.
27
+ * That is separate from PEP 503, which also folds dots.
28
+ */
29
+ export function buildEcosystemPurl(ecosystem, name, version) {
30
+ const type = ecosystem.trim().toLowerCase();
31
+ if (type === "npm")
32
+ return buildPurl(name, version);
33
+ if (type === "pypi") {
34
+ const distribution = name.toLowerCase().replace(/_/g, "-");
35
+ return `pkg:pypi/${distribution}@${encodePurlVersion(version)}`;
36
+ }
37
+ return null;
38
+ }
39
+ export function purlForSbom(pkg) {
40
+ if (pkg.ecosystem.trim().toLowerCase() !== "npm")
41
+ return null;
42
+ return buildEcosystemPurl(pkg.ecosystem, registryPackageName(pkg), pkg.version);
43
+ }
44
+ /** Two installation aliases may share a purl but need distinct component refs. */
45
+ export function sbomComponentRef(pkg, purl) {
46
+ return pkg.registryName ? `${purl}#installed-as=${encodeURIComponent(pkg.name)}` : purl;
47
+ }
@@ -0,0 +1,129 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import YAML from "yaml";
5
+ import { NPM_PUBLIC_REGISTRY } from "../constants.js";
6
+ /**
7
+ * Where each package manager keeps its registry, mirroring the per-manager table in
8
+ * `cooldown.ts`.
9
+ *
10
+ * npm and pnpm share `.npmrc`, because pnpm reads npm's own config file. Yarn Berry
11
+ * uses its own YAML.
12
+ *
13
+ * Bun is absent on purpose. It keeps its registry in `bunfig.toml`, and we do not
14
+ * parse TOML; adding a dependency for it is a decision of its own, and our small
15
+ * runtime footprint is a stated product property. Half-reading the file with a
16
+ * regex would be worse than not reading it, because a wrong registry is the bug
17
+ * this module exists to fix. Bun therefore behaves exactly as it does today.
18
+ */
19
+ const MANAGER_CONFIG = {
20
+ npm: { file: ".npmrc", format: "ini" },
21
+ pnpm: { file: ".npmrc", format: "ini" },
22
+ yarn: { file: ".yarnrc.yml", format: "yaml" },
23
+ };
24
+ const SCOPED_INI_KEY = /^(@[^:\s]+):registry$/;
25
+ /** Reads `key=value` lines, ignoring comments and section headers. */
26
+ function parseIni(contents) {
27
+ const values = new Map();
28
+ for (const rawLine of contents.split(/\r?\n/)) {
29
+ const line = rawLine.trim();
30
+ if (!line || line.startsWith("#") || line.startsWith(";") || line.startsWith("["))
31
+ continue;
32
+ const eq = line.indexOf("=");
33
+ if (eq === -1)
34
+ continue;
35
+ values.set(line.slice(0, eq).trim(), line.slice(eq + 1).trim());
36
+ }
37
+ return values;
38
+ }
39
+ function fromIni(contents) {
40
+ const values = parseIni(contents);
41
+ const scopes = {};
42
+ for (const [key, value] of values) {
43
+ const scoped = SCOPED_INI_KEY.exec(key);
44
+ if (scoped?.[1] && value)
45
+ scopes[scoped[1]] = value;
46
+ }
47
+ return { registry: values.get("registry") || null, scopes };
48
+ }
49
+ function fromYaml(contents) {
50
+ let doc;
51
+ try {
52
+ doc = YAML.parse(contents);
53
+ }
54
+ catch {
55
+ // A malformed config is the project's problem to fix, not a reason to fail a scan.
56
+ // Falling through to the public registry keeps today's behaviour.
57
+ return { registry: null, scopes: {} };
58
+ }
59
+ if (!doc || typeof doc !== "object")
60
+ return { registry: null, scopes: {} };
61
+ const record = doc;
62
+ const registry = typeof record.npmRegistryServer === "string" ? record.npmRegistryServer : null;
63
+ const scopes = {};
64
+ const npmScopes = record.npmScopes;
65
+ if (npmScopes && typeof npmScopes === "object") {
66
+ for (const [scope, entry] of Object.entries(npmScopes)) {
67
+ if (!entry || typeof entry !== "object")
68
+ continue;
69
+ const server = entry.npmRegistryServer;
70
+ // Yarn writes scopes without the leading @; normalise so lookup is uniform.
71
+ if (typeof server === "string" && server)
72
+ scopes[scope.startsWith("@") ? scope : `@${scope}`] = server;
73
+ }
74
+ }
75
+ return { registry, scopes };
76
+ }
77
+ function readIfPresent(file) {
78
+ try {
79
+ return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null;
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ }
85
+ /**
86
+ * Resolves the registry in the order the package manager itself uses: an environment
87
+ * override first, then the project file, then the user's home file.
88
+ *
89
+ * `env` and `homeDir` are injectable so this is testable without touching the real
90
+ * environment or the developer's own config.
91
+ */
92
+ export function resolveRegistryConfig(args) {
93
+ const env = args.env ?? process.env;
94
+ const homeDir = args.homeDir ?? os.homedir();
95
+ const envRegistry = env.NPM_CONFIG_REGISTRY || env.npm_config_registry;
96
+ if (envRegistry) {
97
+ return { registry: envRegistry, scopes: {}, sourceFile: "NPM_CONFIG_REGISTRY" };
98
+ }
99
+ const config = args.packageManager ? MANAGER_CONFIG[args.packageManager] : undefined;
100
+ if (!config)
101
+ return { registry: NPM_PUBLIC_REGISTRY, scopes: {}, sourceFile: null };
102
+ for (const dir of [args.projectPath, homeDir]) {
103
+ const file = path.join(dir, config.file);
104
+ const contents = readIfPresent(file);
105
+ if (contents === null)
106
+ continue;
107
+ const parsed = config.format === "ini" ? fromIni(contents) : fromYaml(contents);
108
+ // A file that exists but configures no registry is not an answer; keep looking,
109
+ // the way npm continues up its own config chain.
110
+ if (!parsed.registry && Object.keys(parsed.scopes).length === 0)
111
+ continue;
112
+ return {
113
+ registry: parsed.registry || NPM_PUBLIC_REGISTRY,
114
+ scopes: parsed.scopes,
115
+ sourceFile: file,
116
+ };
117
+ }
118
+ return { registry: NPM_PUBLIC_REGISTRY, scopes: {}, sourceFile: null };
119
+ }
120
+ export { packageManagerForSource } from "./package-manager-source.js";
121
+ /** The registry a single package resolves through, honouring its scope. */
122
+ export function registryForPackage(config, packageName) {
123
+ if (packageName.startsWith("@")) {
124
+ const scope = packageName.split("/")[0];
125
+ if (scope && config.scopes[scope])
126
+ return config.scopes[scope];
127
+ }
128
+ return config.registry;
129
+ }
@@ -16,6 +16,14 @@ export function reachesFailOn(findings, failOn) {
16
16
  // cannot disagree. The parenthetical echoes the raw flag value: --fail-on is not
17
17
  // validated and normalizeSeverity falls back to critical, so echoing the
18
18
  // normalized level would show the user a value they never typed.
19
+ // The three finding classes the --fail-on gate ORs, as failingGateSummary
20
+ // names them. Both scan paths build their gate input from this one list, so
21
+ // the wording for a class cannot differ between a single- and multi-folder scan.
22
+ export const GATE_CLASS_LABELS = {
23
+ vulnerability: "vulnerability",
24
+ overrideHygiene: "override hygiene",
25
+ maintenanceRisk: "maintenance risk",
26
+ };
19
27
  export function failingGateSummary(classes, failOn) {
20
28
  if (!failOn)
21
29
  return null;
@@ -1,6 +1,14 @@
1
1
  export function pluralize(count, singular, plural = `${singular}s`) {
2
2
  return count === 1 ? singular : plural;
3
3
  }
4
+ /** End diagnostic text as a sentence without duplicating existing punctuation. */
5
+ export function ensureSentence(message) {
6
+ const text = message.trimEnd();
7
+ return text && !/[.!?]$/.test(text) ? `${text}.` : text;
8
+ }
9
+ export function isOutputStdout(output) {
10
+ return output?.trim() === "-";
11
+ }
4
12
  /** Known top-level cve-lite commands, for typo suggestions on a mistyped first argument. */
5
13
  const KNOWN_COMMANDS = ["advisories", "install-skill", "config", "overrides"];
6
14
  /**
@@ -1,7 +1,7 @@
1
1
  import dns from "node:dns";
2
2
  import { URL } from "node:url";
3
3
  const OFFICIAL_OSV_HOSTS = ["api.osv.dev"];
4
- // IPv4 special-purpose CIDRs — numerical match replaces error-prone regex
4
+ // IPv4 special-purpose CIDRs - numerical match replaces error-prone regex
5
5
  // https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
6
6
  const PRIVATE_IPV4_CIDRS = [
7
7
  "0.0.0.0/8", // "this network"
@@ -181,7 +181,7 @@ export function isPrivateOrReservedIp(ip) {
181
181
  return isPrivateOrReservedIpv6(ip);
182
182
  }
183
183
  // Strip brackets from IPv6 literal hostnames (e.g. "[::1]" → "::1")
184
- function stripIpv6Brackets(hostname) {
184
+ export function stripIpv6Brackets(hostname) {
185
185
  if (hostname.startsWith("[") && hostname.endsWith("]")) {
186
186
  return hostname.slice(1, -1);
187
187
  }
@@ -197,7 +197,7 @@ export async function validateOsvUrl(url, allowPrivate) {
197
197
  if (isOfficialOsv(url))
198
198
  return undefined;
199
199
  // Layer 2: Resolve DNS and check ALL addresses
200
- // Strip brackets from IPv6 literal hostnames — dns.lookup expects bare addresses
200
+ // Strip brackets from IPv6 literal hostnames - dns.lookup expects bare addresses
201
201
  const lookupHost = stripIpv6Brackets(parsed.hostname);
202
202
  const addresses = await new Promise((resolve, reject) => {
203
203
  dns.lookup(lookupHost, { all: true }, (err, addresses) => {
@@ -215,7 +215,7 @@ export async function validateOsvUrl(url, allowPrivate) {
215
215
  throw new Error(`--osv-url resolves to private/reserved IP (${ipList}). ` +
216
216
  `Use --allow-private-osv-url for internal mirrors.`);
217
217
  }
218
- // Layer 3: Explicit bypass — return warning for caller to emit
218
+ // Layer 3: Explicit bypass - return warning for caller to emit
219
219
  return (`Warning: --allow-private-osv-url is set. ` +
220
220
  `Requests may access internal host (${ipList}).`);
221
221
  }
@@ -1,5 +1,14 @@
1
1
  import semver from "semver";
2
- export function looksLikeVersion(value) {
2
+ import { pep440Scheme } from "./versions/pep440.js";
3
+ // `filter` and `map` pass the element index as an extra argument. `sort` does
4
+ // not. A non-string argument stays on the npm path. Only the ecosystem name
5
+ // "pypi" selects PEP 440. Callers that omit it keep the historical semver behavior.
6
+ export function isPep440Ecosystem(ecosystem) {
7
+ return typeof ecosystem === "string" && ecosystem.trim().toLowerCase() === "pypi";
8
+ }
9
+ export function looksLikeVersion(value, ecosystem) {
10
+ if (isPep440Ecosystem(ecosystem))
11
+ return pep440Scheme.looksLikeVersion(value);
3
12
  return /^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][^/]+)?$/.test(value);
4
13
  }
5
14
  // Matches a well-formed X.Y.Z version, capturing an optional dot-separated
@@ -10,7 +19,7 @@ export function looksLikeVersion(value) {
10
19
  // through to the flat-token fallback, which would reintroduce the exact
11
20
  // precedence bug this file fixes.
12
21
  const VERSION_SHAPE = /^(\d+)\.(\d+)\.(\d+)(?:-([^/+]+))?(?:\+.*)?$/;
13
- // module-level; safe to grow unbounded — a single scan sees at most
22
+ // module-level; safe to grow unbounded - a single scan sees at most
14
23
  // a few hundred unique version strings, and the cache is discarded when the process exits.
15
24
  const parsedVersionCache = new Map();
16
25
  export function getVersionCacheSize() {
@@ -93,7 +102,9 @@ function comparePrerelease(a, b) {
93
102
  }
94
103
  return 0;
95
104
  }
96
- export function compareVersions(a, b) {
105
+ export function compareVersions(a, b, ecosystem) {
106
+ if (isPep440Ecosystem(ecosystem))
107
+ return pep440Scheme.compare(a, b);
97
108
  const pa = parseVersion(a);
98
109
  const pb = parseVersion(b);
99
110
  if (!pa || !pb)
@@ -111,8 +122,8 @@ export function parseExactManifestVersion(spec) {
111
122
  return null;
112
123
  }
113
124
  export function isBreakingUpgrade(from, to) {
114
- const [fromMajor, fromMinor] = from.split(".").map(Number);
115
- const [toMajor, toMinor] = to.split(".").map(Number);
125
+ const [fromMajor, fromMinor, fromPatch] = from.split(".").map(n => parseInt(n, 10));
126
+ const [toMajor, toMinor, toPatch] = to.split(".").map(n => parseInt(n, 10));
116
127
  if (Number.isNaN(fromMajor) || Number.isNaN(toMajor))
117
128
  return false;
118
129
  if (toMajor > fromMajor)
@@ -120,11 +131,33 @@ export function isBreakingUpgrade(from, to) {
120
131
  // Under semver, 0.x releases treat the minor as the breaking position
121
132
  // (^0.21.1 resolves to >=0.21.1 <0.22.0), so a 0.x cross-minor bump is breaking.
122
133
  if (fromMajor === 0 && toMajor === 0) {
123
- return !Number.isNaN(fromMinor) && !Number.isNaN(toMinor) && toMinor > fromMinor;
134
+ if (Number.isNaN(fromMinor) || Number.isNaN(toMinor))
135
+ return false;
136
+ if (toMinor > fromMinor)
137
+ return true;
138
+ // 0.0.x releases treat the patch as the breaking position (^0.0.3 resolves
139
+ // to >=0.0.3 <0.0.4), so any 0.0.x patch bump is breaking.
140
+ if (fromMinor === 0 && toMinor === 0) {
141
+ return !Number.isNaN(fromPatch) && !Number.isNaN(toPatch) && toPatch > fromPatch;
142
+ }
124
143
  }
125
144
  return false;
126
145
  }
127
- export function isPreReleaseVersion(version) {
146
+ /**
147
+ * True when a recorded version is a local protocol reference rather than a
148
+ * released version: `workspace:` for a monorepo member, `file:` or `link:` for
149
+ * a path dependency. These name source the project supplies itself, so there is
150
+ * no published release of them to install and they can never be an upgrade
151
+ * target. Bun and Yarn write a `workspace:` reference into the lockfile for a
152
+ * member a sibling depends on, which is why such an entry can resolve to a
153
+ * PackageRef at all.
154
+ */
155
+ export function isLocalProtocolVersion(version) {
156
+ return /^(?:workspace|file|link):/.test(version.trim());
157
+ }
158
+ export function isPreReleaseVersion(version, ecosystem) {
159
+ if (isPep440Ecosystem(ecosystem))
160
+ return pep440Scheme.isPreRelease(version);
128
161
  return /^\d+\.\d+\.\d+-[^\s]+$/.test(version);
129
162
  }
130
163
  export function normalizeRawVersion(value) {
@@ -208,7 +241,9 @@ export function coerceVersion(input) {
208
241
  * override specs, where a bare `1.22` is the range `1.22.x` rather than 1.22.0.
209
242
  */
210
243
  const ADVISORY_VERSION = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/;
211
- export function normalizeAdvisoryVersion(value) {
244
+ export function normalizeAdvisoryVersion(value, ecosystem) {
245
+ if (isPep440Ecosystem(ecosystem))
246
+ return pep440Scheme.normalizeAdvisoryVersion(value);
212
247
  if (!value)
213
248
  return null;
214
249
  const match = ADVISORY_VERSION.exec(value.trim());
@@ -266,6 +301,10 @@ export function positionAgainstRange(version, range) {
266
301
  return "outside";
267
302
  }
268
303
  catch {
304
+ // satisfies guards the SemVer constructor inside Range.test(), which catches
305
+ // and returns false; ltr/gtr route through outside(), which does not. Only
306
+ // the latter two throw, and only on a component above MAX_SAFE_INTEGER.
307
+ // Keep the guard: dropping it reintroduces the crash for those two calls.
269
308
  return null;
270
309
  }
271
310
  }
@@ -0,0 +1,191 @@
1
+ import { compareVersions, normalizeAdvisoryVersion } from "../version.js";
2
+ /**
3
+ * Affected windows of one PyPI range.
4
+ *
5
+ * Events are sorted by PEP 440 order before they are paired, so a range
6
+ * written with the 2.x fix ahead of the 1.x fix describes the same windows
7
+ * as the sorted form. `introduced: "0"` sorts before every version, including
8
+ * `0.dev0`. Equal versions keep file order.
9
+ *
10
+ * The walk follows the OSV evaluation: an introduced opens a window, a later
11
+ * introduced does not split a window that is already open, `fixed` closes it
12
+ * exclusively, and `last_affected` closes it inclusively. A version is affected
13
+ * when it sits in any of those windows. A fix from one window cannot clear
14
+ * another.
15
+ *
16
+ * A boundary that does not parse is left off the timeline. An unreadable
17
+ * `fixed` or `last_affected` also drops a trailing open window, because that
18
+ * boundary might have closed it. Events after that closer are a new range,
19
+ * so a later fix cannot close the window the unreadable value may already
20
+ * have closed.
21
+ */
22
+ export function readPep440Range(events) {
23
+ const segments = splitAtUnreadableClosers(events);
24
+ if (segments.length <= 1)
25
+ return readPep440Segment(events);
26
+ const windows = [];
27
+ const fixes = [];
28
+ const unreadable = [];
29
+ for (const segment of segments) {
30
+ const read = readPep440Segment(segment);
31
+ windows.push(...read.windows);
32
+ fixes.push(...read.fixes);
33
+ unreadable.push(...read.unreadable);
34
+ }
35
+ return { windows, fixes, unreadable };
36
+ }
37
+ function splitAtUnreadableClosers(events) {
38
+ const segments = [];
39
+ let current = [];
40
+ for (const event of events) {
41
+ current.push(event);
42
+ const fixedUnreadable = event.fixed !== undefined && !normalizeAdvisoryVersion(event.fixed, "PyPI");
43
+ const lastUnreadable = event.last_affected !== undefined && !normalizeAdvisoryVersion(event.last_affected, "PyPI");
44
+ if (fixedUnreadable || lastUnreadable) {
45
+ segments.push(current);
46
+ current = [];
47
+ }
48
+ }
49
+ if (current.length > 0)
50
+ segments.push(current);
51
+ return segments;
52
+ }
53
+ function readPep440Segment(events) {
54
+ const points = [];
55
+ const unreadable = [];
56
+ const fixes = [];
57
+ const lowerBound = unreadableLowerBound(events);
58
+ let index = 0;
59
+ for (const event of events) {
60
+ if (event.introduced !== undefined) {
61
+ pushBoundary(points, unreadable, "introduced", event.introduced, index, lowerBound);
62
+ index += 1;
63
+ }
64
+ if (event.fixed !== undefined) {
65
+ const canon = normalizeAdvisoryVersion(event.fixed, "PyPI");
66
+ if (canon)
67
+ fixes.push(canon);
68
+ pushBoundary(points, unreadable, "fixed", event.fixed, index, lowerBound);
69
+ index += 1;
70
+ }
71
+ if (event.last_affected !== undefined) {
72
+ pushBoundary(points, unreadable, "last_affected", event.last_affected, index, lowerBound);
73
+ index += 1;
74
+ }
75
+ }
76
+ points.sort((left, right) => {
77
+ const leftSentinel = left.kind === "introduced" && left.raw === "0";
78
+ const rightSentinel = right.kind === "introduced" && right.raw === "0";
79
+ if (leftSentinel !== rightSentinel)
80
+ return leftSentinel ? -1 : 1;
81
+ if (!leftSentinel) {
82
+ const compared = compareVersions(left.canonical, right.canonical, "PyPI");
83
+ if (compared !== 0)
84
+ return compared;
85
+ }
86
+ return left.index - right.index;
87
+ });
88
+ const windows = [];
89
+ let open = false;
90
+ let introduced = null;
91
+ for (const point of points) {
92
+ if (point.kind === "introduced") {
93
+ if (!open) {
94
+ open = true;
95
+ introduced = storedIntroduced(point);
96
+ }
97
+ continue;
98
+ }
99
+ if (!open)
100
+ continue;
101
+ windows.push({
102
+ introduced,
103
+ fixed: point.kind === "fixed" ? point.canonical : null,
104
+ lastAffected: point.kind === "last_affected" ? point.canonical : null,
105
+ });
106
+ open = false;
107
+ introduced = null;
108
+ }
109
+ const unreadableCloser = unreadable.some(boundary => boundary.field === "fixed" || boundary.field === "last_affected");
110
+ if (open && !unreadableCloser) {
111
+ windows.push({ introduced, fixed: null, lastAffected: null });
112
+ }
113
+ return { windows, fixes, unreadable };
114
+ }
115
+ /**
116
+ * The raw event `"0"` is the OSV sentinel. A version whose canonical form is
117
+ * also `"0"` (`v0`, `00`, `0!0`) is version 0, stored as `"0.0"` so a caller
118
+ * does not treat it as the sentinel.
119
+ */
120
+ function storedIntroduced(point) {
121
+ if (point.raw === "0")
122
+ return "0";
123
+ if (point.canonical === "0")
124
+ return "0.0";
125
+ return point.canonical;
126
+ }
127
+ function pushBoundary(points, unreadable, field, value, index, lowerBound) {
128
+ if (field === "introduced" && value === "0") {
129
+ points.push({ kind: field, raw: value, canonical: "0", index });
130
+ return;
131
+ }
132
+ const canonical = normalizeAdvisoryVersion(value, "PyPI");
133
+ if (!canonical) {
134
+ unreadable.push({ field, value, introduced: lowerBound });
135
+ return;
136
+ }
137
+ points.push({ kind: field, raw: value, canonical, index });
138
+ }
139
+ /**
140
+ * The introduced value stored beside an unreadable boundary.
141
+ * A version below every concrete introduced value is outside every window,
142
+ * so the caller can ignore the unreadable boundary for that version.
143
+ */
144
+ function unreadableLowerBound(events) {
145
+ let sawSentinel = false;
146
+ let lowest = null;
147
+ for (const event of events) {
148
+ if (event.introduced === undefined)
149
+ continue;
150
+ if (event.introduced === "0") {
151
+ sawSentinel = true;
152
+ continue;
153
+ }
154
+ const canonical = normalizeAdvisoryVersion(event.introduced, "PyPI");
155
+ if (!canonical)
156
+ return null;
157
+ const stored = canonical === "0" ? "0.0" : canonical;
158
+ if (lowest === null || compareVersions(stored, lowest, "PyPI") < 0)
159
+ lowest = stored;
160
+ }
161
+ if (sawSentinel)
162
+ return "0";
163
+ return lowest;
164
+ }
165
+ /** True when `version` is inside one window produced by `readPep440Range`. */
166
+ export function versionInPep440Window(version, window) {
167
+ if (window.introduced && window.introduced !== "0") {
168
+ if (compareVersions(version, window.introduced, "PyPI") < 0)
169
+ return false;
170
+ }
171
+ if (window.fixed && compareVersions(version, window.fixed, "PyPI") >= 0)
172
+ return false;
173
+ if (window.lastAffected && compareVersions(version, window.lastAffected, "PyPI") > 0)
174
+ return false;
175
+ return true;
176
+ }
177
+ /**
178
+ * True when an unreadable boundary might still describe a window that
179
+ * contains `version`. A version below the boundary's introduced value is
180
+ * outside that window.
181
+ */
182
+ export function pep440UnreadableApplies(version, boundary) {
183
+ if (boundary.field === "introduced")
184
+ return true;
185
+ if (!boundary.introduced || boundary.introduced === "0")
186
+ return true;
187
+ const introduced = normalizeAdvisoryVersion(boundary.introduced, "PyPI");
188
+ if (!introduced)
189
+ return true;
190
+ return compareVersions(version, introduced, "PyPI") >= 0;
191
+ }