| 228 | }; |
| 229 | |
| 230 | export class SemanticVersion { |
| 231 | constructor( |
| 232 | public major: number, |
| 233 | public minor: number, |
| 234 | public patch: number, |
| 235 | public preReleaseType?: string, |
| 236 | public preReleaseNumber?: number, |
| 237 | public build?: string, |
| 238 | ) { |
| 239 | if (major < 0 || minor < 0 || patch < 0) { |
| 240 | throw new Error('Version numbers must be positive'); |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | static parse(version: string): SemanticVersion { |
| 245 | const match = version.match(semanticVersionRegex); |
| 246 | if (!match) { |
| 247 | throw new Error(`Invalid semantic version: ${version}`); |
| 248 | } |
| 249 | |
| 250 | const [, major, minor, patch, preRelease, build] = match; |
| 251 | const [preReleaseType, preReleaseNumber] = preRelease?.split('.') ?? [undefined, undefined]; |
| 252 | |
| 253 | return new SemanticVersion( |
| 254 | Number(major), |
| 255 | Number(minor), |
| 256 | Number(patch), |
| 257 | preReleaseType, |
| 258 | preReleaseNumber !== undefined ? Number(preReleaseNumber) : 0, |
| 259 | build, |
| 260 | ); |
| 261 | } |
| 262 | |
| 263 | public toString(): string { |
| 264 | const preRelease = this.preReleaseType |
| 265 | ? `-${this.preReleaseType}${this.preReleaseNumber ?? 0}` |
| 266 | : ''; |
| 267 | const build = this.build ? `+${this.build}` : ''; |
| 268 | return `${this.major}.${this.minor}.${this.patch}${preRelease}${build}`; |
| 269 | } |
| 270 | |
| 271 | public compare(other: SemanticVersion): number { |
| 272 | // Compare major, minor, and patch versions |
| 273 | if (this.major !== other.major) return this.major - other.major; |
| 274 | if (this.minor !== other.minor) return this.minor - other.minor; |
| 275 | if (this.patch !== other.patch) return this.patch - other.patch; |
| 276 | |
| 277 | // Compare pre-release types and numbers |
| 278 | if (this.preReleaseType || other.preReleaseType) { |
| 279 | if (!this.preReleaseType) return 1; // No pre-release means higher precedence |
| 280 | if (!other.preReleaseType) return -1; |
| 281 | const typeComparison = this.preReleaseType.localeCompare(other.preReleaseType); |
| 282 | if (typeComparison !== 0) return typeComparison; |
| 283 | |
| 284 | // Compare pre-release numbers |
| 285 | const thisNumber = this.preReleaseNumber ?? 0; |
| 286 | const otherNumber = other.preReleaseNumber ?? 0; |
| 287 | if (thisNumber !== otherNumber) return thisNumber - otherNumber; |
nothing calls this directly
no outgoing calls
no test coverage detected