@mark1russell7/package-id 0.0.0-bootstrap.0 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mark Russell
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,44 @@
1
1
  # @mark1russell7/package-id
2
2
 
3
- This version is a placeholder. The release workflow of https://github.com/mark1russell7/package-id publishes the real versions. Use a later version.
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).
4
+
5
+ ```ts
6
+ import { formatPurl, osvPurl, packagePurlOf, parsePurl } from "@mark1russell7/package-id";
7
+
8
+ parsePurl("pkg:npm/%40angular/animation@12.3.1");
9
+ // { type: "npm", namespace: "@angular", name: "animation", version: "12.3.1" }
10
+
11
+ formatPurl({ type: "pypi", name: "Django_package", version: "1.11.1" });
12
+ // "pkg:pypi/django-package@1.11.1"
13
+
14
+ packagePurlOf("pkg:npm/a@1.0.0?arch=x#sub");
15
+ // "pkg:npm/a"
16
+
17
+ osvPurl("Maven", "org.example:core");
18
+ // "pkg:maven/org.example/core"
19
+ ```
20
+
21
+ ## The functions
22
+
23
+ | Function | What it gives |
24
+ | --- | --- |
25
+ | `parsePurl(text)` | The parts of a purl text, decoded and normalized, or `undefined` for a text that is not a purl. |
26
+ | `formatPurl(purl)` | The canonical text of a purl, or `undefined` when a part breaks a rule. |
27
+ | `normalizePurl(purl)` | The canonical parts: the case rules of the type, sorted qualifiers and no empty part. |
28
+ | `packagePurlOf(text)` | The canonical purl with no version, no qualifiers and no subpath. |
29
+ | `osvPurl(ecosystem, name)` | The purl of a package of an OSV ecosystem, with no version. |
30
+ | `osvPackagePurl(pkg)` | The purl of an OSV record package. A valid purl of the record wins. |
31
+ | `OSV_PURL_TYPES` | The purl type of each OSV ecosystem that has one. |
32
+
33
+ ## The canonical form
34
+
35
+ - The type is in lower case.
36
+ - For the types `alpm`, `apk`, `bitbucket`, `composer`, `deb`, `github`, `golang` and `npm`, the namespace and the name are in lower case.
37
+ - For the types `hex`, `pub` and `pypi`, the name is in lower case. A `pypi` name has `-` in place of `_`.
38
+ - The qualifier keys are in lower case and in sorted order. A qualifier with an empty value is not in the purl.
39
+ - The subpath has no empty, `.` or `..` segment.
40
+ - Each part is percent-encoded, but a colon stays as it is. A qualifier value keeps its `/`.
41
+
42
+ ## License
43
+
44
+ MIT
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Package identities: package URLs (purl) and the purl of each OSV ecosystem. The functions are plain functions with
3
+ * no fetch.
4
+ */
5
+ /**
6
+ * Package URLs (purl): parse, format and normalize, as the purl specification tells
7
+ * (`https://github.com/package-url/purl-spec`). The form is `pkg:type/namespace/name@version?qualifiers#subpath`.
8
+ *
9
+ * The functions are plain functions with no fetch and no state.
10
+ */
11
+ /** A package URL as its parts. Each text part is decoded: it has no percent-encoding. */
12
+ interface Purl {
13
+ /** The type of the package, in lower case, for example `npm` or `pypi`. */
14
+ readonly type: string;
15
+ /** The namespace, with `/` between its segments, or `undefined` when the purl has no namespace. */
16
+ readonly namespace?: string;
17
+ /** The name of the package. */
18
+ readonly name: string;
19
+ /** The version, or `undefined` when the purl has no version. */
20
+ readonly version?: string;
21
+ /** The qualifiers, with lower-case keys. A qualifier with an empty value is not in the record. */
22
+ readonly qualifiers?: Readonly<Record<string, string>>;
23
+ /** The subpath, with `/` between its segments, or `undefined` when the purl has no subpath. */
24
+ readonly subpath?: string;
25
+ }
26
+ /**
27
+ * This function gives the canonical parts of a purl. The type and the qualifier keys are in lower case. The parts
28
+ * follow the case rules of the type, and no part is empty.
29
+ * It gives `undefined` when a part breaks a rule of the specification.
30
+ */
31
+ export declare function normalizePurl(purl: Purl): Purl | undefined;
32
+ /**
33
+ * This function reads a purl text into its parts, as the parse steps of the specification tell, and normalizes them.
34
+ * It gives `undefined` when the text is not a valid purl.
35
+ */
36
+ export declare function parsePurl(text: string): Purl | undefined;
37
+ /**
38
+ * This function writes the canonical text of a purl: the parts normalized, each part percent-encoded and the
39
+ * qualifiers in the order of their keys. It gives `undefined` when a part breaks a rule of the specification.
40
+ */
41
+ export declare function formatPurl(purl: Purl): string | undefined;
42
+ /**
43
+ * This function gives the canonical purl of the package with no version, no qualifiers and no subpath. A person who
44
+ * names a package with this text names each version of it. It gives `undefined` when the text is not a valid purl.
45
+ */
46
+ export declare function packagePurlOf(text: string): string | undefined;
47
+ /**
48
+ * The purl type of each OSV ecosystem that has one. An ecosystem that is not in the table has no purl.
49
+ * For a Linux distribution, the table key is the part of the ecosystem before the first `:`.
50
+ */
51
+ export declare const OSV_PURL_TYPES: Readonly<Record<string, string>>;
52
+ /**
53
+ * This function gives the canonical purl of an OSV package, with no version. For an ecosystem with no purl type, or
54
+ * a bad name, it gives `undefined`.
55
+ */
56
+ export declare function osvPurl(ecosystem: string, name: string): string | undefined;
57
+ /**
58
+ * This function gives the purl of a package of an OSV record, with no version, qualifiers or subpath. A valid purl
59
+ * of the record wins. Else the function builds the purl from the ecosystem and the name.
60
+ */
61
+ export declare function osvPackagePurl(pkg: {
62
+ readonly ecosystem: string;
63
+ readonly name: string;
64
+ readonly purl?: string;
65
+ }): string | undefined;
66
+ export type { Purl };
67
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +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"}
package/build/index.js ADDED
@@ -0,0 +1,252 @@
1
+ // src/purl.ts
2
+ /** The pattern of a type: a letter first, then letters, digits, `.`, `+` or `-`. */
3
+ const TYPE = /^[a-z][a-z0-9.+-]*$/;
4
+ /** The pattern of a qualifier key: a letter first, then letters, digits, `.`, `-` or `_`. */
5
+ const KEY = /^[a-z][a-z0-9._-]*$/;
6
+ /**
7
+ * The types whose namespace and name are not case sensitive. The canonical form of these parts is lower case.
8
+ * The list comes from the type definitions of the purl specification.
9
+ */
10
+ const LOWER_NAMESPACE_AND_NAME = /* @__PURE__ */ new Set([
11
+ "alpm",
12
+ "apk",
13
+ "bitbucket",
14
+ "composer",
15
+ "deb",
16
+ "github",
17
+ "golang",
18
+ "npm"
19
+ ]);
20
+ /** The types whose name only is not case sensitive. The canonical form of the name is lower case. */
21
+ const LOWER_NAME = /* @__PURE__ */ new Set([
22
+ "hex",
23
+ "pub",
24
+ "pypi"
25
+ ]);
26
+ /** This function percent-encodes one part of a purl. A letter, a digit, `.-_~` and `:` stay as they are. */
27
+ function encode(text) {
28
+ return encodeURIComponent(text).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%3A/g, ":");
29
+ }
30
+ /** This function decodes one part of a purl, or gives `undefined` for a bad percent-encoding. */
31
+ function decode(text) {
32
+ try {
33
+ return decodeURIComponent(text);
34
+ } catch {
35
+ return;
36
+ }
37
+ }
38
+ /** This function splits a path into its decoded segments. It discards each empty segment. */
39
+ function segments(text) {
40
+ const parts = [];
41
+ for (const raw of text.split("/")) {
42
+ if (raw === "") continue;
43
+ const part = decode(raw);
44
+ if (part === void 0) return void 0;
45
+ parts.push(part);
46
+ }
47
+ return parts;
48
+ }
49
+ /**
50
+ * This function gives the canonical parts of a purl. The type and the qualifier keys are in lower case. The parts
51
+ * follow the case rules of the type, and no part is empty.
52
+ * It gives `undefined` when a part breaks a rule of the specification.
53
+ */
54
+ function normalizePurl(purl) {
55
+ const type = purl.type.toLowerCase();
56
+ if (!TYPE.test(type)) return void 0;
57
+ const lowerAll = LOWER_NAMESPACE_AND_NAME.has(type);
58
+ let name = lowerAll || LOWER_NAME.has(type) ? purl.name.toLowerCase() : purl.name;
59
+ if (type === "pypi") name = name.replace(/_/g, "-");
60
+ if (name === "") return void 0;
61
+ const space = purl.namespace?.split("/").filter((segment) => segment !== "").join("/");
62
+ const namespace = space === void 0 || space === "" ? void 0 : lowerAll ? space.toLowerCase() : space;
63
+ if (type === "maven" && namespace === void 0) return void 0;
64
+ const qualifiers = {};
65
+ for (const [key, value] of Object.entries(purl.qualifiers ?? {})) {
66
+ const lower = key.toLowerCase();
67
+ if (!KEY.test(lower)) return void 0;
68
+ if (value !== "") qualifiers[lower] = value;
69
+ }
70
+ const subpath = purl.subpath?.split("/").filter((segment) => segment !== "" && segment !== "." && segment !== "..").join("/");
71
+ return {
72
+ type,
73
+ ...namespace === void 0 ? {} : { namespace },
74
+ name,
75
+ ...purl.version === void 0 || purl.version === "" ? {} : { version: purl.version },
76
+ ...Object.keys(qualifiers).length === 0 ? {} : { qualifiers },
77
+ ...subpath === void 0 || subpath === "" ? {} : { subpath }
78
+ };
79
+ }
80
+ /**
81
+ * This function reads a purl text into its parts, as the parse steps of the specification tell, and normalizes them.
82
+ * It gives `undefined` when the text is not a valid purl.
83
+ */
84
+ function parsePurl(text) {
85
+ let rest = text.trim();
86
+ let subpath;
87
+ const hash = rest.indexOf("#");
88
+ if (hash >= 0) {
89
+ const parts = segments(rest.slice(hash + 1));
90
+ if (parts === void 0) return void 0;
91
+ subpath = parts.filter((segment) => segment !== "." && segment !== "..").join("/");
92
+ rest = rest.slice(0, hash);
93
+ }
94
+ let qualifiers;
95
+ const question = rest.indexOf("?");
96
+ if (question >= 0) {
97
+ qualifiers = {};
98
+ for (const pair of rest.slice(question + 1).split("&")) {
99
+ if (pair === "") continue;
100
+ const equal = pair.indexOf("=");
101
+ if (equal <= 0) return void 0;
102
+ const key = pair.slice(0, equal).toLowerCase();
103
+ const value = decode(pair.slice(equal + 1));
104
+ if (value === void 0 || key in qualifiers) return void 0;
105
+ qualifiers[key] = value;
106
+ }
107
+ rest = rest.slice(0, question);
108
+ }
109
+ const colon = rest.indexOf(":");
110
+ if (colon < 0 || rest.slice(0, colon).toLowerCase() !== "pkg") return void 0;
111
+ rest = rest.slice(colon + 1).replace(/^\/+/, "");
112
+ const slash = rest.indexOf("/");
113
+ if (slash <= 0) return void 0;
114
+ const type = rest.slice(0, slash);
115
+ rest = rest.slice(slash + 1);
116
+ let version;
117
+ const at = rest.lastIndexOf("@");
118
+ if (at > 0) {
119
+ version = decode(rest.slice(at + 1));
120
+ if (version === void 0) return void 0;
121
+ rest = rest.slice(0, at);
122
+ }
123
+ const path = segments(rest);
124
+ if (path === void 0 || path.length === 0) return void 0;
125
+ const name = path[path.length - 1];
126
+ const namespace = path.length > 1 ? path.slice(0, -1).join("/") : void 0;
127
+ return normalizePurl({
128
+ type,
129
+ ...namespace === void 0 ? {} : { namespace },
130
+ name,
131
+ ...version === void 0 ? {} : { version },
132
+ ...qualifiers === void 0 ? {} : { qualifiers },
133
+ ...subpath === void 0 ? {} : { subpath }
134
+ });
135
+ }
136
+ /**
137
+ * This function writes the canonical text of a purl: the parts normalized, each part percent-encoded and the
138
+ * qualifiers in the order of their keys. It gives `undefined` when a part breaks a rule of the specification.
139
+ */
140
+ function formatPurl(purl) {
141
+ const canonical = normalizePurl(purl);
142
+ if (canonical === void 0) return void 0;
143
+ let text = `pkg:${canonical.type}/`;
144
+ if (canonical.namespace !== void 0) text += `${canonical.namespace.split("/").map(encode).join("/")}/`;
145
+ text += encode(canonical.name);
146
+ if (canonical.version !== void 0) text += `@${encode(canonical.version)}`;
147
+ const keys = Object.keys(canonical.qualifiers ?? {}).sort();
148
+ if (keys.length > 0) text += `?${keys.map((key) => `${key}=${encode(canonical.qualifiers[key]).replace(/%2F/g, "/")}`).join("&")}`;
149
+ if (canonical.subpath !== void 0) text += `#${canonical.subpath.split("/").map(encode).join("/")}`;
150
+ return text;
151
+ }
152
+ /**
153
+ * This function gives the canonical purl of the package with no version, no qualifiers and no subpath. A person who
154
+ * names a package with this text names each version of it. It gives `undefined` when the text is not a valid purl.
155
+ */
156
+ function packagePurlOf(text) {
157
+ const purl = parsePurl(text);
158
+ return purl === void 0 ? void 0 : formatPurl({
159
+ type: purl.type,
160
+ ...purl.namespace === void 0 ? {} : { namespace: purl.namespace },
161
+ name: purl.name
162
+ });
163
+ }
164
+ // src/osv.ts
165
+ /**
166
+ * The map from the ecosystems of OSV (`https://ossf.github.io/osv-schema/`) to purl types, and the purl of a package
167
+ * of an OSV record.
168
+ */
169
+ /**
170
+ * The purl type of each OSV ecosystem that has one. An ecosystem that is not in the table has no purl.
171
+ * For a Linux distribution, the table key is the part of the ecosystem before the first `:`.
172
+ */
173
+ const OSV_PURL_TYPES = {
174
+ npm: "npm",
175
+ PyPI: "pypi",
176
+ "crates.io": "cargo",
177
+ RubyGems: "gem",
178
+ NuGet: "nuget",
179
+ Go: "golang",
180
+ Maven: "maven",
181
+ Packagist: "composer",
182
+ Pub: "pub",
183
+ Hex: "hex",
184
+ Hackage: "hackage",
185
+ CRAN: "cran",
186
+ "GitHub Actions": "github",
187
+ Debian: "deb",
188
+ Ubuntu: "deb",
189
+ Alpine: "apk"
190
+ };
191
+ /** The purl namespace of each OSV ecosystem of a Linux distribution: the name of the distribution. */
192
+ const DISTRIBUTION = {
193
+ Debian: "debian",
194
+ Ubuntu: "ubuntu",
195
+ Alpine: "alpine"
196
+ };
197
+ /** This function gives the namespace and the name of an OSV package name, as the purl type of its ecosystem splits them. */
198
+ function split(type, name) {
199
+ switch (type) {
200
+ case "npm": {
201
+ const slash = name.indexOf("/");
202
+ return name.startsWith("@") && slash > 1 ? {
203
+ namespace: name.slice(0, slash),
204
+ name: name.slice(slash + 1)
205
+ } : { name };
206
+ }
207
+ case "golang":
208
+ case "composer":
209
+ case "github": {
210
+ const slash = name.lastIndexOf("/");
211
+ return slash > 0 ? {
212
+ namespace: name.slice(0, slash),
213
+ name: name.slice(slash + 1)
214
+ } : { name };
215
+ }
216
+ case "maven": {
217
+ const colon = name.indexOf(":");
218
+ return colon > 0 ? {
219
+ namespace: name.slice(0, colon),
220
+ name: name.slice(colon + 1)
221
+ } : void 0;
222
+ }
223
+ default: return { name };
224
+ }
225
+ }
226
+ /**
227
+ * This function gives the canonical purl of an OSV package, with no version. For an ecosystem with no purl type, or
228
+ * a bad name, it gives `undefined`.
229
+ */
230
+ function osvPurl(ecosystem, name) {
231
+ const base = ecosystem.split(":")[0];
232
+ const type = OSV_PURL_TYPES[base];
233
+ if (type === void 0 || name === "") return void 0;
234
+ const names = split(type, name);
235
+ if (names === void 0) return void 0;
236
+ const namespace = DISTRIBUTION[base] ?? names.namespace;
237
+ return formatPurl({
238
+ type,
239
+ ...namespace === void 0 ? {} : { namespace },
240
+ name: names.name
241
+ });
242
+ }
243
+ /**
244
+ * This function gives the purl of a package of an OSV record, with no version, qualifiers or subpath. A valid purl
245
+ * of the record wins. Else the function builds the purl from the ecosystem and the name.
246
+ */
247
+ function osvPackagePurl(pkg) {
248
+ return (pkg.purl === void 0 ? void 0 : packagePurlOf(pkg.purl)) ?? osvPurl(pkg.ecosystem, pkg.name);
249
+ }
250
+ export { OSV_PURL_TYPES, formatPurl, normalizePurl, osvPackagePurl, osvPurl, packagePurlOf, parsePurl };
251
+
252
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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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AAU,KAAA,GAAW,OAAO,KAAA;CAEhC,MAAM,YADe,aAAa,SACA,MAAM;CACxC,OAAO,WAAW;EAAE;EAAM,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;EAAI,MAAM,MAAM;CAAK,CAAC;AACjG;;;;;AAMA,SAAgB,eAAe,KAAwG;CAErI,QADY,IAAI,SAAS,KAAA,IAAY,KAAA,IAAY,cAAc,IAAI,IAAI,MACzD,QAAQ,IAAI,WAAW,IAAI,IAAI;AAC/C"}
package/package.json CHANGED
@@ -1,13 +1,61 @@
1
1
  {
2
+ "$schema": "https://json.schemastore.org/package",
2
3
  "name": "@mark1russell7/package-id",
3
- "version": "0.0.0-bootstrap.0",
4
- "description": "A placeholder that lets npm trust the release workflow of mark1russell7/package-id. Use a later version.",
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.",
6
+ "keywords": [
7
+ "purl",
8
+ "package-url",
9
+ "osv",
10
+ "sbom",
11
+ "typescript"
12
+ ],
13
+ "homepage": "https://github.com/mark1russell7/package-id#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/mark1russell7/package-id/issues"
16
+ },
5
17
  "repository": {
6
18
  "type": "git",
7
- "url": "git+https://github.com/mark1russell7/package-id.git"
19
+ "url": "git+https://github.com/mark1russell7/package-id.git",
20
+ "directory": "packages/package-id"
8
21
  },
9
22
  "license": "MIT",
23
+ "author": "Mark Russell (https://github.com/mark1russell7)",
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "main": "./build/index.js",
27
+ "types": "./build/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./build/index.d.ts",
31
+ "default": "./build/index.js"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "build",
37
+ "src",
38
+ "!src/**/*.test.ts"
39
+ ],
40
+ "engines": {
41
+ "node": ">=22.12"
42
+ },
10
43
  "publishConfig": {
11
44
  "access": "public"
45
+ },
46
+ "devDependencies": {
47
+ "@mark1russell7/cue": "^2.0.0",
48
+ "@types/node": "^26.6.5",
49
+ "@vitest/coverage-v8": "^5.0.3",
50
+ "esbuild": "^0.28.2",
51
+ "tsdown": "^0.23.7",
52
+ "typescript": "^7.0.2",
53
+ "vitest": "^5.0.3"
54
+ },
55
+ "scripts": {
56
+ "build": "tsdown",
57
+ "test": "vitest run",
58
+ "test:watch": "vitest",
59
+ "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json"
12
60
  }
13
- }
61
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Package identities: package URLs (purl) and the purl of each OSV ecosystem. The functions are plain functions with
3
+ * no fetch.
4
+ */
5
+
6
+ export { formatPurl, normalizePurl, packagePurlOf, parsePurl, type Purl } from "./purl.ts";
7
+ export { OSV_PURL_TYPES, osvPackagePurl, osvPurl } from "./osv.ts";
package/src/osv.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The map from the ecosystems of OSV (`https://ossf.github.io/osv-schema/`) to purl types, and the purl of a package
3
+ * of an OSV record.
4
+ */
5
+
6
+ import { formatPurl, packagePurlOf } from "./purl.ts";
7
+
8
+ /**
9
+ * The purl type of each OSV ecosystem that has one. An ecosystem that is not in the table has no purl.
10
+ * For a Linux distribution, the table key is the part of the ecosystem before the first `:`.
11
+ */
12
+ export const OSV_PURL_TYPES: Readonly<Record<string, string>> = {
13
+ npm: "npm",
14
+ PyPI: "pypi",
15
+ "crates.io": "cargo",
16
+ RubyGems: "gem",
17
+ NuGet: "nuget",
18
+ Go: "golang",
19
+ Maven: "maven",
20
+ Packagist: "composer",
21
+ Pub: "pub",
22
+ Hex: "hex",
23
+ Hackage: "hackage",
24
+ CRAN: "cran",
25
+ "GitHub Actions": "github",
26
+ Debian: "deb",
27
+ Ubuntu: "deb",
28
+ Alpine: "apk",
29
+ };
30
+
31
+ /** The purl namespace of each OSV ecosystem of a Linux distribution: the name of the distribution. */
32
+ const DISTRIBUTION: Readonly<Record<string, string>> = { Debian: "debian", Ubuntu: "ubuntu", Alpine: "alpine" };
33
+
34
+ /** This function gives the namespace and the name of an OSV package name, as the purl type of its ecosystem splits them. */
35
+ function split(type: string, name: string): { readonly namespace?: string; readonly name: string } | undefined {
36
+ switch (type) {
37
+ case "npm": {
38
+ const slash = name.indexOf("/");
39
+ return name.startsWith("@") && slash > 1 ? { namespace: name.slice(0, slash), name: name.slice(slash + 1) } : { name };
40
+ }
41
+ case "golang":
42
+ case "composer":
43
+ case "github": {
44
+ const slash = name.lastIndexOf("/");
45
+ return slash > 0 ? { namespace: name.slice(0, slash), name: name.slice(slash + 1) } : { name };
46
+ }
47
+ case "maven": {
48
+ const colon = name.indexOf(":");
49
+ return colon > 0 ? { namespace: name.slice(0, colon), name: name.slice(colon + 1) } : undefined;
50
+ }
51
+ default:
52
+ return { name };
53
+ }
54
+ }
55
+
56
+ /**
57
+ * This function gives the canonical purl of an OSV package, with no version. For an ecosystem with no purl type, or
58
+ * a bad name, it gives `undefined`.
59
+ */
60
+ export function osvPurl(ecosystem: string, name: string): string | undefined {
61
+ const base = ecosystem.split(":")[0]!;
62
+ const type = OSV_PURL_TYPES[base];
63
+ if (type === undefined || name === "") return undefined;
64
+ const names = split(type, name);
65
+ if (names === undefined) return undefined;
66
+ const distribution = DISTRIBUTION[base];
67
+ const namespace = distribution ?? names.namespace;
68
+ return formatPurl({ type, ...(namespace === undefined ? {} : { namespace }), name: names.name });
69
+ }
70
+
71
+ /**
72
+ * This function gives the purl of a package of an OSV record, with no version, qualifiers or subpath. A valid purl
73
+ * of the record wins. Else the function builds the purl from the ecosystem and the name.
74
+ */
75
+ export function osvPackagePurl(pkg: { readonly ecosystem: string; readonly name: string; readonly purl?: string }): string | undefined {
76
+ const own = pkg.purl === undefined ? undefined : packagePurlOf(pkg.purl);
77
+ return own ?? osvPurl(pkg.ecosystem, pkg.name);
78
+ }
package/src/purl.ts ADDED
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Package URLs (purl): parse, format and normalize, as the purl specification tells
3
+ * (`https://github.com/package-url/purl-spec`). The form is `pkg:type/namespace/name@version?qualifiers#subpath`.
4
+ *
5
+ * The functions are plain functions with no fetch and no state.
6
+ */
7
+
8
+ /** A package URL as its parts. Each text part is decoded: it has no percent-encoding. */
9
+ export interface Purl {
10
+ /** The type of the package, in lower case, for example `npm` or `pypi`. */
11
+ readonly type: string;
12
+ /** The namespace, with `/` between its segments, or `undefined` when the purl has no namespace. */
13
+ readonly namespace?: string;
14
+ /** The name of the package. */
15
+ readonly name: string;
16
+ /** The version, or `undefined` when the purl has no version. */
17
+ readonly version?: string;
18
+ /** The qualifiers, with lower-case keys. A qualifier with an empty value is not in the record. */
19
+ readonly qualifiers?: Readonly<Record<string, string>>;
20
+ /** The subpath, with `/` between its segments, or `undefined` when the purl has no subpath. */
21
+ readonly subpath?: string;
22
+ }
23
+
24
+ /** The pattern of a type: a letter first, then letters, digits, `.`, `+` or `-`. */
25
+ const TYPE = /^[a-z][a-z0-9.+-]*$/;
26
+
27
+ /** The pattern of a qualifier key: a letter first, then letters, digits, `.`, `-` or `_`. */
28
+ const KEY = /^[a-z][a-z0-9._-]*$/;
29
+
30
+ /**
31
+ * The types whose namespace and name are not case sensitive. The canonical form of these parts is lower case.
32
+ * The list comes from the type definitions of the purl specification.
33
+ */
34
+ const LOWER_NAMESPACE_AND_NAME: ReadonlySet<string> = new Set(["alpm", "apk", "bitbucket", "composer", "deb", "github", "golang", "npm"]);
35
+
36
+ /** The types whose name only is not case sensitive. The canonical form of the name is lower case. */
37
+ const LOWER_NAME: ReadonlySet<string> = new Set(["hex", "pub", "pypi"]);
38
+
39
+ /** This function percent-encodes one part of a purl. A letter, a digit, `.-_~` and `:` stay as they are. */
40
+ function encode(text: string): string {
41
+ return encodeURIComponent(text)
42
+ .replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`)
43
+ .replace(/%3A/g, ":");
44
+ }
45
+
46
+ /** This function decodes one part of a purl, or gives `undefined` for a bad percent-encoding. */
47
+ function decode(text: string): string | undefined {
48
+ try {
49
+ return decodeURIComponent(text);
50
+ } catch {
51
+ return undefined;
52
+ }
53
+ }
54
+
55
+ /** This function splits a path into its decoded segments. It discards each empty segment. */
56
+ function segments(text: string): string[] | undefined {
57
+ const parts: string[] = [];
58
+ for (const raw of text.split("/")) {
59
+ if (raw === "") continue;
60
+ const part = decode(raw);
61
+ if (part === undefined) return undefined;
62
+ parts.push(part);
63
+ }
64
+ return parts;
65
+ }
66
+
67
+ /**
68
+ * This function gives the canonical parts of a purl. The type and the qualifier keys are in lower case. The parts
69
+ * follow the case rules of the type, and no part is empty.
70
+ * It gives `undefined` when a part breaks a rule of the specification.
71
+ */
72
+ export function normalizePurl(purl: Purl): Purl | undefined {
73
+ const type = purl.type.toLowerCase();
74
+ if (!TYPE.test(type)) return undefined;
75
+ const lowerAll = LOWER_NAMESPACE_AND_NAME.has(type);
76
+ const lowerName = lowerAll || LOWER_NAME.has(type);
77
+ let name = lowerName ? purl.name.toLowerCase() : purl.name;
78
+ if (type === "pypi") name = name.replace(/_/g, "-");
79
+ if (name === "") return undefined;
80
+ const space = purl.namespace?.split("/").filter((segment) => segment !== "").join("/");
81
+ const namespace = space === undefined || space === "" ? undefined : lowerAll ? space.toLowerCase() : space;
82
+ if (type === "maven" && namespace === undefined) return undefined;
83
+ const qualifiers: Record<string, string> = {};
84
+ for (const [key, value] of Object.entries(purl.qualifiers ?? {})) {
85
+ const lower = key.toLowerCase();
86
+ if (!KEY.test(lower)) return undefined;
87
+ if (value !== "") qualifiers[lower] = value;
88
+ }
89
+ const subpath = purl.subpath
90
+ ?.split("/")
91
+ .filter((segment) => segment !== "" && segment !== "." && segment !== "..")
92
+ .join("/");
93
+ return {
94
+ type,
95
+ ...(namespace === undefined ? {} : { namespace }),
96
+ name,
97
+ ...(purl.version === undefined || purl.version === "" ? {} : { version: purl.version }),
98
+ ...(Object.keys(qualifiers).length === 0 ? {} : { qualifiers }),
99
+ ...(subpath === undefined || subpath === "" ? {} : { subpath }),
100
+ };
101
+ }
102
+
103
+ /**
104
+ * This function reads a purl text into its parts, as the parse steps of the specification tell, and normalizes them.
105
+ * It gives `undefined` when the text is not a valid purl.
106
+ */
107
+ export function parsePurl(text: string): Purl | undefined {
108
+ let rest = text.trim();
109
+ let subpath: string | undefined;
110
+ const hash = rest.indexOf("#");
111
+ if (hash >= 0) {
112
+ const parts = segments(rest.slice(hash + 1));
113
+ if (parts === undefined) return undefined;
114
+ subpath = parts.filter((segment) => segment !== "." && segment !== "..").join("/");
115
+ rest = rest.slice(0, hash);
116
+ }
117
+ let qualifiers: Record<string, string> | undefined;
118
+ const question = rest.indexOf("?");
119
+ if (question >= 0) {
120
+ qualifiers = {};
121
+ for (const pair of rest.slice(question + 1).split("&")) {
122
+ if (pair === "") continue;
123
+ const equal = pair.indexOf("=");
124
+ if (equal <= 0) return undefined;
125
+ const key = pair.slice(0, equal).toLowerCase();
126
+ const value = decode(pair.slice(equal + 1));
127
+ if (value === undefined || key in qualifiers) return undefined;
128
+ qualifiers[key] = value;
129
+ }
130
+ rest = rest.slice(0, question);
131
+ }
132
+ const colon = rest.indexOf(":");
133
+ if (colon < 0 || rest.slice(0, colon).toLowerCase() !== "pkg") return undefined;
134
+ rest = rest.slice(colon + 1).replace(/^\/+/, "");
135
+ const slash = rest.indexOf("/");
136
+ if (slash <= 0) return undefined;
137
+ const type = rest.slice(0, slash);
138
+ rest = rest.slice(slash + 1);
139
+ let version: string | undefined;
140
+ const at = rest.lastIndexOf("@");
141
+ // An npm scope in a purl is `%40`, so a raw `@` starts the version. A raw `@` at the start of the
142
+ // namespace is not a version.
143
+ if (at > 0) {
144
+ version = decode(rest.slice(at + 1));
145
+ if (version === undefined) return undefined;
146
+ rest = rest.slice(0, at);
147
+ }
148
+ const path = segments(rest);
149
+ if (path === undefined || path.length === 0) return undefined;
150
+ const name = path[path.length - 1]!;
151
+ const namespace = path.length > 1 ? path.slice(0, -1).join("/") : undefined;
152
+ return normalizePurl({
153
+ type,
154
+ ...(namespace === undefined ? {} : { namespace }),
155
+ name,
156
+ ...(version === undefined ? {} : { version }),
157
+ ...(qualifiers === undefined ? {} : { qualifiers }),
158
+ ...(subpath === undefined ? {} : { subpath }),
159
+ });
160
+ }
161
+
162
+ /**
163
+ * This function writes the canonical text of a purl: the parts normalized, each part percent-encoded and the
164
+ * qualifiers in the order of their keys. It gives `undefined` when a part breaks a rule of the specification.
165
+ */
166
+ export function formatPurl(purl: Purl): string | undefined {
167
+ const canonical = normalizePurl(purl);
168
+ if (canonical === undefined) return undefined;
169
+ let text = `pkg:${canonical.type}/`;
170
+ if (canonical.namespace !== undefined) text += `${canonical.namespace.split("/").map(encode).join("/")}/`;
171
+ text += encode(canonical.name);
172
+ if (canonical.version !== undefined) text += `@${encode(canonical.version)}`;
173
+ const keys = Object.keys(canonical.qualifiers ?? {}).sort();
174
+ // A qualifier value keeps its `/`, as the test suite of the specification does with `repository_url`.
175
+ if (keys.length > 0) text += `?${keys.map((key) => `${key}=${encode(canonical.qualifiers![key]!).replace(/%2F/g, "/")}`).join("&")}`;
176
+ if (canonical.subpath !== undefined) text += `#${canonical.subpath.split("/").map(encode).join("/")}`;
177
+ return text;
178
+ }
179
+
180
+ /**
181
+ * This function gives the canonical purl of the package with no version, no qualifiers and no subpath. A person who
182
+ * names a package with this text names each version of it. It gives `undefined` when the text is not a valid purl.
183
+ */
184
+ export function packagePurlOf(text: string): string | undefined {
185
+ const purl = parsePurl(text);
186
+ return purl === undefined ? undefined : formatPurl({ type: purl.type, ...(purl.namespace === undefined ? {} : { namespace: purl.namespace }), name: purl.name });
187
+ }