@mark1russell7/package-id 0.0.0-stage → 0.0.2

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/src/vers.ts ADDED
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Version ranges in the `vers` format of the purl specification, for example `vers:npm/>=1.0.0|<1.2.3`. The functions
3
+ * parse a range, format it and tell if a version is in it, with the version order of the scheme.
4
+ */
5
+ import { compareVersions } from "./version.ts";
6
+
7
+ /** The comparators of a `vers` constraint. */
8
+ export type VersComparator = "=" | "!=" | "<" | "<=" | ">" | ">=";
9
+
10
+ /** One constraint of a range: a comparator and a version. */
11
+ export interface VersConstraint {
12
+ readonly comparator: VersComparator;
13
+ readonly version: string;
14
+ }
15
+
16
+ /** A version range. A range with the constraint `*` holds each version, and its list of constraints is empty. */
17
+ export interface Vers {
18
+ /** The version scheme, for example `npm`, `pypi` or `deb`. */
19
+ readonly scheme: string;
20
+ /** True: the range is `*`, so it holds each version. */
21
+ readonly all: boolean;
22
+ readonly constraints: readonly VersConstraint[];
23
+ }
24
+
25
+ // The longer comparators come first, so `<=` is not read as `<` and a version that starts with `=`.
26
+ const COMPARATORS: readonly VersComparator[] = ["!=", "<=", ">=", "<", ">", "="];
27
+
28
+ /** This function reads one constraint, for example `>=1.0.0`. A constraint with no comparator has the comparator `=`. */
29
+ function parseConstraint(text: string): VersConstraint | undefined {
30
+ const trimmed = text.trim();
31
+ const comparator = COMPARATORS.find((c) => trimmed.startsWith(c)) ?? "=";
32
+ const raw = trimmed.slice(trimmed.startsWith(comparator) ? comparator.length : 0).trim();
33
+ if (raw === "") return undefined;
34
+ let version: string;
35
+ try {
36
+ version = decodeURIComponent(raw);
37
+ } catch {
38
+ return undefined;
39
+ }
40
+ return { comparator, version };
41
+ }
42
+
43
+ /** This function reads a `vers` text. A text that is not a range gives `undefined`. */
44
+ export function parseVers(text: string): Vers | undefined {
45
+ const match = /^vers:([A-Za-z0-9.+-]+)\/(.+)$/.exec(text.replace(/\s+/g, ""));
46
+ if (match === null) return undefined;
47
+ const scheme = match[1]!.toLowerCase();
48
+ const body = match[2]!;
49
+ if (body === "*") return { scheme, all: true, constraints: [] };
50
+ const constraints: VersConstraint[] = [];
51
+ for (const part of body.split("|")) {
52
+ const constraint = parseConstraint(part);
53
+ if (constraint === undefined) return undefined;
54
+ constraints.push(constraint);
55
+ }
56
+ return { scheme, all: false, constraints };
57
+ }
58
+
59
+ // The characters that a version keeps in a `vers` text: the others are percent-encoded.
60
+ const encodeVersion = (version: string): string => version.replace(/[^A-Za-z0-9.+~_:-]/g, (c) => encodeURIComponent(c));
61
+
62
+ /**
63
+ * This function gives the `vers` text of a range. The constraints come in the order of the versions, when the scheme
64
+ * has a known order. The comparator `=` has no sign, as the specification tells.
65
+ */
66
+ export function formatVers(vers: Vers): string {
67
+ if (vers.all) return `vers:${vers.scheme}/*`;
68
+ const sorted = sortConstraints(vers.scheme, vers.constraints) ?? vers.constraints;
69
+ const body = sorted.map((c) => `${c.comparator === "=" ? "" : c.comparator}${encodeVersion(c.version)}`).join("|");
70
+ return `vers:${vers.scheme}/${body}`;
71
+ }
72
+
73
+ // The constraints in the order of their versions, or `undefined` when a version is not a version of the scheme.
74
+ function sortConstraints(scheme: string, constraints: readonly VersConstraint[]): VersConstraint[] | undefined {
75
+ let unknown = false;
76
+ const sorted = [...constraints].sort((a, b) => {
77
+ const c = compareVersions(scheme, a.version, b.version);
78
+ if (c === undefined) unknown = true;
79
+ return c ?? 0;
80
+ });
81
+ return unknown ? undefined : sorted;
82
+ }
83
+
84
+ /**
85
+ * This function tells if a version is in a range, with the algorithm of the `vers` specification. The result is
86
+ * `undefined` when the scheme has no known order, or when a version is not a version of the scheme. Thus a caller
87
+ * does not take an unknown result as a match or as no match.
88
+ */
89
+ export function versContains(vers: Vers, version: string): boolean | undefined {
90
+ if (vers.all) return true;
91
+ const compare = (a: string, b: string): number | undefined => compareVersions(vers.scheme, a, b);
92
+ for (const constraint of vers.constraints) {
93
+ const c = compare(version, constraint.version);
94
+ if (c === undefined) return undefined;
95
+ if (c === 0 && ["=", "<=", ">="].includes(constraint.comparator)) return true;
96
+ if (c === 0 && constraint.comparator === "!=") return false;
97
+ }
98
+ const ranged = sortConstraints(
99
+ vers.scheme,
100
+ vers.constraints.filter((c) => c.comparator !== "=" && c.comparator !== "!="),
101
+ );
102
+ if (ranged === undefined) return undefined;
103
+ if (ranged.length === 0) {
104
+ // Only `!=` constraints that the version does not equal: the version is in the range.
105
+ return vers.constraints.some((c) => c.comparator === "!=");
106
+ }
107
+ const below = (c: VersConstraint): boolean => c.comparator === "<" || c.comparator === "<=";
108
+ const above = (c: VersConstraint): boolean => c.comparator === ">" || c.comparator === ">=";
109
+ const first = ranged[0]!;
110
+ const last = ranged[ranged.length - 1]!;
111
+ if (below(first) && compare(version, first.version)! < 0) return true;
112
+ if (above(last) && compare(version, last.version)! > 0) return true;
113
+ for (let i = 0; i + 1 < ranged.length; i++) {
114
+ const low = ranged[i]!;
115
+ const high = ranged[i + 1]!;
116
+ if (above(low) && below(high) && compare(version, low.version)! > 0 && compare(version, high.version)! < 0) return true;
117
+ }
118
+ return false;
119
+ }
120
+
121
+ /**
122
+ * This function gives the end of the part of a range that holds a version, when that end is a constraint `<`. For the
123
+ * range of an advisory, it is the first fixed version above the version. The result is `undefined` for a version out
124
+ * of the range, or for an unknown order. It is also `undefined` for a part with no such end: `<=`, an open end or `=`.
125
+ */
126
+ export function versEnd(vers: Vers, version: string): string | undefined {
127
+ if (vers.all || versContains(vers, version) !== true) return undefined;
128
+ if (vers.constraints.some((c) => c.comparator === "=" && compareVersions(vers.scheme, version, c.version) === 0)) return undefined;
129
+ const ranged = sortConstraints(
130
+ vers.scheme,
131
+ vers.constraints.filter((c) => c.comparator !== "=" && c.comparator !== "!="),
132
+ );
133
+ const next = ranged?.find((c) => compareVersions(vers.scheme, version, c.version)! < 0);
134
+ return next?.comparator === "<" ? next.version : undefined;
135
+ }
package/src/version.ts ADDED
@@ -0,0 +1,283 @@
1
+ /**
2
+ * The version order of each ecosystem: SemVer, Go modules, PEP 440, Debian and RPM. Each function compares two
3
+ * versions of one scheme. A text that is not a version of the scheme gives `undefined`, not a guess.
4
+ */
5
+
6
+ /** The version schemes that this module compares. */
7
+ export type VersionScheme = "semver" | "golang" | "pypi" | "deb" | "rpm";
8
+
9
+ /** The version scheme of each purl type whose order this module knows. */
10
+ const TYPE_SCHEMES: ReadonlyMap<string, VersionScheme> = new Map([
11
+ ["npm", "semver"],
12
+ ["cargo", "semver"],
13
+ ["semver", "semver"],
14
+ ["golang", "golang"],
15
+ ["pypi", "pypi"],
16
+ ["deb", "deb"],
17
+ ["rpm", "rpm"],
18
+ ]);
19
+
20
+ /** This function gives the version scheme of a purl type, or `undefined` for a type whose order this module does not know. */
21
+ export function versionScheme(type: string): VersionScheme | undefined {
22
+ return TYPE_SCHEMES.get(type.toLowerCase());
23
+ }
24
+
25
+ /**
26
+ * This function compares two versions of one scheme. The result is below 0 when `a` comes before `b`, 0 when they are
27
+ * equal and above 0 when `a` comes after `b`. When a text is not a version of the scheme, the result is `undefined`.
28
+ */
29
+ export function compareVersions(scheme: string, a: string, b: string): number | undefined {
30
+ switch (scheme) {
31
+ case "semver":
32
+ case "npm":
33
+ case "cargo":
34
+ return compareSemver(a, b);
35
+ case "golang":
36
+ return compareGo(a, b);
37
+ case "pypi":
38
+ return comparePep440(a, b);
39
+ case "deb":
40
+ return compareDebian(a, b);
41
+ case "rpm":
42
+ return compareRpm(a, b);
43
+ default:
44
+ return undefined;
45
+ }
46
+ }
47
+
48
+ const sign = (n: number): number => (n < 0 ? -1 : n > 0 ? 1 : 0);
49
+ const compareText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
50
+ const compareDigits = (a: string, b: string): number => {
51
+ const x = a.replace(/^0+(?=\d)/, "");
52
+ const y = b.replace(/^0+(?=\d)/, "");
53
+ return x.length !== y.length ? sign(x.length - y.length) : compareText(x, y);
54
+ };
55
+
56
+ // SemVer 2.0.0. The build metadata does not change the order.
57
+ const SEMVER = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
58
+
59
+ /** The parts of a SemVer version that decide its order. */
60
+ interface Semver {
61
+ readonly core: readonly [string, string, string];
62
+ readonly pre: readonly string[];
63
+ }
64
+
65
+ function parseSemver(text: string): Semver | undefined {
66
+ const match = SEMVER.exec(text.trim().replace(/^=/, ""));
67
+ if (match === null) return undefined;
68
+ return { core: [match[1]!, match[2]!, match[3]!], pre: match[4] === undefined ? [] : match[4].split(".") };
69
+ }
70
+
71
+ function compareSemverParts(x: Semver, y: Semver): number {
72
+ for (let i = 0; i < 3; i++) {
73
+ const c = compareDigits(x.core[i]!, y.core[i]!);
74
+ if (c !== 0) return c;
75
+ }
76
+ // A version with a pre-release comes before the same version with no pre-release.
77
+ if (x.pre.length === 0 || y.pre.length === 0) return sign(y.pre.length - x.pre.length);
78
+ for (let i = 0; i < Math.min(x.pre.length, y.pre.length); i++) {
79
+ const p = x.pre[i]!;
80
+ const q = y.pre[i]!;
81
+ const pn = /^\d+$/.test(p);
82
+ const qn = /^\d+$/.test(q);
83
+ const c = pn && qn ? compareDigits(p, q) : pn ? -1 : qn ? 1 : compareText(p, q);
84
+ if (c !== 0) return c;
85
+ }
86
+ return sign(x.pre.length - y.pre.length);
87
+ }
88
+
89
+ /** This function compares two SemVer 2.0.0 versions. It accepts a leading `v` or `=`, as npm does. */
90
+ export function compareSemver(a: string, b: string): number | undefined {
91
+ const x = parseSemver(a);
92
+ const y = parseSemver(b);
93
+ return x === undefined || y === undefined ? undefined : compareSemverParts(x, y);
94
+ }
95
+
96
+ /**
97
+ * This function compares two versions of Go modules. A Go version starts with `v` and follows SemVer. A pseudo-version is
98
+ * a pre-release, so it has its place in the order of SemVer. The suffix `+incompatible` is build metadata.
99
+ */
100
+ export function compareGo(a: string, b: string): number | undefined {
101
+ if (!a.startsWith("v") || !b.startsWith("v")) return undefined;
102
+ return compareSemver(a, b);
103
+ }
104
+
105
+ // PEP 440: the pattern of the version specification of the Python packaging guide.
106
+ const PEP440 =
107
+ /^\s*v?(?:(?:(\d+)!)?(\d+(?:\.\d+)*)(?:[-_.]?(a|b|c|rc|alpha|beta|pre|preview)[-_.]?(\d+)?)?(?:-(\d+)|[-_.]?(post|rev|r)[-_.]?(\d+)?)?(?:[-_.]?(dev)[-_.]?(\d+)?)?)(?:\+([a-z0-9]+(?:[-_.][a-z0-9]+)*))?\s*$/i;
108
+
109
+ /** The parts of a PEP 440 version that decide its order. */
110
+ interface Pep440 {
111
+ readonly epoch: number;
112
+ readonly release: readonly number[];
113
+ /** The pre-release as a rank (a 0, b 1, rc 2) and a number. */
114
+ readonly pre?: readonly [number, number];
115
+ readonly post?: number;
116
+ readonly dev?: number;
117
+ readonly local: readonly string[];
118
+ }
119
+
120
+ const PRE_RANK: Readonly<Record<string, number>> = { a: 0, alpha: 0, b: 1, beta: 1, c: 2, rc: 2, pre: 2, preview: 2 };
121
+
122
+ function parsePep440(text: string): Pep440 | undefined {
123
+ const m = PEP440.exec(text);
124
+ if (m === null) return undefined;
125
+ const release = m[2]!.split(".").map(Number);
126
+ while (release.length > 1 && release[release.length - 1] === 0) release.pop();
127
+ const post = m[5] !== undefined ? Number(m[5]) : m[6] !== undefined ? Number(m[7] ?? 0) : undefined;
128
+ return {
129
+ epoch: Number(m[1] ?? 0),
130
+ release,
131
+ ...(m[3] === undefined ? {} : { pre: [PRE_RANK[m[3].toLowerCase()]!, Number(m[4] ?? 0)] as const }),
132
+ ...(post === undefined ? {} : { post }),
133
+ ...(m[8] === undefined ? {} : { dev: Number(m[9] ?? 0) }),
134
+ local: m[10] === undefined ? [] : m[10].toLowerCase().split(/[-_.]/),
135
+ };
136
+ }
137
+
138
+ function compareNumbers(a: readonly number[], b: readonly number[]): number {
139
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
140
+ const c = sign((a[i] ?? 0) - (b[i] ?? 0));
141
+ if (c !== 0) return c;
142
+ }
143
+ return 0;
144
+ }
145
+
146
+ /** This function compares two PEP 440 versions, with the order of the Python packaging specification. */
147
+ export function comparePep440(a: string, b: string): number | undefined {
148
+ const x = parsePep440(a);
149
+ const y = parsePep440(b);
150
+ if (x === undefined || y === undefined) return undefined;
151
+ const epoch = sign(x.epoch - y.epoch);
152
+ if (epoch !== 0) return epoch;
153
+ const release = compareNumbers(x.release, y.release);
154
+ if (release !== 0) return release;
155
+ // A dev release with no pre-release and no post-release comes before each pre-release.
156
+ const preKey = (v: Pep440): readonly number[] => (v.pre !== undefined ? [0, ...v.pre] : v.post === undefined && v.dev !== undefined ? [-1] : [1]);
157
+ const pre = compareNumbers(preKey(x), preKey(y));
158
+ if (pre !== 0) return pre;
159
+ const postKey = (v: Pep440): readonly number[] => (v.post === undefined ? [-1] : [0, v.post]);
160
+ const post = compareNumbers(postKey(x), postKey(y));
161
+ if (post !== 0) return post;
162
+ const devKey = (v: Pep440): readonly number[] => (v.dev === undefined ? [1] : [0, v.dev]);
163
+ const dev = compareNumbers(devKey(x), devKey(y));
164
+ if (dev !== 0) return dev;
165
+ return compareLocal(x.local, y.local);
166
+ }
167
+
168
+ // A local version comes after the same version with no local part. A number segment comes after a text segment.
169
+ function compareLocal(a: readonly string[], b: readonly string[]): number {
170
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
171
+ const p = a[i]!;
172
+ const q = b[i]!;
173
+ const pn = /^\d+$/.test(p);
174
+ const qn = /^\d+$/.test(q);
175
+ const c = pn && qn ? compareDigits(p, q) : pn ? 1 : qn ? -1 : compareText(p, q);
176
+ if (c !== 0) return c;
177
+ }
178
+ return sign(a.length - b.length);
179
+ }
180
+
181
+ // The order of a character of a Debian version: `~` comes before the end, the end before a letter, a letter before
182
+ // each other character. A digit has the rank of the end, as in dpkg.
183
+ function debianRank(text: string, i: number): number {
184
+ if (i >= text.length) return 0;
185
+ const c = text[i]!;
186
+ if (/d/.test(c)) return 0;
187
+ if (c === "~") return -1;
188
+ if (/[A-Za-z]/.test(c)) return c.charCodeAt(0);
189
+ return c.charCodeAt(0) + 256;
190
+ }
191
+
192
+ // The comparison of dpkg: parts with no digit and parts of digits, one after the other.
193
+ function compareDebianPart(a: string, b: string): number {
194
+ let i = 0;
195
+ let j = 0;
196
+ while (i < a.length || j < b.length) {
197
+ while ((i < a.length && !/\d/.test(a[i]!)) || (j < b.length && !/\d/.test(b[j]!))) {
198
+ const c = debianRank(a, i) - debianRank(b, j);
199
+ if (c !== 0) return sign(c);
200
+ i++;
201
+ j++;
202
+ }
203
+ let p = "";
204
+ let q = "";
205
+ while (i < a.length && /\d/.test(a[i]!)) p += a[i++];
206
+ while (j < b.length && /\d/.test(b[j]!)) q += b[j++];
207
+ const c = compareDigits(p || "0", q || "0");
208
+ if (c !== 0) return c;
209
+ }
210
+ return 0;
211
+ }
212
+
213
+ const DEBIAN = /^(?:(\d+):)?([0-9][A-Za-z0-9.+~:-]*?)(?:-([A-Za-z0-9.+~]+))?$/;
214
+
215
+ /** This function compares two Debian versions (`[epoch:]upstream[-revision]`) with the order of dpkg. */
216
+ export function compareDebian(a: string, b: string): number | undefined {
217
+ const x = DEBIAN.exec(a.trim());
218
+ const y = DEBIAN.exec(b.trim());
219
+ if (x === null || y === null) return undefined;
220
+ const epoch = compareDigits(x[1] ?? "0", y[1] ?? "0");
221
+ if (epoch !== 0) return epoch;
222
+ const upstream = compareDebianPart(x[2]!, y[2]!);
223
+ if (upstream !== 0) return upstream;
224
+ return compareDebianPart(x[3] ?? "0", y[3] ?? "0");
225
+ }
226
+
227
+ // The comparison of rpmvercmp: segments of letters or digits. `~` comes before each other thing, also the end. `^` comes
228
+ // after the end, but before each other segment.
229
+ function rpmvercmp(a: string, b: string): number {
230
+ if (a === b) return 0;
231
+ let i = 0;
232
+ let j = 0;
233
+ for (;;) {
234
+ while (i < a.length && !/[A-Za-z0-9~^]/.test(a[i]!)) i++;
235
+ while (j < b.length && !/[A-Za-z0-9~^]/.test(b[j]!)) j++;
236
+ const ca = a[i];
237
+ const cb = b[j];
238
+ if (ca === "~" || cb === "~") {
239
+ if (ca !== "~") return 1;
240
+ if (cb !== "~") return -1;
241
+ i++;
242
+ j++;
243
+ continue;
244
+ }
245
+ if (ca === "^" || cb === "^") {
246
+ if (ca === undefined) return -1;
247
+ if (cb === undefined) return 1;
248
+ if (ca !== "^") return 1;
249
+ if (cb !== "^") return -1;
250
+ i++;
251
+ j++;
252
+ continue;
253
+ }
254
+ if (ca === undefined || cb === undefined) break;
255
+ const digits = /\d/.test(ca);
256
+ const same = digits ? /\d/ : /[A-Za-z]/;
257
+ let p = "";
258
+ let q = "";
259
+ while (i < a.length && same.test(a[i]!)) p += a[i++];
260
+ while (j < b.length && same.test(b[j]!)) q += b[j++];
261
+ // A segment of digits comes after a segment of letters.
262
+ if (q === "") return digits ? 1 : -1;
263
+ const c = digits ? compareDigits(p, q) : compareText(p, q);
264
+ if (c !== 0) return c;
265
+ }
266
+ if (i >= a.length && j >= b.length) return 0;
267
+ return i >= a.length ? -1 : 1;
268
+ }
269
+
270
+ const RPM = /^(?:(\d+):)?([^-]+)(?:-([^-]+))?$/;
271
+
272
+ /** This function compares two RPM versions (`[epoch:]version[-release]`) with the order of `rpmvercmp`. */
273
+ export function compareRpm(a: string, b: string): number | undefined {
274
+ const x = RPM.exec(a.trim());
275
+ const y = RPM.exec(b.trim());
276
+ if (x === null || y === null) return undefined;
277
+ const epoch = compareDigits(x[1] ?? "0", y[1] ?? "0");
278
+ if (epoch !== 0) return epoch;
279
+ const version = rpmvercmp(x[2]!, y[2]!);
280
+ if (version !== 0) return version;
281
+ // A version with no release comes before each release of that version. Thus a check of a fix does not take it as fixed.
282
+ return rpmvercmp(x[3] ?? "", y[3] ?? "");
283
+ }