@mark1russell7/package-id 0.0.1 → 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/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # @mark1russell7/package-id
2
2
 
3
- Package identities as plain functions with no fetch. The first part is the package URL (purl) of the [purl specification](https://github.com/package-url/purl-spec).
3
+ Package identities as plain functions with no fetch. The parts are the package URL (purl) of the [purl specification](https://github.com/package-url/purl-spec), the version order of each ecosystem and the version ranges of the [vers specification](https://github.com/package-url/vers-spec).
4
4
 
5
5
  ```ts
6
- import { formatPurl, osvPurl, packagePurlOf, parsePurl } from "@mark1russell7/package-id";
6
+ import { compareVersions, formatPurl, osvPurl, packagePurlOf, parsePurl, parseVers, versContains } from "@mark1russell7/package-id";
7
7
 
8
8
  parsePurl("pkg:npm/%40angular/animation@12.3.1");
9
9
  // { type: "npm", namespace: "@angular", name: "animation", version: "12.3.1" }
@@ -16,6 +16,12 @@ packagePurlOf("pkg:npm/a@1.0.0?arch=x#sub");
16
16
 
17
17
  osvPurl("Maven", "org.example:core");
18
18
  // "pkg:maven/org.example/core"
19
+
20
+ compareVersions("deb", "1.0~rc1", "1.0");
21
+ // -1
22
+
23
+ versContains(parseVers("vers:npm/>=1.0.0|<1.2.3")!, "1.1.0");
24
+ // true
19
25
  ```
20
26
 
21
27
  ## The functions
@@ -29,6 +35,13 @@ osvPurl("Maven", "org.example:core");
29
35
  | `osvPurl(ecosystem, name)` | The purl of a package of an OSV ecosystem, with no version. |
30
36
  | `osvPackagePurl(pkg)` | The purl of an OSV record package. A valid purl of the record wins. |
31
37
  | `OSV_PURL_TYPES` | The purl type of each OSV ecosystem that has one. |
38
+ | `compareVersions(scheme, a, b)` | Below 0, 0 or above 0 for the order of two versions, or `undefined` for a text that is not a version. |
39
+ | `compareSemver`, `compareGo`, `comparePep440`, `compareDebian`, `compareRpm` | The order of one scheme: SemVer 2.0.0, Go modules, PEP 440, dpkg and `rpmvercmp`. |
40
+ | `versionScheme(type)` | The version scheme of a purl type, or `undefined` when the order of the type is not known. |
41
+ | `parseVers(text)` | The scheme and the constraints of a `vers` range, or `undefined` for a text that is not a range. |
42
+ | `formatVers(vers)` | The `vers` text of a range, with the constraints in the order of their versions. |
43
+ | `versContains(vers, version)` | True when the version is in the range. The result is `undefined` when the order is not known. |
44
+ | `versEnd(vers, version)` | The end `<` of the part of the range that holds the version: for an advisory, the fixed version. |
32
45
 
33
46
  ## The canonical form
34
47
 
@@ -39,6 +52,10 @@ osvPurl("Maven", "org.example:core");
39
52
  - The subpath has no empty, `.` or `..` segment.
40
53
  - Each part is percent-encoded, but a colon stays as it is. A qualifier value keeps its `/`.
41
54
 
55
+ ## An unknown order
56
+
57
+ A comparison does not guess. A version that is not a version of its scheme gives `undefined`. A scheme with no known order also gives `undefined`, for example Maven. Thus a caller that matches advisories to installed versions does not take an unknown result as a match or as no match.
58
+
42
59
  ## License
43
60
 
44
61
  MIT
package/build/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Package identities: package URLs (purl) and the purl of each OSV ecosystem. The functions are plain functions with
2
+ * Package identities: package URLs (purl), the purl of each OSV ecosystem, the version order of each ecosystem and version ranges (vers). The functions are plain functions with
3
3
  * no fetch.
4
4
  */
5
5
  /**
@@ -44,6 +44,40 @@ export declare function formatPurl(purl: Purl): string | undefined;
44
44
  * names a package with this text names each version of it. It gives `undefined` when the text is not a valid purl.
45
45
  */
46
46
  export declare function packagePurlOf(text: string): string | undefined;
47
+ /** The comparators of a `vers` constraint. */
48
+ type VersComparator = "=" | "!=" | "<" | "<=" | ">" | ">=";
49
+ /** One constraint of a range: a comparator and a version. */
50
+ interface VersConstraint {
51
+ readonly comparator: VersComparator;
52
+ readonly version: string;
53
+ }
54
+ /** A version range. A range with the constraint `*` holds each version, and its list of constraints is empty. */
55
+ interface Vers {
56
+ /** The version scheme, for example `npm`, `pypi` or `deb`. */
57
+ readonly scheme: string;
58
+ /** True: the range is `*`, so it holds each version. */
59
+ readonly all: boolean;
60
+ readonly constraints: readonly VersConstraint[];
61
+ }
62
+ /** This function reads a `vers` text. A text that is not a range gives `undefined`. */
63
+ export declare function parseVers(text: string): Vers | undefined;
64
+ /**
65
+ * This function gives the `vers` text of a range. The constraints come in the order of the versions, when the scheme
66
+ * has a known order. The comparator `=` has no sign, as the specification tells.
67
+ */
68
+ export declare function formatVers(vers: Vers): string;
69
+ /**
70
+ * This function tells if a version is in a range, with the algorithm of the `vers` specification. The result is
71
+ * `undefined` when the scheme has no known order, or when a version is not a version of the scheme. Thus a caller
72
+ * does not take an unknown result as a match or as no match.
73
+ */
74
+ export declare function versContains(vers: Vers, version: string): boolean | undefined;
75
+ /**
76
+ * This function gives the end of the part of a range that holds a version, when that end is a constraint `<`. For the
77
+ * range of an advisory, it is the first fixed version above the version. The result is `undefined` for a version out
78
+ * of the range, or for an unknown order. It is also `undefined` for a part with no such end: `<=`, an open end or `=`.
79
+ */
80
+ export declare function versEnd(vers: Vers, version: string): string | undefined;
47
81
  /**
48
82
  * The purl type of each OSV ecosystem that has one. An ecosystem that is not in the table has no purl.
49
83
  * For a Linux distribution, the table key is the part of the ecosystem before the first `:`.
@@ -63,5 +97,52 @@ export declare function osvPackagePurl(pkg: {
63
97
  readonly name: string;
64
98
  readonly purl?: string;
65
99
  }): string | undefined;
66
- export type { Purl };
100
+ /** One event of an OSV range, as the OSV schema writes it: each event has one of the four fields. */
101
+ interface OsvEvent {
102
+ readonly introduced?: string;
103
+ readonly fixed?: string;
104
+ readonly last_affected?: string;
105
+ readonly limit?: string;
106
+ }
107
+ /** A range of an OSV record: its type (`SEMVER`, `ECOSYSTEM` or `GIT`) and its events. */
108
+ interface OsvRange {
109
+ readonly type: string;
110
+ readonly events: readonly OsvEvent[];
111
+ }
112
+ /**
113
+ * This function gives the `vers` range of an OSV range. A range of the type `SEMVER` has the scheme `semver`. A range
114
+ * of the type `ECOSYSTEM` has the purl type of its ecosystem as its scheme. A `GIT` range, an ecosystem with no purl type
115
+ * or an event with no version gives `undefined`.
116
+ *
117
+ * The events come in the order of their versions, as the OSV schema tells, when the scheme has a known order. Else they
118
+ * keep the order of the record. The event `introduced 0` is the start of each version, so it gives no constraint.
119
+ */
120
+ export declare function osvRangeVers(ecosystem: string, range: OsvRange): Vers | undefined;
121
+ /**
122
+ * The version order of each ecosystem: SemVer, Go modules, PEP 440, Debian and RPM. Each function compares two
123
+ * versions of one scheme. A text that is not a version of the scheme gives `undefined`, not a guess.
124
+ */
125
+ /** The version schemes that this module compares. */
126
+ type VersionScheme = "semver" | "golang" | "pypi" | "deb" | "rpm";
127
+ /** This function gives the version scheme of a purl type, or `undefined` for a type whose order this module does not know. */
128
+ export declare function versionScheme(type: string): VersionScheme | undefined;
129
+ /**
130
+ * This function compares two versions of one scheme. The result is below 0 when `a` comes before `b`, 0 when they are
131
+ * equal and above 0 when `a` comes after `b`. When a text is not a version of the scheme, the result is `undefined`.
132
+ */
133
+ export declare function compareVersions(scheme: string, a: string, b: string): number | undefined;
134
+ /** This function compares two SemVer 2.0.0 versions. It accepts a leading `v` or `=`, as npm does. */
135
+ export declare function compareSemver(a: string, b: string): number | undefined;
136
+ /**
137
+ * This function compares two versions of Go modules. A Go version starts with `v` and follows SemVer. A pseudo-version is
138
+ * a pre-release, so it has its place in the order of SemVer. The suffix `+incompatible` is build metadata.
139
+ */
140
+ export declare function compareGo(a: string, b: string): number | undefined;
141
+ /** This function compares two PEP 440 versions, with the order of the Python packaging specification. */
142
+ export declare function comparePep440(a: string, b: string): number | undefined;
143
+ /** This function compares two Debian versions (`[epoch:]upstream[-revision]`) with the order of dpkg. */
144
+ export declare function compareDebian(a: string, b: string): number | undefined;
145
+ /** This function compares two RPM versions (`[epoch:]version[-release]`) with the order of `rpmvercmp`. */
146
+ export declare function compareRpm(a: string, b: string): number | undefined;
147
+ export type { OsvEvent, OsvRange, Purl, Vers, VersComparator, VersConstraint, VersionScheme };
67
148
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/purl.ts","../src/osv.ts"],"mappings":";;;;;;;;;;;UAQiB;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA,aAAa,SAAS;;WAEtB;;;;;;;wBAmDK,cAAc,MAAM,OAAO;;;;;wBAmC3B,UAAU,eAAe;;;;;wBA2DzB,WAAW,MAAM;;;;;wBAkBjB,cAAc;;;;;qBC5KjB,gBAAgB,SAAS;;;;;wBAgDtB,QAAQ,mBAAmB;;;;;wBAe3B,eAAe;WAAgB;WAA4B;WAAuB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/purl.ts","../src/vers.ts","../src/osv.ts","../src/version.ts"],"mappings":";;;;;;;;;;;UAQiB;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA,aAAa,SAAS;;WAEtB;;;;;;;wBAmDK,cAAc,MAAM,OAAO;;;;;wBAmC3B,UAAU,eAAe;;;;;wBA2DzB,WAAW,MAAM;;;;;wBAkBjB,cAAc;;KChLlB;;UAGK;WACN,YAAY;WACZ;;;UAIM;;WAEN;;WAEA;WACA,sBAAsB;;;wBAsBjB,UAAU,eAAe;;;;;wBAsBzB,WAAW,MAAM;;;;;;wBAuBjB,aAAa,MAAM,MAAM;;;;;;wBAqCzB,QAAQ,MAAM,MAAM;;;;;qBChHvB,gBAAgB,SAAS;;;;;wBAgDtB,QAAQ,mBAAmB;;;;;wBAe3B,eAAe;WAAgB;WAA4B;WAAuB;;;UAMjF;WACN;WACA;WACA;WACA;;;UAIM;WACN;WACA,iBAAiB;;;;;;;;;;wBAWZ,aAAa,mBAAmB,OAAO,WAAW;;;;;;KCjGtD;;wBAcI,cAAc,eAAe;;;;;wBAQ7B,gBAAgB,gBAAgB,WAAW;;wBA6D3C,cAAc,WAAW;;;;;wBAUzB,UAAU,WAAW;;wBA+CrB,cAAc,WAAW;;wBAqEzB,cAAc,WAAW;;wBAyDzB,WAAW,WAAW"}
package/build/index.js CHANGED
@@ -161,6 +161,241 @@ function packagePurlOf(text) {
161
161
  name: purl.name
162
162
  });
163
163
  }
164
+ // src/version.ts
165
+ /** The version scheme of each purl type whose order this module knows. */
166
+ const TYPE_SCHEMES = /* @__PURE__ */ new Map([
167
+ ["npm", "semver"],
168
+ ["cargo", "semver"],
169
+ ["semver", "semver"],
170
+ ["golang", "golang"],
171
+ ["pypi", "pypi"],
172
+ ["deb", "deb"],
173
+ ["rpm", "rpm"]
174
+ ]);
175
+ /** This function gives the version scheme of a purl type, or `undefined` for a type whose order this module does not know. */
176
+ function versionScheme(type) {
177
+ return TYPE_SCHEMES.get(type.toLowerCase());
178
+ }
179
+ /**
180
+ * This function compares two versions of one scheme. The result is below 0 when `a` comes before `b`, 0 when they are
181
+ * equal and above 0 when `a` comes after `b`. When a text is not a version of the scheme, the result is `undefined`.
182
+ */
183
+ function compareVersions(scheme, a, b) {
184
+ switch (scheme) {
185
+ case "semver":
186
+ case "npm":
187
+ case "cargo": return compareSemver(a, b);
188
+ case "golang": return compareGo(a, b);
189
+ case "pypi": return comparePep440(a, b);
190
+ case "deb": return compareDebian(a, b);
191
+ case "rpm": return compareRpm(a, b);
192
+ default: return;
193
+ }
194
+ }
195
+ const sign = (n) => n < 0 ? -1 : n > 0 ? 1 : 0;
196
+ const compareText = (a, b) => a < b ? -1 : a > b ? 1 : 0;
197
+ const compareDigits = (a, b) => {
198
+ const x = a.replace(/^0+(?=\d)/, "");
199
+ const y = b.replace(/^0+(?=\d)/, "");
200
+ return x.length !== y.length ? sign(x.length - y.length) : compareText(x, y);
201
+ };
202
+ 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-]+)*)?$/;
203
+ function parseSemver(text) {
204
+ const match = SEMVER.exec(text.trim().replace(/^=/, ""));
205
+ if (match === null) return void 0;
206
+ return {
207
+ core: [
208
+ match[1],
209
+ match[2],
210
+ match[3]
211
+ ],
212
+ pre: match[4] === void 0 ? [] : match[4].split(".")
213
+ };
214
+ }
215
+ function compareSemverParts(x, y) {
216
+ for (let i = 0; i < 3; i++) {
217
+ const c = compareDigits(x.core[i], y.core[i]);
218
+ if (c !== 0) return c;
219
+ }
220
+ if (x.pre.length === 0 || y.pre.length === 0) return sign(y.pre.length - x.pre.length);
221
+ for (let i = 0; i < Math.min(x.pre.length, y.pre.length); i++) {
222
+ const p = x.pre[i];
223
+ const q = y.pre[i];
224
+ const pn = /^\d+$/.test(p);
225
+ const qn = /^\d+$/.test(q);
226
+ const c = pn && qn ? compareDigits(p, q) : pn ? -1 : qn ? 1 : compareText(p, q);
227
+ if (c !== 0) return c;
228
+ }
229
+ return sign(x.pre.length - y.pre.length);
230
+ }
231
+ /** This function compares two SemVer 2.0.0 versions. It accepts a leading `v` or `=`, as npm does. */
232
+ function compareSemver(a, b) {
233
+ const x = parseSemver(a);
234
+ const y = parseSemver(b);
235
+ return x === void 0 || y === void 0 ? void 0 : compareSemverParts(x, y);
236
+ }
237
+ /**
238
+ * This function compares two versions of Go modules. A Go version starts with `v` and follows SemVer. A pseudo-version is
239
+ * a pre-release, so it has its place in the order of SemVer. The suffix `+incompatible` is build metadata.
240
+ */
241
+ function compareGo(a, b) {
242
+ if (!a.startsWith("v") || !b.startsWith("v")) return void 0;
243
+ return compareSemver(a, b);
244
+ }
245
+ const PEP440 = /^\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;
246
+ const PRE_RANK = {
247
+ a: 0,
248
+ alpha: 0,
249
+ b: 1,
250
+ beta: 1,
251
+ c: 2,
252
+ rc: 2,
253
+ pre: 2,
254
+ preview: 2
255
+ };
256
+ function parsePep440(text) {
257
+ const m = PEP440.exec(text);
258
+ if (m === null) return void 0;
259
+ const release = m[2].split(".").map(Number);
260
+ while (release.length > 1 && release[release.length - 1] === 0) release.pop();
261
+ const post = m[5] !== void 0 ? Number(m[5]) : m[6] !== void 0 ? Number(m[7] ?? 0) : void 0;
262
+ return {
263
+ epoch: Number(m[1] ?? 0),
264
+ release,
265
+ ...m[3] === void 0 ? {} : { pre: [PRE_RANK[m[3].toLowerCase()], Number(m[4] ?? 0)] },
266
+ ...post === void 0 ? {} : { post },
267
+ ...m[8] === void 0 ? {} : { dev: Number(m[9] ?? 0) },
268
+ local: m[10] === void 0 ? [] : m[10].toLowerCase().split(/[-_.]/)
269
+ };
270
+ }
271
+ function compareNumbers(a, b) {
272
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
273
+ const c = sign((a[i] ?? 0) - (b[i] ?? 0));
274
+ if (c !== 0) return c;
275
+ }
276
+ return 0;
277
+ }
278
+ /** This function compares two PEP 440 versions, with the order of the Python packaging specification. */
279
+ function comparePep440(a, b) {
280
+ const x = parsePep440(a);
281
+ const y = parsePep440(b);
282
+ if (x === void 0 || y === void 0) return void 0;
283
+ const epoch = sign(x.epoch - y.epoch);
284
+ if (epoch !== 0) return epoch;
285
+ const release = compareNumbers(x.release, y.release);
286
+ if (release !== 0) return release;
287
+ const preKey = (v) => v.pre !== void 0 ? [0, ...v.pre] : v.post === void 0 && v.dev !== void 0 ? [-1] : [1];
288
+ const pre = compareNumbers(preKey(x), preKey(y));
289
+ if (pre !== 0) return pre;
290
+ const postKey = (v) => v.post === void 0 ? [-1] : [0, v.post];
291
+ const post = compareNumbers(postKey(x), postKey(y));
292
+ if (post !== 0) return post;
293
+ const devKey = (v) => v.dev === void 0 ? [1] : [0, v.dev];
294
+ const dev = compareNumbers(devKey(x), devKey(y));
295
+ if (dev !== 0) return dev;
296
+ return compareLocal(x.local, y.local);
297
+ }
298
+ function compareLocal(a, b) {
299
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
300
+ const p = a[i];
301
+ const q = b[i];
302
+ const pn = /^\d+$/.test(p);
303
+ const qn = /^\d+$/.test(q);
304
+ const c = pn && qn ? compareDigits(p, q) : pn ? 1 : qn ? -1 : compareText(p, q);
305
+ if (c !== 0) return c;
306
+ }
307
+ return sign(a.length - b.length);
308
+ }
309
+ function debianRank(text, i) {
310
+ if (i >= text.length) return 0;
311
+ const c = text[i];
312
+ if (/d/.test(c)) return 0;
313
+ if (c === "~") return -1;
314
+ if (/[A-Za-z]/.test(c)) return c.charCodeAt(0);
315
+ return c.charCodeAt(0) + 256;
316
+ }
317
+ function compareDebianPart(a, b) {
318
+ let i = 0;
319
+ let j = 0;
320
+ while (i < a.length || j < b.length) {
321
+ while (i < a.length && !/\d/.test(a[i]) || j < b.length && !/\d/.test(b[j])) {
322
+ const c = debianRank(a, i) - debianRank(b, j);
323
+ if (c !== 0) return sign(c);
324
+ i++;
325
+ j++;
326
+ }
327
+ let p = "";
328
+ let q = "";
329
+ while (i < a.length && /\d/.test(a[i])) p += a[i++];
330
+ while (j < b.length && /\d/.test(b[j])) q += b[j++];
331
+ const c = compareDigits(p || "0", q || "0");
332
+ if (c !== 0) return c;
333
+ }
334
+ return 0;
335
+ }
336
+ const DEBIAN = /^(?:(\d+):)?([0-9][A-Za-z0-9.+~:-]*?)(?:-([A-Za-z0-9.+~]+))?$/;
337
+ /** This function compares two Debian versions (`[epoch:]upstream[-revision]`) with the order of dpkg. */
338
+ function compareDebian(a, b) {
339
+ const x = DEBIAN.exec(a.trim());
340
+ const y = DEBIAN.exec(b.trim());
341
+ if (x === null || y === null) return void 0;
342
+ const epoch = compareDigits(x[1] ?? "0", y[1] ?? "0");
343
+ if (epoch !== 0) return epoch;
344
+ const upstream = compareDebianPart(x[2], y[2]);
345
+ if (upstream !== 0) return upstream;
346
+ return compareDebianPart(x[3] ?? "0", y[3] ?? "0");
347
+ }
348
+ function rpmvercmp(a, b) {
349
+ if (a === b) return 0;
350
+ let i = 0;
351
+ let j = 0;
352
+ for (;;) {
353
+ while (i < a.length && !/[A-Za-z0-9~^]/.test(a[i])) i++;
354
+ while (j < b.length && !/[A-Za-z0-9~^]/.test(b[j])) j++;
355
+ const ca = a[i];
356
+ const cb = b[j];
357
+ if (ca === "~" || cb === "~") {
358
+ if (ca !== "~") return 1;
359
+ if (cb !== "~") return -1;
360
+ i++;
361
+ j++;
362
+ continue;
363
+ }
364
+ if (ca === "^" || cb === "^") {
365
+ if (ca === void 0) return -1;
366
+ if (cb === void 0) return 1;
367
+ if (ca !== "^") return 1;
368
+ if (cb !== "^") return -1;
369
+ i++;
370
+ j++;
371
+ continue;
372
+ }
373
+ if (ca === void 0 || cb === void 0) break;
374
+ const digits = /\d/.test(ca);
375
+ const same = digits ? /\d/ : /[A-Za-z]/;
376
+ let p = "";
377
+ let q = "";
378
+ while (i < a.length && same.test(a[i])) p += a[i++];
379
+ while (j < b.length && same.test(b[j])) q += b[j++];
380
+ if (q === "") return digits ? 1 : -1;
381
+ const c = digits ? compareDigits(p, q) : compareText(p, q);
382
+ if (c !== 0) return c;
383
+ }
384
+ if (i >= a.length && j >= b.length) return 0;
385
+ return i >= a.length ? -1 : 1;
386
+ }
387
+ const RPM = /^(?:(\d+):)?([^-]+)(?:-([^-]+))?$/;
388
+ /** This function compares two RPM versions (`[epoch:]version[-release]`) with the order of `rpmvercmp`. */
389
+ function compareRpm(a, b) {
390
+ const x = RPM.exec(a.trim());
391
+ const y = RPM.exec(b.trim());
392
+ if (x === null || y === null) return void 0;
393
+ const epoch = compareDigits(x[1] ?? "0", y[1] ?? "0");
394
+ if (epoch !== 0) return epoch;
395
+ const version = rpmvercmp(x[2], y[2]);
396
+ if (version !== 0) return version;
397
+ return rpmvercmp(x[3] ?? "", y[3] ?? "");
398
+ }
164
399
  // src/osv.ts
165
400
  /**
166
401
  * The map from the ecosystems of OSV (`https://ossf.github.io/osv-schema/`) to purl types, and the purl of a package
@@ -229,11 +464,11 @@ function split(type, name) {
229
464
  */
230
465
  function osvPurl(ecosystem, name) {
231
466
  const base = ecosystem.split(":")[0];
232
- const type = OSV_PURL_TYPES[base];
467
+ const type = Object.hasOwn(OSV_PURL_TYPES, base) ? OSV_PURL_TYPES[base] : void 0;
233
468
  if (type === void 0 || name === "") return void 0;
234
469
  const names = split(type, name);
235
470
  if (names === void 0) return void 0;
236
- const namespace = DISTRIBUTION[base] ?? names.namespace;
471
+ const namespace = (Object.hasOwn(DISTRIBUTION, base) ? DISTRIBUTION[base] : void 0) ?? names.namespace;
237
472
  return formatPurl({
238
473
  type,
239
474
  ...namespace === void 0 ? {} : { namespace },
@@ -247,6 +482,183 @@ function osvPurl(ecosystem, name) {
247
482
  function osvPackagePurl(pkg) {
248
483
  return (pkg.purl === void 0 ? void 0 : packagePurlOf(pkg.purl)) ?? osvPurl(pkg.ecosystem, pkg.name);
249
484
  }
250
- export { OSV_PURL_TYPES, formatPurl, normalizePurl, osvPackagePurl, osvPurl, packagePurlOf, parsePurl };
485
+ /**
486
+ * This function gives the `vers` range of an OSV range. A range of the type `SEMVER` has the scheme `semver`. A range
487
+ * of the type `ECOSYSTEM` has the purl type of its ecosystem as its scheme. A `GIT` range, an ecosystem with no purl type
488
+ * or an event with no version gives `undefined`.
489
+ *
490
+ * The events come in the order of their versions, as the OSV schema tells, when the scheme has a known order. Else they
491
+ * keep the order of the record. The event `introduced 0` is the start of each version, so it gives no constraint.
492
+ */
493
+ function osvRangeVers(ecosystem, range) {
494
+ const base = ecosystem.split(":")[0];
495
+ const type = Object.hasOwn(OSV_PURL_TYPES, base) ? OSV_PURL_TYPES[base] : void 0;
496
+ const scheme = range.type === "SEMVER" ? "semver" : range.type === "ECOSYSTEM" ? type : void 0;
497
+ if (scheme === void 0) return void 0;
498
+ const constraints = [];
499
+ let all = false;
500
+ for (const event of range.events) {
501
+ const constraint = eventConstraint(event);
502
+ if (constraint === void 0) return void 0;
503
+ if (constraint === "start") all = true;
504
+ else if (constraint !== "none") constraints.push(constraint);
505
+ }
506
+ if (constraints.length === 0) return all ? {
507
+ scheme,
508
+ all: true,
509
+ constraints: []
510
+ } : void 0;
511
+ return {
512
+ scheme,
513
+ all: false,
514
+ constraints: sortEvents(scheme, constraints)
515
+ };
516
+ }
517
+ function eventConstraint(event) {
518
+ if (event.introduced !== void 0) return event.introduced === "0" ? "start" : {
519
+ comparator: ">=",
520
+ version: event.introduced
521
+ };
522
+ if (event.fixed !== void 0) return {
523
+ comparator: "<",
524
+ version: event.fixed
525
+ };
526
+ if (event.last_affected !== void 0) return {
527
+ comparator: "<=",
528
+ version: event.last_affected
529
+ };
530
+ if (event.limit !== void 0) return event.limit === "*" ? "none" : {
531
+ comparator: "<",
532
+ version: event.limit
533
+ };
534
+ }
535
+ function sortEvents(scheme, constraints) {
536
+ if (versionScheme(scheme) === void 0) return [...constraints];
537
+ let unknown = false;
538
+ const sorted = [...constraints].sort((a, b) => {
539
+ const c = compareVersions(scheme, a.version, b.version);
540
+ if (c === void 0) unknown = true;
541
+ return c ?? 0;
542
+ });
543
+ return unknown ? [...constraints] : sorted;
544
+ }
545
+ // src/vers.ts
546
+ /**
547
+ * Version ranges in the `vers` format of the purl specification, for example `vers:npm/>=1.0.0|<1.2.3`. The functions
548
+ * parse a range, format it and tell if a version is in it, with the version order of the scheme.
549
+ */
550
+ const COMPARATORS = [
551
+ "!=",
552
+ "<=",
553
+ ">=",
554
+ "<",
555
+ ">",
556
+ "="
557
+ ];
558
+ /** This function reads one constraint, for example `>=1.0.0`. A constraint with no comparator has the comparator `=`. */
559
+ function parseConstraint(text) {
560
+ const trimmed = text.trim();
561
+ const comparator = COMPARATORS.find((c) => trimmed.startsWith(c)) ?? "=";
562
+ const raw = trimmed.slice(trimmed.startsWith(comparator) ? comparator.length : 0).trim();
563
+ if (raw === "") return void 0;
564
+ let version;
565
+ try {
566
+ version = decodeURIComponent(raw);
567
+ } catch {
568
+ return;
569
+ }
570
+ return {
571
+ comparator,
572
+ version
573
+ };
574
+ }
575
+ /** This function reads a `vers` text. A text that is not a range gives `undefined`. */
576
+ function parseVers(text) {
577
+ const match = /^vers:([A-Za-z0-9.+-]+)\/(.+)$/.exec(text.replace(/\s+/g, ""));
578
+ if (match === null) return void 0;
579
+ const scheme = match[1].toLowerCase();
580
+ const body = match[2];
581
+ if (body === "*") return {
582
+ scheme,
583
+ all: true,
584
+ constraints: []
585
+ };
586
+ const constraints = [];
587
+ for (const part of body.split("|")) {
588
+ const constraint = parseConstraint(part);
589
+ if (constraint === void 0) return void 0;
590
+ constraints.push(constraint);
591
+ }
592
+ return {
593
+ scheme,
594
+ all: false,
595
+ constraints
596
+ };
597
+ }
598
+ const encodeVersion = (version) => version.replace(/[^A-Za-z0-9.+~_:-]/g, (c) => encodeURIComponent(c));
599
+ /**
600
+ * This function gives the `vers` text of a range. The constraints come in the order of the versions, when the scheme
601
+ * has a known order. The comparator `=` has no sign, as the specification tells.
602
+ */
603
+ function formatVers(vers) {
604
+ if (vers.all) return `vers:${vers.scheme}/*`;
605
+ const body = (sortConstraints(vers.scheme, vers.constraints) ?? vers.constraints).map((c) => `${c.comparator === "=" ? "" : c.comparator}${encodeVersion(c.version)}`).join("|");
606
+ return `vers:${vers.scheme}/${body}`;
607
+ }
608
+ function sortConstraints(scheme, constraints) {
609
+ let unknown = false;
610
+ const sorted = [...constraints].sort((a, b) => {
611
+ const c = compareVersions(scheme, a.version, b.version);
612
+ if (c === void 0) unknown = true;
613
+ return c ?? 0;
614
+ });
615
+ return unknown ? void 0 : sorted;
616
+ }
617
+ /**
618
+ * This function tells if a version is in a range, with the algorithm of the `vers` specification. The result is
619
+ * `undefined` when the scheme has no known order, or when a version is not a version of the scheme. Thus a caller
620
+ * does not take an unknown result as a match or as no match.
621
+ */
622
+ function versContains(vers, version) {
623
+ if (vers.all) return true;
624
+ const compare = (a, b) => compareVersions(vers.scheme, a, b);
625
+ for (const constraint of vers.constraints) {
626
+ const c = compare(version, constraint.version);
627
+ if (c === void 0) return void 0;
628
+ if (c === 0 && [
629
+ "=",
630
+ "<=",
631
+ ">="
632
+ ].includes(constraint.comparator)) return true;
633
+ if (c === 0 && constraint.comparator === "!=") return false;
634
+ }
635
+ const ranged = sortConstraints(vers.scheme, vers.constraints.filter((c) => c.comparator !== "=" && c.comparator !== "!="));
636
+ if (ranged === void 0) return void 0;
637
+ if (ranged.length === 0) return vers.constraints.some((c) => c.comparator === "!=");
638
+ const below = (c) => c.comparator === "<" || c.comparator === "<=";
639
+ const above = (c) => c.comparator === ">" || c.comparator === ">=";
640
+ const first = ranged[0];
641
+ const last = ranged[ranged.length - 1];
642
+ if (below(first) && compare(version, first.version) < 0) return true;
643
+ if (above(last) && compare(version, last.version) > 0) return true;
644
+ for (let i = 0; i + 1 < ranged.length; i++) {
645
+ const low = ranged[i];
646
+ const high = ranged[i + 1];
647
+ if (above(low) && below(high) && compare(version, low.version) > 0 && compare(version, high.version) < 0) return true;
648
+ }
649
+ return false;
650
+ }
651
+ /**
652
+ * This function gives the end of the part of a range that holds a version, when that end is a constraint `<`. For the
653
+ * range of an advisory, it is the first fixed version above the version. The result is `undefined` for a version out
654
+ * of the range, or for an unknown order. It is also `undefined` for a part with no such end: `<=`, an open end or `=`.
655
+ */
656
+ function versEnd(vers, version) {
657
+ if (vers.all || versContains(vers, version) !== true) return void 0;
658
+ if (vers.constraints.some((c) => c.comparator === "=" && compareVersions(vers.scheme, version, c.version) === 0)) return void 0;
659
+ const next = sortConstraints(vers.scheme, vers.constraints.filter((c) => c.comparator !== "=" && c.comparator !== "!="))?.find((c) => compareVersions(vers.scheme, version, c.version) < 0);
660
+ return next?.comparator === "<" ? next.version : void 0;
661
+ }
662
+ export { OSV_PURL_TYPES, compareDebian, compareGo, comparePep440, compareRpm, compareSemver, compareVersions, formatPurl, formatVers, normalizePurl, osvPackagePurl, osvPurl, osvRangeVers, packagePurlOf, parsePurl, parseVers, versContains, versEnd, versionScheme };
251
663
 
252
664
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/purl.ts","../src/osv.ts"],"sourcesContent":["/**\n * Package URLs (purl): parse, format and normalize, as the purl specification tells\n * (`https://github.com/package-url/purl-spec`). The form is `pkg:type/namespace/name@version?qualifiers#subpath`.\n *\n * The functions are plain functions with no fetch and no state.\n */\n\n/** A package URL as its parts. Each text part is decoded: it has no percent-encoding. */\nexport interface Purl {\n /** The type of the package, in lower case, for example `npm` or `pypi`. */\n readonly type: string;\n /** The namespace, with `/` between its segments, or `undefined` when the purl has no namespace. */\n readonly namespace?: string;\n /** The name of the package. */\n readonly name: string;\n /** The version, or `undefined` when the purl has no version. */\n readonly version?: string;\n /** The qualifiers, with lower-case keys. A qualifier with an empty value is not in the record. */\n readonly qualifiers?: Readonly<Record<string, string>>;\n /** The subpath, with `/` between its segments, or `undefined` when the purl has no subpath. */\n readonly subpath?: string;\n}\n\n/** The pattern of a type: a letter first, then letters, digits, `.`, `+` or `-`. */\nconst TYPE = /^[a-z][a-z0-9.+-]*$/;\n\n/** The pattern of a qualifier key: a letter first, then letters, digits, `.`, `-` or `_`. */\nconst KEY = /^[a-z][a-z0-9._-]*$/;\n\n/**\n * The types whose namespace and name are not case sensitive. The canonical form of these parts is lower case.\n * The list comes from the type definitions of the purl specification.\n */\nconst LOWER_NAMESPACE_AND_NAME: ReadonlySet<string> = new Set([\"alpm\", \"apk\", \"bitbucket\", \"composer\", \"deb\", \"github\", \"golang\", \"npm\"]);\n\n/** The types whose name only is not case sensitive. The canonical form of the name is lower case. */\nconst LOWER_NAME: ReadonlySet<string> = new Set([\"hex\", \"pub\", \"pypi\"]);\n\n/** This function percent-encodes one part of a purl. A letter, a digit, `.-_~` and `:` stay as they are. */\nfunction encode(text: string): string {\n return encodeURIComponent(text)\n .replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`)\n .replace(/%3A/g, \":\");\n}\n\n/** This function decodes one part of a purl, or gives `undefined` for a bad percent-encoding. */\nfunction decode(text: string): string | undefined {\n try {\n return decodeURIComponent(text);\n } catch {\n return undefined;\n }\n}\n\n/** This function splits a path into its decoded segments. It discards each empty segment. */\nfunction segments(text: string): string[] | undefined {\n const parts: string[] = [];\n for (const raw of text.split(\"/\")) {\n if (raw === \"\") continue;\n const part = decode(raw);\n if (part === undefined) return undefined;\n parts.push(part);\n }\n return parts;\n}\n\n/**\n * This function gives the canonical parts of a purl. The type and the qualifier keys are in lower case. The parts\n * follow the case rules of the type, and no part is empty.\n * It gives `undefined` when a part breaks a rule of the specification.\n */\nexport function normalizePurl(purl: Purl): Purl | undefined {\n const type = purl.type.toLowerCase();\n if (!TYPE.test(type)) return undefined;\n const lowerAll = LOWER_NAMESPACE_AND_NAME.has(type);\n const lowerName = lowerAll || LOWER_NAME.has(type);\n let name = lowerName ? purl.name.toLowerCase() : purl.name;\n if (type === \"pypi\") name = name.replace(/_/g, \"-\");\n if (name === \"\") return undefined;\n const space = purl.namespace?.split(\"/\").filter((segment) => segment !== \"\").join(\"/\");\n const namespace = space === undefined || space === \"\" ? undefined : lowerAll ? space.toLowerCase() : space;\n if (type === \"maven\" && namespace === undefined) return undefined;\n const qualifiers: Record<string, string> = {};\n for (const [key, value] of Object.entries(purl.qualifiers ?? {})) {\n const lower = key.toLowerCase();\n if (!KEY.test(lower)) return undefined;\n if (value !== \"\") qualifiers[lower] = value;\n }\n const subpath = purl.subpath\n ?.split(\"/\")\n .filter((segment) => segment !== \"\" && segment !== \".\" && segment !== \"..\")\n .join(\"/\");\n return {\n type,\n ...(namespace === undefined ? {} : { namespace }),\n name,\n ...(purl.version === undefined || purl.version === \"\" ? {} : { version: purl.version }),\n ...(Object.keys(qualifiers).length === 0 ? {} : { qualifiers }),\n ...(subpath === undefined || subpath === \"\" ? {} : { subpath }),\n };\n}\n\n/**\n * This function reads a purl text into its parts, as the parse steps of the specification tell, and normalizes them.\n * It gives `undefined` when the text is not a valid purl.\n */\nexport function parsePurl(text: string): Purl | undefined {\n let rest = text.trim();\n let subpath: string | undefined;\n const hash = rest.indexOf(\"#\");\n if (hash >= 0) {\n const parts = segments(rest.slice(hash + 1));\n if (parts === undefined) return undefined;\n subpath = parts.filter((segment) => segment !== \".\" && segment !== \"..\").join(\"/\");\n rest = rest.slice(0, hash);\n }\n let qualifiers: Record<string, string> | undefined;\n const question = rest.indexOf(\"?\");\n if (question >= 0) {\n qualifiers = {};\n for (const pair of rest.slice(question + 1).split(\"&\")) {\n if (pair === \"\") continue;\n const equal = pair.indexOf(\"=\");\n if (equal <= 0) return undefined;\n const key = pair.slice(0, equal).toLowerCase();\n const value = decode(pair.slice(equal + 1));\n if (value === undefined || key in qualifiers) return undefined;\n qualifiers[key] = value;\n }\n rest = rest.slice(0, question);\n }\n const colon = rest.indexOf(\":\");\n if (colon < 0 || rest.slice(0, colon).toLowerCase() !== \"pkg\") return undefined;\n rest = rest.slice(colon + 1).replace(/^\\/+/, \"\");\n const slash = rest.indexOf(\"/\");\n if (slash <= 0) return undefined;\n const type = rest.slice(0, slash);\n rest = rest.slice(slash + 1);\n let version: string | undefined;\n const at = rest.lastIndexOf(\"@\");\n // An npm scope in a purl is `%40`, so a raw `@` starts the version. A raw `@` at the start of the\n // namespace is not a version.\n if (at > 0) {\n version = decode(rest.slice(at + 1));\n if (version === undefined) return undefined;\n rest = rest.slice(0, at);\n }\n const path = segments(rest);\n if (path === undefined || path.length === 0) return undefined;\n const name = path[path.length - 1]!;\n const namespace = path.length > 1 ? path.slice(0, -1).join(\"/\") : undefined;\n return normalizePurl({\n type,\n ...(namespace === undefined ? {} : { namespace }),\n name,\n ...(version === undefined ? {} : { version }),\n ...(qualifiers === undefined ? {} : { qualifiers }),\n ...(subpath === undefined ? {} : { subpath }),\n });\n}\n\n/**\n * This function writes the canonical text of a purl: the parts normalized, each part percent-encoded and the\n * qualifiers in the order of their keys. It gives `undefined` when a part breaks a rule of the specification.\n */\nexport function formatPurl(purl: Purl): string | undefined {\n const canonical = normalizePurl(purl);\n if (canonical === undefined) return undefined;\n let text = `pkg:${canonical.type}/`;\n if (canonical.namespace !== undefined) text += `${canonical.namespace.split(\"/\").map(encode).join(\"/\")}/`;\n text += encode(canonical.name);\n if (canonical.version !== undefined) text += `@${encode(canonical.version)}`;\n const keys = Object.keys(canonical.qualifiers ?? {}).sort();\n // A qualifier value keeps its `/`, as the test suite of the specification does with `repository_url`.\n if (keys.length > 0) text += `?${keys.map((key) => `${key}=${encode(canonical.qualifiers![key]!).replace(/%2F/g, \"/\")}`).join(\"&\")}`;\n if (canonical.subpath !== undefined) text += `#${canonical.subpath.split(\"/\").map(encode).join(\"/\")}`;\n return text;\n}\n\n/**\n * This function gives the canonical purl of the package with no version, no qualifiers and no subpath. A person who\n * names a package with this text names each version of it. It gives `undefined` when the text is not a valid purl.\n */\nexport function packagePurlOf(text: string): string | undefined {\n const purl = parsePurl(text);\n return purl === undefined ? undefined : formatPurl({ type: purl.type, ...(purl.namespace === undefined ? {} : { namespace: purl.namespace }), name: purl.name });\n}\n","/**\n * The map from the ecosystems of OSV (`https://ossf.github.io/osv-schema/`) to purl types, and the purl of a package\n * of an OSV record.\n */\n\nimport { formatPurl, packagePurlOf } from \"./purl.ts\";\n\n/**\n * The purl type of each OSV ecosystem that has one. An ecosystem that is not in the table has no purl.\n * For a Linux distribution, the table key is the part of the ecosystem before the first `:`.\n */\nexport const OSV_PURL_TYPES: Readonly<Record<string, string>> = {\n npm: \"npm\",\n PyPI: \"pypi\",\n \"crates.io\": \"cargo\",\n RubyGems: \"gem\",\n NuGet: \"nuget\",\n Go: \"golang\",\n Maven: \"maven\",\n Packagist: \"composer\",\n Pub: \"pub\",\n Hex: \"hex\",\n Hackage: \"hackage\",\n CRAN: \"cran\",\n \"GitHub Actions\": \"github\",\n Debian: \"deb\",\n Ubuntu: \"deb\",\n Alpine: \"apk\",\n};\n\n/** The purl namespace of each OSV ecosystem of a Linux distribution: the name of the distribution. */\nconst DISTRIBUTION: Readonly<Record<string, string>> = { Debian: \"debian\", Ubuntu: \"ubuntu\", Alpine: \"alpine\" };\n\n/** This function gives the namespace and the name of an OSV package name, as the purl type of its ecosystem splits them. */\nfunction split(type: string, name: string): { readonly namespace?: string; readonly name: string } | undefined {\n switch (type) {\n case \"npm\": {\n const slash = name.indexOf(\"/\");\n return name.startsWith(\"@\") && slash > 1 ? { namespace: name.slice(0, slash), name: name.slice(slash + 1) } : { name };\n }\n case \"golang\":\n case \"composer\":\n case \"github\": {\n const slash = name.lastIndexOf(\"/\");\n return slash > 0 ? { namespace: name.slice(0, slash), name: name.slice(slash + 1) } : { name };\n }\n case \"maven\": {\n const colon = name.indexOf(\":\");\n return colon > 0 ? { namespace: name.slice(0, colon), name: name.slice(colon + 1) } : undefined;\n }\n default:\n return { name };\n }\n}\n\n/**\n * This function gives the canonical purl of an OSV package, with no version. For an ecosystem with no purl type, or\n * a bad name, it gives `undefined`.\n */\nexport function osvPurl(ecosystem: string, name: string): string | undefined {\n const base = ecosystem.split(\":\")[0]!;\n const type = OSV_PURL_TYPES[base];\n if (type === undefined || name === \"\") return undefined;\n const names = split(type, name);\n if (names === undefined) return undefined;\n const distribution = DISTRIBUTION[base];\n const namespace = distribution ?? names.namespace;\n return formatPurl({ type, ...(namespace === undefined ? {} : { namespace }), name: names.name });\n}\n\n/**\n * This function gives the purl of a package of an OSV record, with no version, qualifiers or subpath. A valid purl\n * of the record wins. Else the function builds the purl from the ecosystem and the name.\n */\nexport function osvPackagePurl(pkg: { readonly ecosystem: string; readonly name: string; readonly purl?: string }): string | undefined {\n const own = pkg.purl === undefined ? undefined : packagePurlOf(pkg.purl);\n return own ?? osvPurl(pkg.ecosystem, pkg.name);\n}\n"],"mappings":";;AAwBA,MAAM,OAAO;;AAGb,MAAM,MAAM;;;;;AAMZ,MAAM,2CAAgD,IAAI,IAAI;CAAC;CAAQ;CAAO;CAAa;CAAY;CAAO;CAAU;CAAU;AAAK,CAAC;;AAGxI,MAAM,6BAAkC,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AI,SAAS,KAAA,IAAY,KAAA,IAAY,cAAc,IAAI,IAAI,MACzD,QAAQ,IAAI,WAAW,IAAI,IAAI;AAC/C"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/purl.ts","../src/version.ts","../src/osv.ts","../src/vers.ts"],"sourcesContent":["/**\n * Package URLs (purl): parse, format and normalize, as the purl specification tells\n * (`https://github.com/package-url/purl-spec`). The form is `pkg:type/namespace/name@version?qualifiers#subpath`.\n *\n * The functions are plain functions with no fetch and no state.\n */\n\n/** A package URL as its parts. Each text part is decoded: it has no percent-encoding. */\nexport interface Purl {\n /** The type of the package, in lower case, for example `npm` or `pypi`. */\n readonly type: string;\n /** The namespace, with `/` between its segments, or `undefined` when the purl has no namespace. */\n readonly namespace?: string;\n /** The name of the package. */\n readonly name: string;\n /** The version, or `undefined` when the purl has no version. */\n readonly version?: string;\n /** The qualifiers, with lower-case keys. A qualifier with an empty value is not in the record. */\n readonly qualifiers?: Readonly<Record<string, string>>;\n /** The subpath, with `/` between its segments, or `undefined` when the purl has no subpath. */\n readonly subpath?: string;\n}\n\n/** The pattern of a type: a letter first, then letters, digits, `.`, `+` or `-`. */\nconst TYPE = /^[a-z][a-z0-9.+-]*$/;\n\n/** The pattern of a qualifier key: a letter first, then letters, digits, `.`, `-` or `_`. */\nconst KEY = /^[a-z][a-z0-9._-]*$/;\n\n/**\n * The types whose namespace and name are not case sensitive. The canonical form of these parts is lower case.\n * The list comes from the type definitions of the purl specification.\n */\nconst LOWER_NAMESPACE_AND_NAME: ReadonlySet<string> = new Set([\"alpm\", \"apk\", \"bitbucket\", \"composer\", \"deb\", \"github\", \"golang\", \"npm\"]);\n\n/** The types whose name only is not case sensitive. The canonical form of the name is lower case. */\nconst LOWER_NAME: ReadonlySet<string> = new Set([\"hex\", \"pub\", \"pypi\"]);\n\n/** This function percent-encodes one part of a purl. A letter, a digit, `.-_~` and `:` stay as they are. */\nfunction encode(text: string): string {\n return encodeURIComponent(text)\n .replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`)\n .replace(/%3A/g, \":\");\n}\n\n/** This function decodes one part of a purl, or gives `undefined` for a bad percent-encoding. */\nfunction decode(text: string): string | undefined {\n try {\n return decodeURIComponent(text);\n } catch {\n return undefined;\n }\n}\n\n/** This function splits a path into its decoded segments. It discards each empty segment. */\nfunction segments(text: string): string[] | undefined {\n const parts: string[] = [];\n for (const raw of text.split(\"/\")) {\n if (raw === \"\") continue;\n const part = decode(raw);\n if (part === undefined) return undefined;\n parts.push(part);\n }\n return parts;\n}\n\n/**\n * This function gives the canonical parts of a purl. The type and the qualifier keys are in lower case. The parts\n * follow the case rules of the type, and no part is empty.\n * It gives `undefined` when a part breaks a rule of the specification.\n */\nexport function normalizePurl(purl: Purl): Purl | undefined {\n const type = purl.type.toLowerCase();\n if (!TYPE.test(type)) return undefined;\n const lowerAll = LOWER_NAMESPACE_AND_NAME.has(type);\n const lowerName = lowerAll || LOWER_NAME.has(type);\n let name = lowerName ? purl.name.toLowerCase() : purl.name;\n if (type === \"pypi\") name = name.replace(/_/g, \"-\");\n if (name === \"\") return undefined;\n const space = purl.namespace?.split(\"/\").filter((segment) => segment !== \"\").join(\"/\");\n const namespace = space === undefined || space === \"\" ? undefined : lowerAll ? space.toLowerCase() : space;\n if (type === \"maven\" && namespace === undefined) return undefined;\n const qualifiers: Record<string, string> = {};\n for (const [key, value] of Object.entries(purl.qualifiers ?? {})) {\n const lower = key.toLowerCase();\n if (!KEY.test(lower)) return undefined;\n if (value !== \"\") qualifiers[lower] = value;\n }\n const subpath = purl.subpath\n ?.split(\"/\")\n .filter((segment) => segment !== \"\" && segment !== \".\" && segment !== \"..\")\n .join(\"/\");\n return {\n type,\n ...(namespace === undefined ? {} : { namespace }),\n name,\n ...(purl.version === undefined || purl.version === \"\" ? {} : { version: purl.version }),\n ...(Object.keys(qualifiers).length === 0 ? {} : { qualifiers }),\n ...(subpath === undefined || subpath === \"\" ? {} : { subpath }),\n };\n}\n\n/**\n * This function reads a purl text into its parts, as the parse steps of the specification tell, and normalizes them.\n * It gives `undefined` when the text is not a valid purl.\n */\nexport function parsePurl(text: string): Purl | undefined {\n let rest = text.trim();\n let subpath: string | undefined;\n const hash = rest.indexOf(\"#\");\n if (hash >= 0) {\n const parts = segments(rest.slice(hash + 1));\n if (parts === undefined) return undefined;\n subpath = parts.filter((segment) => segment !== \".\" && segment !== \"..\").join(\"/\");\n rest = rest.slice(0, hash);\n }\n let qualifiers: Record<string, string> | undefined;\n const question = rest.indexOf(\"?\");\n if (question >= 0) {\n qualifiers = {};\n for (const pair of rest.slice(question + 1).split(\"&\")) {\n if (pair === \"\") continue;\n const equal = pair.indexOf(\"=\");\n if (equal <= 0) return undefined;\n const key = pair.slice(0, equal).toLowerCase();\n const value = decode(pair.slice(equal + 1));\n if (value === undefined || key in qualifiers) return undefined;\n qualifiers[key] = value;\n }\n rest = rest.slice(0, question);\n }\n const colon = rest.indexOf(\":\");\n if (colon < 0 || rest.slice(0, colon).toLowerCase() !== \"pkg\") return undefined;\n rest = rest.slice(colon + 1).replace(/^\\/+/, \"\");\n const slash = rest.indexOf(\"/\");\n if (slash <= 0) return undefined;\n const type = rest.slice(0, slash);\n rest = rest.slice(slash + 1);\n let version: string | undefined;\n const at = rest.lastIndexOf(\"@\");\n // An npm scope in a purl is `%40`, so a raw `@` starts the version. A raw `@` at the start of the\n // namespace is not a version.\n if (at > 0) {\n version = decode(rest.slice(at + 1));\n if (version === undefined) return undefined;\n rest = rest.slice(0, at);\n }\n const path = segments(rest);\n if (path === undefined || path.length === 0) return undefined;\n const name = path[path.length - 1]!;\n const namespace = path.length > 1 ? path.slice(0, -1).join(\"/\") : undefined;\n return normalizePurl({\n type,\n ...(namespace === undefined ? {} : { namespace }),\n name,\n ...(version === undefined ? {} : { version }),\n ...(qualifiers === undefined ? {} : { qualifiers }),\n ...(subpath === undefined ? {} : { subpath }),\n });\n}\n\n/**\n * This function writes the canonical text of a purl: the parts normalized, each part percent-encoded and the\n * qualifiers in the order of their keys. It gives `undefined` when a part breaks a rule of the specification.\n */\nexport function formatPurl(purl: Purl): string | undefined {\n const canonical = normalizePurl(purl);\n if (canonical === undefined) return undefined;\n let text = `pkg:${canonical.type}/`;\n if (canonical.namespace !== undefined) text += `${canonical.namespace.split(\"/\").map(encode).join(\"/\")}/`;\n text += encode(canonical.name);\n if (canonical.version !== undefined) text += `@${encode(canonical.version)}`;\n const keys = Object.keys(canonical.qualifiers ?? {}).sort();\n // A qualifier value keeps its `/`, as the test suite of the specification does with `repository_url`.\n if (keys.length > 0) text += `?${keys.map((key) => `${key}=${encode(canonical.qualifiers![key]!).replace(/%2F/g, \"/\")}`).join(\"&\")}`;\n if (canonical.subpath !== undefined) text += `#${canonical.subpath.split(\"/\").map(encode).join(\"/\")}`;\n return text;\n}\n\n/**\n * This function gives the canonical purl of the package with no version, no qualifiers and no subpath. A person who\n * names a package with this text names each version of it. It gives `undefined` when the text is not a valid purl.\n */\nexport function packagePurlOf(text: string): string | undefined {\n const purl = parsePurl(text);\n return purl === undefined ? undefined : formatPurl({ type: purl.type, ...(purl.namespace === undefined ? {} : { namespace: purl.namespace }), name: purl.name });\n}\n","/**\n * The version order of each ecosystem: SemVer, Go modules, PEP 440, Debian and RPM. Each function compares two\n * versions of one scheme. A text that is not a version of the scheme gives `undefined`, not a guess.\n */\n\n/** The version schemes that this module compares. */\nexport type VersionScheme = \"semver\" | \"golang\" | \"pypi\" | \"deb\" | \"rpm\";\n\n/** The version scheme of each purl type whose order this module knows. */\nconst TYPE_SCHEMES: ReadonlyMap<string, VersionScheme> = new Map([\n [\"npm\", \"semver\"],\n [\"cargo\", \"semver\"],\n [\"semver\", \"semver\"],\n [\"golang\", \"golang\"],\n [\"pypi\", \"pypi\"],\n [\"deb\", \"deb\"],\n [\"rpm\", \"rpm\"],\n]);\n\n/** This function gives the version scheme of a purl type, or `undefined` for a type whose order this module does not know. */\nexport function versionScheme(type: string): VersionScheme | undefined {\n return TYPE_SCHEMES.get(type.toLowerCase());\n}\n\n/**\n * This function compares two versions of one scheme. The result is below 0 when `a` comes before `b`, 0 when they are\n * equal and above 0 when `a` comes after `b`. When a text is not a version of the scheme, the result is `undefined`.\n */\nexport function compareVersions(scheme: string, a: string, b: string): number | undefined {\n switch (scheme) {\n case \"semver\":\n case \"npm\":\n case \"cargo\":\n return compareSemver(a, b);\n case \"golang\":\n return compareGo(a, b);\n case \"pypi\":\n return comparePep440(a, b);\n case \"deb\":\n return compareDebian(a, b);\n case \"rpm\":\n return compareRpm(a, b);\n default:\n return undefined;\n }\n}\n\nconst sign = (n: number): number => (n < 0 ? -1 : n > 0 ? 1 : 0);\nconst compareText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\nconst compareDigits = (a: string, b: string): number => {\n const x = a.replace(/^0+(?=\\d)/, \"\");\n const y = b.replace(/^0+(?=\\d)/, \"\");\n return x.length !== y.length ? sign(x.length - y.length) : compareText(x, y);\n};\n\n// SemVer 2.0.0. The build metadata does not change the order.\nconst 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-]+)*)?$/;\n\n/** The parts of a SemVer version that decide its order. */\ninterface Semver {\n readonly core: readonly [string, string, string];\n readonly pre: readonly string[];\n}\n\nfunction parseSemver(text: string): Semver | undefined {\n const match = SEMVER.exec(text.trim().replace(/^=/, \"\"));\n if (match === null) return undefined;\n return { core: [match[1]!, match[2]!, match[3]!], pre: match[4] === undefined ? [] : match[4].split(\".\") };\n}\n\nfunction compareSemverParts(x: Semver, y: Semver): number {\n for (let i = 0; i < 3; i++) {\n const c = compareDigits(x.core[i]!, y.core[i]!);\n if (c !== 0) return c;\n }\n // A version with a pre-release comes before the same version with no pre-release.\n if (x.pre.length === 0 || y.pre.length === 0) return sign(y.pre.length - x.pre.length);\n for (let i = 0; i < Math.min(x.pre.length, y.pre.length); i++) {\n const p = x.pre[i]!;\n const q = y.pre[i]!;\n const pn = /^\\d+$/.test(p);\n const qn = /^\\d+$/.test(q);\n const c = pn && qn ? compareDigits(p, q) : pn ? -1 : qn ? 1 : compareText(p, q);\n if (c !== 0) return c;\n }\n return sign(x.pre.length - y.pre.length);\n}\n\n/** This function compares two SemVer 2.0.0 versions. It accepts a leading `v` or `=`, as npm does. */\nexport function compareSemver(a: string, b: string): number | undefined {\n const x = parseSemver(a);\n const y = parseSemver(b);\n return x === undefined || y === undefined ? undefined : compareSemverParts(x, y);\n}\n\n/**\n * This function compares two versions of Go modules. A Go version starts with `v` and follows SemVer. A pseudo-version is\n * a pre-release, so it has its place in the order of SemVer. The suffix `+incompatible` is build metadata.\n */\nexport function compareGo(a: string, b: string): number | undefined {\n if (!a.startsWith(\"v\") || !b.startsWith(\"v\")) return undefined;\n return compareSemver(a, b);\n}\n\n// PEP 440: the pattern of the version specification of the Python packaging guide.\nconst PEP440 =\n /^\\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;\n\n/** The parts of a PEP 440 version that decide its order. */\ninterface Pep440 {\n readonly epoch: number;\n readonly release: readonly number[];\n /** The pre-release as a rank (a 0, b 1, rc 2) and a number. */\n readonly pre?: readonly [number, number];\n readonly post?: number;\n readonly dev?: number;\n readonly local: readonly string[];\n}\n\nconst PRE_RANK: Readonly<Record<string, number>> = { a: 0, alpha: 0, b: 1, beta: 1, c: 2, rc: 2, pre: 2, preview: 2 };\n\nfunction parsePep440(text: string): Pep440 | undefined {\n const m = PEP440.exec(text);\n if (m === null) return undefined;\n const release = m[2]!.split(\".\").map(Number);\n while (release.length > 1 && release[release.length - 1] === 0) release.pop();\n const post = m[5] !== undefined ? Number(m[5]) : m[6] !== undefined ? Number(m[7] ?? 0) : undefined;\n return {\n epoch: Number(m[1] ?? 0),\n release,\n ...(m[3] === undefined ? {} : { pre: [PRE_RANK[m[3].toLowerCase()]!, Number(m[4] ?? 0)] as const }),\n ...(post === undefined ? {} : { post }),\n ...(m[8] === undefined ? {} : { dev: Number(m[9] ?? 0) }),\n local: m[10] === undefined ? [] : m[10].toLowerCase().split(/[-_.]/),\n };\n}\n\nfunction compareNumbers(a: readonly number[], b: readonly number[]): number {\n for (let i = 0; i < Math.max(a.length, b.length); i++) {\n const c = sign((a[i] ?? 0) - (b[i] ?? 0));\n if (c !== 0) return c;\n }\n return 0;\n}\n\n/** This function compares two PEP 440 versions, with the order of the Python packaging specification. */\nexport function comparePep440(a: string, b: string): number | undefined {\n const x = parsePep440(a);\n const y = parsePep440(b);\n if (x === undefined || y === undefined) return undefined;\n const epoch = sign(x.epoch - y.epoch);\n if (epoch !== 0) return epoch;\n const release = compareNumbers(x.release, y.release);\n if (release !== 0) return release;\n // A dev release with no pre-release and no post-release comes before each pre-release.\n const preKey = (v: Pep440): readonly number[] => (v.pre !== undefined ? [0, ...v.pre] : v.post === undefined && v.dev !== undefined ? [-1] : [1]);\n const pre = compareNumbers(preKey(x), preKey(y));\n if (pre !== 0) return pre;\n const postKey = (v: Pep440): readonly number[] => (v.post === undefined ? [-1] : [0, v.post]);\n const post = compareNumbers(postKey(x), postKey(y));\n if (post !== 0) return post;\n const devKey = (v: Pep440): readonly number[] => (v.dev === undefined ? [1] : [0, v.dev]);\n const dev = compareNumbers(devKey(x), devKey(y));\n if (dev !== 0) return dev;\n return compareLocal(x.local, y.local);\n}\n\n// A local version comes after the same version with no local part. A number segment comes after a text segment.\nfunction compareLocal(a: readonly string[], b: readonly string[]): number {\n for (let i = 0; i < Math.min(a.length, b.length); i++) {\n const p = a[i]!;\n const q = b[i]!;\n const pn = /^\\d+$/.test(p);\n const qn = /^\\d+$/.test(q);\n const c = pn && qn ? compareDigits(p, q) : pn ? 1 : qn ? -1 : compareText(p, q);\n if (c !== 0) return c;\n }\n return sign(a.length - b.length);\n}\n\n// The order of a character of a Debian version: `~` comes before the end, the end before a letter, a letter before\n// each other character. A digit has the rank of the end, as in dpkg.\nfunction debianRank(text: string, i: number): number {\n if (i >= text.length) return 0;\n const c = text[i]!;\n if (/d/.test(c)) return 0;\n if (c === \"~\") return -1;\n if (/[A-Za-z]/.test(c)) return c.charCodeAt(0);\n return c.charCodeAt(0) + 256;\n}\n\n// The comparison of dpkg: parts with no digit and parts of digits, one after the other.\nfunction compareDebianPart(a: string, b: string): number {\n let i = 0;\n let j = 0;\n while (i < a.length || j < b.length) {\n while ((i < a.length && !/\\d/.test(a[i]!)) || (j < b.length && !/\\d/.test(b[j]!))) {\n const c = debianRank(a, i) - debianRank(b, j);\n if (c !== 0) return sign(c);\n i++;\n j++;\n }\n let p = \"\";\n let q = \"\";\n while (i < a.length && /\\d/.test(a[i]!)) p += a[i++];\n while (j < b.length && /\\d/.test(b[j]!)) q += b[j++];\n const c = compareDigits(p || \"0\", q || \"0\");\n if (c !== 0) return c;\n }\n return 0;\n}\n\nconst DEBIAN = /^(?:(\\d+):)?([0-9][A-Za-z0-9.+~:-]*?)(?:-([A-Za-z0-9.+~]+))?$/;\n\n/** This function compares two Debian versions (`[epoch:]upstream[-revision]`) with the order of dpkg. */\nexport function compareDebian(a: string, b: string): number | undefined {\n const x = DEBIAN.exec(a.trim());\n const y = DEBIAN.exec(b.trim());\n if (x === null || y === null) return undefined;\n const epoch = compareDigits(x[1] ?? \"0\", y[1] ?? \"0\");\n if (epoch !== 0) return epoch;\n const upstream = compareDebianPart(x[2]!, y[2]!);\n if (upstream !== 0) return upstream;\n return compareDebianPart(x[3] ?? \"0\", y[3] ?? \"0\");\n}\n\n// The comparison of rpmvercmp: segments of letters or digits. `~` comes before each other thing, also the end. `^` comes\n// after the end, but before each other segment.\nfunction rpmvercmp(a: string, b: string): number {\n if (a === b) return 0;\n let i = 0;\n let j = 0;\n for (;;) {\n while (i < a.length && !/[A-Za-z0-9~^]/.test(a[i]!)) i++;\n while (j < b.length && !/[A-Za-z0-9~^]/.test(b[j]!)) j++;\n const ca = a[i];\n const cb = b[j];\n if (ca === \"~\" || cb === \"~\") {\n if (ca !== \"~\") return 1;\n if (cb !== \"~\") return -1;\n i++;\n j++;\n continue;\n }\n if (ca === \"^\" || cb === \"^\") {\n if (ca === undefined) return -1;\n if (cb === undefined) return 1;\n if (ca !== \"^\") return 1;\n if (cb !== \"^\") return -1;\n i++;\n j++;\n continue;\n }\n if (ca === undefined || cb === undefined) break;\n const digits = /\\d/.test(ca);\n const same = digits ? /\\d/ : /[A-Za-z]/;\n let p = \"\";\n let q = \"\";\n while (i < a.length && same.test(a[i]!)) p += a[i++];\n while (j < b.length && same.test(b[j]!)) q += b[j++];\n // A segment of digits comes after a segment of letters.\n if (q === \"\") return digits ? 1 : -1;\n const c = digits ? compareDigits(p, q) : compareText(p, q);\n if (c !== 0) return c;\n }\n if (i >= a.length && j >= b.length) return 0;\n return i >= a.length ? -1 : 1;\n}\n\nconst RPM = /^(?:(\\d+):)?([^-]+)(?:-([^-]+))?$/;\n\n/** This function compares two RPM versions (`[epoch:]version[-release]`) with the order of `rpmvercmp`. */\nexport function compareRpm(a: string, b: string): number | undefined {\n const x = RPM.exec(a.trim());\n const y = RPM.exec(b.trim());\n if (x === null || y === null) return undefined;\n const epoch = compareDigits(x[1] ?? \"0\", y[1] ?? \"0\");\n if (epoch !== 0) return epoch;\n const version = rpmvercmp(x[2]!, y[2]!);\n if (version !== 0) return version;\n // A version with no release comes before each release of that version. Thus a check of a fix does not take it as fixed.\n return rpmvercmp(x[3] ?? \"\", y[3] ?? \"\");\n}\n","/**\n * The map from the ecosystems of OSV (`https://ossf.github.io/osv-schema/`) to purl types, and the purl of a package\n * of an OSV record.\n */\n\nimport { formatPurl, packagePurlOf } from \"./purl.ts\";\nimport type { Vers, VersConstraint } from \"./vers.ts\";\nimport { compareVersions, versionScheme } from \"./version.ts\";\n\n/**\n * The purl type of each OSV ecosystem that has one. An ecosystem that is not in the table has no purl.\n * For a Linux distribution, the table key is the part of the ecosystem before the first `:`.\n */\nexport const OSV_PURL_TYPES: Readonly<Record<string, string>> = {\n npm: \"npm\",\n PyPI: \"pypi\",\n \"crates.io\": \"cargo\",\n RubyGems: \"gem\",\n NuGet: \"nuget\",\n Go: \"golang\",\n Maven: \"maven\",\n Packagist: \"composer\",\n Pub: \"pub\",\n Hex: \"hex\",\n Hackage: \"hackage\",\n CRAN: \"cran\",\n \"GitHub Actions\": \"github\",\n Debian: \"deb\",\n Ubuntu: \"deb\",\n Alpine: \"apk\",\n};\n\n/** The purl namespace of each OSV ecosystem of a Linux distribution: the name of the distribution. */\nconst DISTRIBUTION: Readonly<Record<string, string>> = { Debian: \"debian\", Ubuntu: \"ubuntu\", Alpine: \"alpine\" };\n\n/** This function gives the namespace and the name of an OSV package name, as the purl type of its ecosystem splits them. */\nfunction split(type: string, name: string): { readonly namespace?: string; readonly name: string } | undefined {\n switch (type) {\n case \"npm\": {\n const slash = name.indexOf(\"/\");\n return name.startsWith(\"@\") && slash > 1 ? { namespace: name.slice(0, slash), name: name.slice(slash + 1) } : { name };\n }\n case \"golang\":\n case \"composer\":\n case \"github\": {\n const slash = name.lastIndexOf(\"/\");\n return slash > 0 ? { namespace: name.slice(0, slash), name: name.slice(slash + 1) } : { name };\n }\n case \"maven\": {\n const colon = name.indexOf(\":\");\n return colon > 0 ? { namespace: name.slice(0, colon), name: name.slice(colon + 1) } : undefined;\n }\n default:\n return { name };\n }\n}\n\n/**\n * This function gives the canonical purl of an OSV package, with no version. For an ecosystem with no purl type, or\n * a bad name, it gives `undefined`.\n */\nexport function osvPurl(ecosystem: string, name: string): string | undefined {\n const base = ecosystem.split(\":\")[0]!;\n const type = Object.hasOwn(OSV_PURL_TYPES, base) ? OSV_PURL_TYPES[base] : undefined;\n if (type === undefined || name === \"\") return undefined;\n const names = split(type, name);\n if (names === undefined) return undefined;\n const distribution = Object.hasOwn(DISTRIBUTION, base) ? DISTRIBUTION[base] : undefined;\n const namespace = distribution ?? names.namespace;\n return formatPurl({ type, ...(namespace === undefined ? {} : { namespace }), name: names.name });\n}\n\n/**\n * This function gives the purl of a package of an OSV record, with no version, qualifiers or subpath. A valid purl\n * of the record wins. Else the function builds the purl from the ecosystem and the name.\n */\nexport function osvPackagePurl(pkg: { readonly ecosystem: string; readonly name: string; readonly purl?: string }): string | undefined {\n const own = pkg.purl === undefined ? undefined : packagePurlOf(pkg.purl);\n return own ?? osvPurl(pkg.ecosystem, pkg.name);\n}\n\n/** One event of an OSV range, as the OSV schema writes it: each event has one of the four fields. */\nexport interface OsvEvent {\n readonly introduced?: string;\n readonly fixed?: string;\n readonly last_affected?: string;\n readonly limit?: string;\n}\n\n/** A range of an OSV record: its type (`SEMVER`, `ECOSYSTEM` or `GIT`) and its events. */\nexport interface OsvRange {\n readonly type: string;\n readonly events: readonly OsvEvent[];\n}\n\n/**\n * This function gives the `vers` range of an OSV range. A range of the type `SEMVER` has the scheme `semver`. A range\n * of the type `ECOSYSTEM` has the purl type of its ecosystem as its scheme. A `GIT` range, an ecosystem with no purl type\n * or an event with no version gives `undefined`.\n *\n * The events come in the order of their versions, as the OSV schema tells, when the scheme has a known order. Else they\n * keep the order of the record. The event `introduced 0` is the start of each version, so it gives no constraint.\n */\nexport function osvRangeVers(ecosystem: string, range: OsvRange): Vers | undefined {\n const base = ecosystem.split(\":\")[0]!;\n const type = Object.hasOwn(OSV_PURL_TYPES, base) ? OSV_PURL_TYPES[base] : undefined;\n const scheme = range.type === \"SEMVER\" ? \"semver\" : range.type === \"ECOSYSTEM\" ? type : undefined;\n if (scheme === undefined) return undefined;\n const constraints: VersConstraint[] = [];\n let all = false;\n for (const event of range.events) {\n const constraint = eventConstraint(event);\n if (constraint === undefined) return undefined;\n if (constraint === \"start\") all = true;\n else if (constraint !== \"none\") constraints.push(constraint);\n }\n if (constraints.length === 0) return all ? { scheme, all: true, constraints: [] } : undefined;\n return { scheme, all: false, constraints: sortEvents(scheme, constraints) };\n}\n\n// The constraint of one event: \"start\" for `introduced 0`, \"none\" for `limit *` (no limit).\nfunction eventConstraint(event: OsvEvent): VersConstraint | \"start\" | \"none\" | undefined {\n if (event.introduced !== undefined) return event.introduced === \"0\" ? \"start\" : { comparator: \">=\", version: event.introduced };\n if (event.fixed !== undefined) return { comparator: \"<\", version: event.fixed };\n if (event.last_affected !== undefined) return { comparator: \"<=\", version: event.last_affected };\n if (event.limit !== undefined) return event.limit === \"*\" ? \"none\" : { comparator: \"<\", version: event.limit };\n return undefined;\n}\n\n// The constraints in the order of their versions, or in their own order when the scheme has no known order.\nfunction sortEvents(scheme: string, constraints: readonly VersConstraint[]): VersConstraint[] {\n if (versionScheme(scheme) === undefined) return [...constraints];\n let unknown = false;\n const sorted = [...constraints].sort((a, b) => {\n const c = compareVersions(scheme, a.version, b.version);\n if (c === undefined) unknown = true;\n return c ?? 0;\n });\n return unknown ? [...constraints] : sorted;\n}\n","/**\n * Version ranges in the `vers` format of the purl specification, for example `vers:npm/>=1.0.0|<1.2.3`. The functions\n * parse a range, format it and tell if a version is in it, with the version order of the scheme.\n */\nimport { compareVersions } from \"./version.ts\";\n\n/** The comparators of a `vers` constraint. */\nexport type VersComparator = \"=\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\";\n\n/** One constraint of a range: a comparator and a version. */\nexport interface VersConstraint {\n readonly comparator: VersComparator;\n readonly version: string;\n}\n\n/** A version range. A range with the constraint `*` holds each version, and its list of constraints is empty. */\nexport interface Vers {\n /** The version scheme, for example `npm`, `pypi` or `deb`. */\n readonly scheme: string;\n /** True: the range is `*`, so it holds each version. */\n readonly all: boolean;\n readonly constraints: readonly VersConstraint[];\n}\n\n// The longer comparators come first, so `<=` is not read as `<` and a version that starts with `=`.\nconst COMPARATORS: readonly VersComparator[] = [\"!=\", \"<=\", \">=\", \"<\", \">\", \"=\"];\n\n/** This function reads one constraint, for example `>=1.0.0`. A constraint with no comparator has the comparator `=`. */\nfunction parseConstraint(text: string): VersConstraint | undefined {\n const trimmed = text.trim();\n const comparator = COMPARATORS.find((c) => trimmed.startsWith(c)) ?? \"=\";\n const raw = trimmed.slice(trimmed.startsWith(comparator) ? comparator.length : 0).trim();\n if (raw === \"\") return undefined;\n let version: string;\n try {\n version = decodeURIComponent(raw);\n } catch {\n return undefined;\n }\n return { comparator, version };\n}\n\n/** This function reads a `vers` text. A text that is not a range gives `undefined`. */\nexport function parseVers(text: string): Vers | undefined {\n const match = /^vers:([A-Za-z0-9.+-]+)\\/(.+)$/.exec(text.replace(/\\s+/g, \"\"));\n if (match === null) return undefined;\n const scheme = match[1]!.toLowerCase();\n const body = match[2]!;\n if (body === \"*\") return { scheme, all: true, constraints: [] };\n const constraints: VersConstraint[] = [];\n for (const part of body.split(\"|\")) {\n const constraint = parseConstraint(part);\n if (constraint === undefined) return undefined;\n constraints.push(constraint);\n }\n return { scheme, all: false, constraints };\n}\n\n// The characters that a version keeps in a `vers` text: the others are percent-encoded.\nconst encodeVersion = (version: string): string => version.replace(/[^A-Za-z0-9.+~_:-]/g, (c) => encodeURIComponent(c));\n\n/**\n * This function gives the `vers` text of a range. The constraints come in the order of the versions, when the scheme\n * has a known order. The comparator `=` has no sign, as the specification tells.\n */\nexport function formatVers(vers: Vers): string {\n if (vers.all) return `vers:${vers.scheme}/*`;\n const sorted = sortConstraints(vers.scheme, vers.constraints) ?? vers.constraints;\n const body = sorted.map((c) => `${c.comparator === \"=\" ? \"\" : c.comparator}${encodeVersion(c.version)}`).join(\"|\");\n return `vers:${vers.scheme}/${body}`;\n}\n\n// The constraints in the order of their versions, or `undefined` when a version is not a version of the scheme.\nfunction sortConstraints(scheme: string, constraints: readonly VersConstraint[]): VersConstraint[] | undefined {\n let unknown = false;\n const sorted = [...constraints].sort((a, b) => {\n const c = compareVersions(scheme, a.version, b.version);\n if (c === undefined) unknown = true;\n return c ?? 0;\n });\n return unknown ? undefined : sorted;\n}\n\n/**\n * This function tells if a version is in a range, with the algorithm of the `vers` specification. The result is\n * `undefined` when the scheme has no known order, or when a version is not a version of the scheme. Thus a caller\n * does not take an unknown result as a match or as no match.\n */\nexport function versContains(vers: Vers, version: string): boolean | undefined {\n if (vers.all) return true;\n const compare = (a: string, b: string): number | undefined => compareVersions(vers.scheme, a, b);\n for (const constraint of vers.constraints) {\n const c = compare(version, constraint.version);\n if (c === undefined) return undefined;\n if (c === 0 && [\"=\", \"<=\", \">=\"].includes(constraint.comparator)) return true;\n if (c === 0 && constraint.comparator === \"!=\") return false;\n }\n const ranged = sortConstraints(\n vers.scheme,\n vers.constraints.filter((c) => c.comparator !== \"=\" && c.comparator !== \"!=\"),\n );\n if (ranged === undefined) return undefined;\n if (ranged.length === 0) {\n // Only `!=` constraints that the version does not equal: the version is in the range.\n return vers.constraints.some((c) => c.comparator === \"!=\");\n }\n const below = (c: VersConstraint): boolean => c.comparator === \"<\" || c.comparator === \"<=\";\n const above = (c: VersConstraint): boolean => c.comparator === \">\" || c.comparator === \">=\";\n const first = ranged[0]!;\n const last = ranged[ranged.length - 1]!;\n if (below(first) && compare(version, first.version)! < 0) return true;\n if (above(last) && compare(version, last.version)! > 0) return true;\n for (let i = 0; i + 1 < ranged.length; i++) {\n const low = ranged[i]!;\n const high = ranged[i + 1]!;\n if (above(low) && below(high) && compare(version, low.version)! > 0 && compare(version, high.version)! < 0) return true;\n }\n return false;\n}\n\n/**\n * This function gives the end of the part of a range that holds a version, when that end is a constraint `<`. For the\n * range of an advisory, it is the first fixed version above the version. The result is `undefined` for a version out\n * of the range, or for an unknown order. It is also `undefined` for a part with no such end: `<=`, an open end or `=`.\n */\nexport function versEnd(vers: Vers, version: string): string | undefined {\n if (vers.all || versContains(vers, version) !== true) return undefined;\n if (vers.constraints.some((c) => c.comparator === \"=\" && compareVersions(vers.scheme, version, c.version) === 0)) return undefined;\n const ranged = sortConstraints(\n vers.scheme,\n vers.constraints.filter((c) => c.comparator !== \"=\" && c.comparator !== \"!=\"),\n );\n const next = ranged?.find((c) => compareVersions(vers.scheme, version, c.version)! < 0);\n return next?.comparator === \"<\" ? next.version : undefined;\n}\n"],"mappings":";;AAwBA,MAAM,OAAO;;AAGb,MAAM,MAAM;;;;;AAMZ,MAAM,2CAAgD,IAAI,IAAI;CAAC;CAAQ;CAAO;CAAa;CAAY;CAAO;CAAU;CAAU;AAAK,CAAC;;AAGxI,MAAM,6BAAkC,IAAI,IAAI;CAAC;CAAO;CAAO;AAAM,CAAC;;AAGtE,SAAS,OAAO,MAAsB;CACpC,OAAO,mBAAmB,IAAI,CAAC,CAC5B,QAAQ,aAAa,cAAc,IAAI,UAAU,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,GAAG,CAAC,CAC5F,QAAQ,QAAQ,GAAG;AACxB;;AAGA,SAAS,OAAO,MAAkC;CAChD,IAAI;EACF,OAAO,mBAAmB,IAAI;CAChC,QAAQ;EACN;CACF;AACF;;AAGA,SAAS,SAAS,MAAoC;CACpD,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,OAAO,KAAK,MAAM,GAAG,GAAG;EACjC,IAAI,QAAQ,IAAI;EAChB,MAAM,OAAO,OAAO,GAAG;EACvB,IAAI,SAAS,KAAA,GAAW,OAAO,KAAA;EAC/B,MAAM,KAAK,IAAI;CACjB;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,cAAc,MAA8B;CAC1D,MAAM,OAAO,KAAK,KAAK,YAAY;CACnC,IAAI,CAAC,KAAK,KAAK,IAAI,GAAG,OAAO,KAAA;CAC7B,MAAM,WAAW,yBAAyB,IAAI,IAAI;CAElD,IAAI,OADc,YAAY,WAAW,IAAI,IAAI,IAC1B,KAAK,KAAK,YAAY,IAAI,KAAK;CACtD,IAAI,SAAS,QAAQ,OAAO,KAAK,QAAQ,MAAM,GAAG;CA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,IAAI,MAAM,IAAI,KAAK,QAAQ,SAAS,KAAK,OAAO,IAAK,GAAG,OAAO;CAC/D,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,OAAO,QAAQ,KAAK;EAC1C,MAAM,MAAM,OAAO;EACnB,MAAM,OAAO,OAAO,IAAI;EACxB,IAAI,MAAM,GAAG,KAAK,MAAM,IAAI,KAAK,QAAQ,SAAS,IAAI,OAAO,IAAK,KAAK,QAAQ,SAAS,KAAK,OAAO,IAAK,GAAG,OAAO;CACrH;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,QAAQ,MAAY,SAAqC;CACvE,IAAI,KAAK,OAAO,aAAa,MAAM,OAAO,MAAM,MAAM,OAAO,KAAA;CAC7D,IAAI,KAAK,YAAY,MAAM,MAAM,EAAE,eAAe,OAAO,gBAAgB,KAAK,QAAQ,SAAS,EAAE,OAAO,MAAM,CAAC,GAAG,OAAO,KAAA;CAKzH,MAAM,OAJS,gBACb,KAAK,QACL,KAAK,YAAY,QAAQ,MAAM,EAAE,eAAe,OAAO,EAAE,eAAe,IAAI,CAE5D,CAAC,EAAE,MAAM,MAAM,gBAAgB,KAAK,QAAQ,SAAS,EAAE,OAAO,IAAK,CAAC;CACtF,OAAO,MAAM,eAAe,MAAM,KAAK,UAAU,KAAA;AACnD"}
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/package-id",
4
- "version": "0.0.1",
5
- "description": "Package URLs (purl): parse, format and normalize, and the purl of each OSV ecosystem. Plain functions with no fetch.",
4
+ "version": "0.0.2",
5
+ "description": "Package URLs (purl), the purl of each OSV ecosystem, the version order of each ecosystem and version ranges (vers). Plain functions with no fetch.",
6
6
  "keywords": [
7
7
  "purl",
8
8
  "package-url",
package/src/index.ts CHANGED
@@ -1,7 +1,18 @@
1
1
  /**
2
- * Package identities: package URLs (purl) and the purl of each OSV ecosystem. The functions are plain functions with
2
+ * Package identities: package URLs (purl), the purl of each OSV ecosystem, the version order of each ecosystem and version ranges (vers). The functions are plain functions with
3
3
  * no fetch.
4
4
  */
5
5
 
6
6
  export { formatPurl, normalizePurl, packagePurlOf, parsePurl, type Purl } from "./purl.ts";
7
- export { OSV_PURL_TYPES, osvPackagePurl, osvPurl } from "./osv.ts";
7
+ export { OSV_PURL_TYPES, osvPackagePurl, osvPurl, osvRangeVers, type OsvEvent, type OsvRange } from "./osv.ts";
8
+ export {
9
+ compareDebian,
10
+ compareGo,
11
+ comparePep440,
12
+ compareRpm,
13
+ compareSemver,
14
+ compareVersions,
15
+ versionScheme,
16
+ type VersionScheme,
17
+ } from "./version.ts";
18
+ export { formatVers, parseVers, versContains, versEnd, type Vers, type VersComparator, type VersConstraint } from "./vers.ts";
package/src/osv.ts CHANGED
@@ -4,6 +4,8 @@
4
4
  */
5
5
 
6
6
  import { formatPurl, packagePurlOf } from "./purl.ts";
7
+ import type { Vers, VersConstraint } from "./vers.ts";
8
+ import { compareVersions, versionScheme } from "./version.ts";
7
9
 
8
10
  /**
9
11
  * The purl type of each OSV ecosystem that has one. An ecosystem that is not in the table has no purl.
@@ -59,11 +61,11 @@ function split(type: string, name: string): { readonly namespace?: string; reado
59
61
  */
60
62
  export function osvPurl(ecosystem: string, name: string): string | undefined {
61
63
  const base = ecosystem.split(":")[0]!;
62
- const type = OSV_PURL_TYPES[base];
64
+ const type = Object.hasOwn(OSV_PURL_TYPES, base) ? OSV_PURL_TYPES[base] : undefined;
63
65
  if (type === undefined || name === "") return undefined;
64
66
  const names = split(type, name);
65
67
  if (names === undefined) return undefined;
66
- const distribution = DISTRIBUTION[base];
68
+ const distribution = Object.hasOwn(DISTRIBUTION, base) ? DISTRIBUTION[base] : undefined;
67
69
  const namespace = distribution ?? names.namespace;
68
70
  return formatPurl({ type, ...(namespace === undefined ? {} : { namespace }), name: names.name });
69
71
  }
@@ -76,3 +78,63 @@ export function osvPackagePurl(pkg: { readonly ecosystem: string; readonly name:
76
78
  const own = pkg.purl === undefined ? undefined : packagePurlOf(pkg.purl);
77
79
  return own ?? osvPurl(pkg.ecosystem, pkg.name);
78
80
  }
81
+
82
+ /** One event of an OSV range, as the OSV schema writes it: each event has one of the four fields. */
83
+ export interface OsvEvent {
84
+ readonly introduced?: string;
85
+ readonly fixed?: string;
86
+ readonly last_affected?: string;
87
+ readonly limit?: string;
88
+ }
89
+
90
+ /** A range of an OSV record: its type (`SEMVER`, `ECOSYSTEM` or `GIT`) and its events. */
91
+ export interface OsvRange {
92
+ readonly type: string;
93
+ readonly events: readonly OsvEvent[];
94
+ }
95
+
96
+ /**
97
+ * This function gives the `vers` range of an OSV range. A range of the type `SEMVER` has the scheme `semver`. A range
98
+ * of the type `ECOSYSTEM` has the purl type of its ecosystem as its scheme. A `GIT` range, an ecosystem with no purl type
99
+ * or an event with no version gives `undefined`.
100
+ *
101
+ * The events come in the order of their versions, as the OSV schema tells, when the scheme has a known order. Else they
102
+ * keep the order of the record. The event `introduced 0` is the start of each version, so it gives no constraint.
103
+ */
104
+ export function osvRangeVers(ecosystem: string, range: OsvRange): Vers | undefined {
105
+ const base = ecosystem.split(":")[0]!;
106
+ const type = Object.hasOwn(OSV_PURL_TYPES, base) ? OSV_PURL_TYPES[base] : undefined;
107
+ const scheme = range.type === "SEMVER" ? "semver" : range.type === "ECOSYSTEM" ? type : undefined;
108
+ if (scheme === undefined) return undefined;
109
+ const constraints: VersConstraint[] = [];
110
+ let all = false;
111
+ for (const event of range.events) {
112
+ const constraint = eventConstraint(event);
113
+ if (constraint === undefined) return undefined;
114
+ if (constraint === "start") all = true;
115
+ else if (constraint !== "none") constraints.push(constraint);
116
+ }
117
+ if (constraints.length === 0) return all ? { scheme, all: true, constraints: [] } : undefined;
118
+ return { scheme, all: false, constraints: sortEvents(scheme, constraints) };
119
+ }
120
+
121
+ // The constraint of one event: "start" for `introduced 0`, "none" for `limit *` (no limit).
122
+ function eventConstraint(event: OsvEvent): VersConstraint | "start" | "none" | undefined {
123
+ if (event.introduced !== undefined) return event.introduced === "0" ? "start" : { comparator: ">=", version: event.introduced };
124
+ if (event.fixed !== undefined) return { comparator: "<", version: event.fixed };
125
+ if (event.last_affected !== undefined) return { comparator: "<=", version: event.last_affected };
126
+ if (event.limit !== undefined) return event.limit === "*" ? "none" : { comparator: "<", version: event.limit };
127
+ return undefined;
128
+ }
129
+
130
+ // The constraints in the order of their versions, or in their own order when the scheme has no known order.
131
+ function sortEvents(scheme: string, constraints: readonly VersConstraint[]): VersConstraint[] {
132
+ if (versionScheme(scheme) === undefined) return [...constraints];
133
+ let unknown = false;
134
+ const sorted = [...constraints].sort((a, b) => {
135
+ const c = compareVersions(scheme, a.version, b.version);
136
+ if (c === undefined) unknown = true;
137
+ return c ?? 0;
138
+ });
139
+ return unknown ? [...constraints] : sorted;
140
+ }
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
+ }