@sous-io/sous 0.2.30 → 0.2.31

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.
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Which version of sous an update moves an install to.
3
+ *
4
+ * Everything here is pure: it reads the registry's answer (the abbreviated
5
+ * package document) and the version an install holds, and decides. Nothing is
6
+ * fetched or installed, so a dry run and a real run choose exactly alike.
7
+ */
8
+
9
+ import semver from "semver";
10
+ import { z } from "zod";
11
+ import { ConfigError } from "../errors.js";
12
+
13
+ /** What the registry publishes for the package, reduced to what a choice needs. */
14
+ export type RegistryMetadata = {
15
+ /** The package name the registry answered for. */
16
+ name: string;
17
+ /** Every published version that is valid semver, newest first. */
18
+ versions: string[];
19
+ /** Each dist-tag (`latest`, `next`) and the version it points at. */
20
+ distTags: Record<string, string>;
21
+ };
22
+
23
+ /**
24
+ * What the person asked for.
25
+ *
26
+ * - `default`: the newest version in the installed major.
27
+ * - `major`: the newest version, whatever its major.
28
+ * - `spec`: an exact version, a dist-tag name, or a semver range.
29
+ */
30
+ export type VersionRequest =
31
+ | { kind: "default" }
32
+ | { kind: "major" }
33
+ | { kind: "spec"; spec: string };
34
+
35
+ /** How the chosen version relates to the installed one. */
36
+ export type VersionDirection = "upgrade" | "downgrade" | "current";
37
+
38
+ /** The version an install moves to, and how the choice was read. */
39
+ export type VersionChoice = {
40
+ /** The version to install; equal to the installed version when `direction` is `current`. */
41
+ target: string;
42
+ direction: VersionDirection;
43
+ /** Whether prerelease versions counted as candidates, after the default was applied. */
44
+ prerelease: boolean;
45
+ /**
46
+ * How a `spec` request was read: an exact version, a dist-tag or a range.
47
+ * Undefined for the other requests.
48
+ */
49
+ specKind?: "version" | "dist-tag" | "range";
50
+ };
51
+
52
+ /** Input to `chooseVersion`. */
53
+ export type ChooseVersionInput = {
54
+ /** The version the install holds now. */
55
+ current: string;
56
+ /** Every published version (any order; invalid entries are ignored). */
57
+ versions: readonly string[];
58
+ /** The registry's dist-tags. */
59
+ distTags: Readonly<Record<string, string>>;
60
+ request: VersionRequest;
61
+ /**
62
+ * Whether prerelease versions count as candidates. Undefined means "on when
63
+ * the installed version is itself a prerelease".
64
+ */
65
+ prerelease?: boolean;
66
+ };
67
+
68
+ /** How many of the newest versions an error lists. */
69
+ const NEWEST_LISTED = 5;
70
+
71
+ /**
72
+ * The abbreviated package document, as far as sous reads it. Every other field
73
+ * the registry sends is kept and ignored, so a registry that adds one breaks
74
+ * nothing.
75
+ */
76
+ const abbreviatedDocumentSchema = z.looseObject({
77
+ name: z.string(),
78
+ "dist-tags": z.record(z.string(), z.string()).default({}),
79
+ versions: z.record(z.string(), z.unknown()),
80
+ });
81
+
82
+ /**
83
+ * Reads the registry's abbreviated package document (the answer to a request
84
+ * sent with `Accept: application/vnd.npm.install-v1+json`).
85
+ *
86
+ * Keys of `versions` that are not valid semver are dropped, and so is a
87
+ * dist-tag that points at one. A body that is not JSON, or lacks `name` or
88
+ * `versions`, is a ConfigError naming `source`.
89
+ *
90
+ * @param text - The response body.
91
+ * @param source - Where the body came from (the URL), named in errors.
92
+ */
93
+ export function parseRegistryMetadata(text: string, source: string): RegistryMetadata {
94
+ let raw: unknown;
95
+ try {
96
+ raw = JSON.parse(text);
97
+ } catch (error) {
98
+ throw new ConfigError(
99
+ `The registry's answer from ${source} is not JSON.\n ${(error as Error).message}`
100
+ );
101
+ }
102
+ const parsed = abbreviatedDocumentSchema.safeParse(raw);
103
+ if (!parsed.success) {
104
+ const problems = parsed.error.issues.map(
105
+ (issue) => ` ${issue.path.join(".") || "(top level)"}: ${issue.message}`
106
+ );
107
+ throw new ConfigError(
108
+ [`The registry's answer from ${source} is not a package document.`, ...problems].join("\n")
109
+ );
110
+ }
111
+
112
+ const versions = Object.keys(parsed.data.versions)
113
+ .filter((version) => semver.valid(version) === version)
114
+ .sort(semver.rcompare);
115
+ const distTags: Record<string, string> = {};
116
+ for (const [tag, version] of Object.entries(parsed.data["dist-tags"])) {
117
+ if (semver.valid(version) === version) distTags[tag] = version;
118
+ }
119
+ return { name: parsed.data.name, versions, distTags };
120
+ }
121
+
122
+ /**
123
+ * The range the default request looks in: at least the installed version and
124
+ * below the next major. For a 0.x install that is `<1.0.0`, deliberately NOT
125
+ * caret semantics (which would stop at the next minor): the default is "the
126
+ * newest published version in the current major" (sous-io/sous#135), and a
127
+ * 0.x install's major is 0.
128
+ *
129
+ * The upper bound is written `-0` so a prerelease of the next major
130
+ * (`1.0.0-rc.1`, which sorts below `1.0.0`) is outside it too.
131
+ *
132
+ * defaultRange("0.2.30") -> ">=0.2.30 <1.0.0-0"
133
+ */
134
+ export function defaultRange(current: string): string {
135
+ return `>=${current} <${semver.major(current) + 1}.0.0-0`;
136
+ }
137
+
138
+ /**
139
+ * Chooses the version an install moves to.
140
+ *
141
+ * - `default`: the newest candidate in `defaultRange(current)`; nothing newer
142
+ * means `current`. Never a downgrade.
143
+ * - `major`: the newest candidate overall; when that is older than the
144
+ * installed version, `current`. Never a downgrade.
145
+ * - `spec`: an exact version (a leading `v` is accepted) that must be
146
+ * published, a dist-tag's version, or the newest candidate a range admits.
147
+ * A spec may downgrade, and `direction` then says so.
148
+ *
149
+ * A candidate is a published version that is not a prerelease, or any
150
+ * published version when prereleases are on. An exact version and a dist-tag
151
+ * are taken as named, whatever the prerelease setting.
152
+ *
153
+ * @throws ConfigError when `current` is not a version, or a spec matches
154
+ * nothing; the message lists the dist-tags and the newest versions.
155
+ */
156
+ export function chooseVersion(input: ChooseVersionInput): VersionChoice {
157
+ const current = semver.valid(input.current);
158
+ if (current === null) {
159
+ throw new ConfigError(
160
+ `The installed version "${input.current}" is not a version sous can compare with the published ones.`
161
+ );
162
+ }
163
+ const prerelease = input.prerelease ?? semver.prerelease(current) !== null;
164
+ const published = input.versions.filter((version) => semver.valid(version) === version);
165
+ const candidates = prerelease
166
+ ? published
167
+ : published.filter((version) => semver.prerelease(version) === null);
168
+ const range = { includePrerelease: true };
169
+
170
+ const settle = (target: string | null, specKind?: VersionChoice["specKind"]): VersionChoice => {
171
+ const choice: VersionChoice = {
172
+ target: target ?? current,
173
+ direction: directionOf(target ?? current, current),
174
+ prerelease,
175
+ };
176
+ if (specKind !== undefined) choice.specKind = specKind;
177
+ return choice;
178
+ };
179
+ const noDowngrade = (target: string | null): string | null =>
180
+ target !== null && semver.gt(target, current) ? target : null;
181
+
182
+ const { request } = input;
183
+ if (request.kind === "default") {
184
+ return settle(noDowngrade(semver.maxSatisfying(candidates, defaultRange(current), range)));
185
+ }
186
+ if (request.kind === "major") {
187
+ return settle(noDowngrade(semver.maxSatisfying(candidates, "*", range)));
188
+ }
189
+
190
+ const spec = request.spec.trim();
191
+ const exact = semver.valid(spec);
192
+ if (exact !== null) {
193
+ if (!published.includes(exact)) throw noMatch(spec, "is not a published version", input);
194
+ return settle(exact, "version");
195
+ }
196
+ const tagged = input.distTags[spec];
197
+ if (tagged !== undefined) return settle(tagged, "dist-tag");
198
+ if (semver.validRange(spec) !== null) {
199
+ const newest = semver.maxSatisfying(candidates, spec, range);
200
+ if (newest === null) {
201
+ throw noMatch(
202
+ spec,
203
+ prerelease
204
+ ? "matches no published version"
205
+ : "matches no published version that is not a prerelease",
206
+ input
207
+ );
208
+ }
209
+ return settle(newest, "range");
210
+ }
211
+ throw noMatch(spec, "is not a version, a range or a dist-tag", input);
212
+ }
213
+
214
+ /** How `target` relates to `current`. */
215
+ function directionOf(target: string, current: string): VersionDirection {
216
+ const order = semver.compare(target, current);
217
+ if (order > 0) return "upgrade";
218
+ if (order < 0) return "downgrade";
219
+ return "current";
220
+ }
221
+
222
+ /**
223
+ * The error for a spec that names nothing: what was asked, why it matched
224
+ * nothing, and what the registry does publish.
225
+ */
226
+ function noMatch(spec: string, why: string, input: ChooseVersionInput): ConfigError {
227
+ const lines = [`The requested version "${spec}" ${why}.`];
228
+ const tags = Object.entries(input.distTags).sort(([a], [b]) => a.localeCompare(b));
229
+ if (tags.length > 0) {
230
+ lines.push(" The dist-tags point at:");
231
+ for (const [tag, version] of tags) lines.push(` ${tag}: ${version}`);
232
+ }
233
+ const newest = input.versions
234
+ .filter((version) => semver.valid(version) === version)
235
+ .sort(semver.rcompare)
236
+ .slice(0, NEWEST_LISTED);
237
+ if (newest.length > 0) {
238
+ lines.push(` The newest published versions are ${newest.join(", ")}.`);
239
+ } else {
240
+ lines.push(" The registry lists no published versions.");
241
+ }
242
+ return new ConfigError(lines.join("\n"));
243
+ }