Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

semver.ts

235 lines7.1 KB

1interface ParsedSemver {
2 readonly major: number;
3 readonly minor: number;
4 readonly patch: number;
5 readonly prerelease: ReadonlyArray<string>;
6}
7​
8const SEMVER_NUMBER_SEGMENT = /^\d+$/;
9​
10export function normalizeSemverVersion(version: string): string {
11 const [withoutBuildMetadata = ""] = version.trim().split("+", 2);
12 const [main, prerelease] = withoutBuildMetadata.split("-", 2);
13 const segments: string[] = [];
14 for (const segment of (main ?? "").split(".")) {
15 const trimmed = segment.trim();
16 if (trimmed.length > 0) {
17 segments.push(trimmed);
18 }
19 }
20​
21 // Pad shorthand versions ("20" or "20.1") up to three segments so major-only
22 // and minor-only inputs parse and compare numerically. This matches
23 // satisfiesSemverRange, which already treats a missing minor/patch as 0. The
24 // length > 0 guard keeps empty/garbage input empty (parseSemver still
25 // rejects it), and inputs with more than three segments are left untouched.
26 while (segments.length > 0 && segments.length < 3) {
27 segments.push("0");
28 }
29​
30 return prerelease ? `${segments.join(".")}-${prerelease}` : segments.join(".");
32​
33export function parseSemver(value: string): ParsedSemver | null {
34 const normalized = normalizeSemverVersion(value).replace(/^v/, "");
35 const [main = "", prerelease] = normalized.split("-", 2);
36 const segments = main.split(".");
37 if (segments.length !== 3) {
38 return null;
39 }
40​
41 const [majorSegment, minorSegment, patchSegment] = segments;
42 if (majorSegment === undefined || minorSegment === undefined || patchSegment === undefined) {
43 return null;
44 }
45 if (
46 !SEMVER_NUMBER_SEGMENT.test(majorSegment) ||
47 !SEMVER_NUMBER_SEGMENT.test(minorSegment) ||
48 !SEMVER_NUMBER_SEGMENT.test(patchSegment)
49 ) {
50 return null;
51 }
52​
53 const major = Number.parseInt(majorSegment, 10);
54 const minor = Number.parseInt(minorSegment, 10);
55 const patch = Number.parseInt(patchSegment, 10);
56 if (![major, minor, patch].every(Number.isInteger)) {
57 return null;
58 }
59​
60 return {
61 major,
62 minor,
63 patch,
64 prerelease: parsePrereleaseSegments(prerelease),
65 };
67​
68function parsePrereleaseSegments(prerelease: string | undefined): ReadonlyArray<string> {
69 if (prerelease === undefined) {
70 return [];
71 }
72 const segments: string[] = [];
73 for (const segment of prerelease.split(".")) {
74 const trimmed = segment.trim();
75 if (trimmed.length > 0) {
76 segments.push(trimmed);
77 }
78 }
79 return segments;
81​
82function comparePrereleaseIdentifier(left: string, right: string): number {
83 const leftNumeric = SEMVER_NUMBER_SEGMENT.test(left);
84 const rightNumeric = SEMVER_NUMBER_SEGMENT.test(right);
85​
86 if (leftNumeric && rightNumeric) {
87 return Number.parseInt(left, 10) - Number.parseInt(right, 10);
88 }
89 if (leftNumeric) {
90 return -1;
91 }
92 if (rightNumeric) {
93 return 1;
94 }
95 return left.localeCompare(right);
97​
98export function compareSemverVersions(left: string, right: string): number {
99 const parsedLeft = parseSemver(left);
100 const parsedRight = parseSemver(right);
101 if (!parsedLeft || !parsedRight) {
102 return left.localeCompare(right);
103 }
104​
105 if (parsedLeft.major !== parsedRight.major) {
106 return parsedLeft.major - parsedRight.major;
107 }
108 if (parsedLeft.minor !== parsedRight.minor) {
109 return parsedLeft.minor - parsedRight.minor;
110 }
111 if (parsedLeft.patch !== parsedRight.patch) {
112 return parsedLeft.patch - parsedRight.patch;
113 }
114​
115 if (parsedLeft.prerelease.length === 0 && parsedRight.prerelease.length === 0) {
116 return 0;
117 }
118 if (parsedLeft.prerelease.length === 0) {
119 return 1;
120 }
121 if (parsedRight.prerelease.length === 0) {
122 return -1;
123 }
124​
125 const length = Math.max(parsedLeft.prerelease.length, parsedRight.prerelease.length);
126 for (let index = 0; index < length; index += 1) {
127 const leftIdentifier = parsedLeft.prerelease[index];
128 const rightIdentifier = parsedRight.prerelease[index];
129 if (leftIdentifier === undefined) {
130 return -1;
131 }
132 if (rightIdentifier === undefined) {
133 return 1;
134 }
135 const comparison = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);
136 if (comparison !== 0) {
137 return comparison;
138 }
139 }
140​
141 return 0;
143​
144/**
145 * Small semver range checker for CLI/runtime gates.
146 *
147 * Keep the function body valid plain JavaScript: SSH startup stringifies this
148 * function and runs it on remote Node versions before TypeScript support is known.
149 *
150 * @param rawVersion Version string, with or without a leading `v`.
151 * @param range Space-separated comparators, with `||` range groups.
152 * @returns Whether `rawVersion` satisfies the supported range syntax.
153 */
154export const satisfiesSemverRange: (rawVersion: string, range: string) => boolean =
155 function satisfiesSemverRange(rawVersion, range) {
156 const normalizedVersion = String(rawVersion).trim().replace(/^v/, "");
157 const versionMatch = normalizedVersion.match(
158 /^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-[0-9A-Za-z.-]+)?$/,
159 );
160 if (!versionMatch) {
161 return false;
162 }
163​
164 const version = {
165 major: Number(versionMatch[1]),
166 minor: Number(versionMatch[2] || 0),
167 patch: Number(versionMatch[3] || 0),
168 };
169​
170 return range.split("||").some((group) => {
171 const comparators = group.trim().split(/\s+/).filter(Boolean);
172 if (comparators.length === 0) {
173 return false;
174 }
175 return comparators.every((comparator) => {
176 const match = comparator.trim().match(/^(\^|>=|>|<=|<|=)?\s*v?(\d+(?:\.\d+){0,2})$/);
177 if (!match) {
178 return false;
179 }
180 const targetVersion = match[2];
181 if (targetVersion === undefined) {
182 return false;
183 }
184 const targetMatch = targetVersion.match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?$/);
185 if (!targetMatch) {
186 return false;
187 }
188 const target = {
189 major: Number(targetMatch[1]),
190 minor: Number(targetMatch[2] || 0),
191 patch: Number(targetMatch[3] || 0),
192 };
193 const compared =
194 version.major !== target.major
195 ? version.major > target.major
196 ? 1
197 : -1
198 : version.minor !== target.minor
199 ? version.minor > target.minor
200 ? 1
201 : -1
202 : version.patch !== target.patch
203 ? version.patch > target.patch
204 ? 1
205 : -1
206 : 0;
207 const operator = match[1] || "=";
208 switch (operator) {
209 case "^":
210 if (compared < 0) {
211 return false;
212 }
213 if (target.major > 0) {
214 return version.major === target.major;
215 }
216 if (target.minor > 0) {
217 return version.major === 0 && version.minor === target.minor;
218 }
219 return version.major === 0 && version.minor === 0 && version.patch === target.patch;
220 case ">=":
221 return compared >= 0;
222 case ">":
223 return compared > 0;
224 case "<=":
225 return compared <= 0;
226 case "<":
227 return compared < 0;
228 case "=":
229 return compared === 0;
230 default:
231 return false;
232 }
233 });
234 });
235 };