How to use semver

Comprehensive semver code examples:

How to use semver.patch:

14
15
16
17
18
19
20
21
22
23
 * `{ firefox: { version: '9.6.0.beta1' }, chrome: { version: '9.6.0.1', version_name: '9.6.0-beta.1' } }`.
 */
function getBrowserVersionMap(platforms, version) {
  const major = semver.major(version);
  const minor = semver.minor(version);
  const patch = semver.patch(version);
  const prerelease = semver.prerelease(version);
  let buildType, buildVersionSummary, buildVersion;
  if (prerelease) {
    [buildType, buildVersionSummary] = prerelease;

How to use semver.prototype:

39
40
41
42
43
44
45
46
47
48
compare: function(other) {
        other = new SemVish(other);
        return this.compareMain(other) || this.comparePre(other);
},
compareMain: function(other) {
        return SemVer.prototype.compareMain.call(this, new SemVish(other));
},
comparePre: function(other) {
        other = new SemVish(other);
        if (!this.prerelease.length || !other.prerelease.length) {

How to use semver.neq:

53
54
55
56
57
58
59
60
61

depKeys.map(depKey => {
  const curVersion = get(tapPackage, [depKey, repoName])
  if(!curVersion) return

  semver.neq(
    semver.coerce(cleanVersion(curVersion)),
    semver.coerce(cleanVersion(repoVersion))
  ) && (versionsDiff[repoName] = { current: curVersion, repo: repoVersion } )

How to use semver.gtr:

92
93
94
95
96
97
98
99
100
101
if (dep && !semver.satisfies(dep.version, peerVersionRange)) {
  track.count('peer_dep_version_mismatch', {
    compile_package: packageName,
  });

  const peerIsBehind = semver.gtr(dep.version, peerVersionRange);

  const errorMessage = chalk`{bold ${packageName}} expected to find {bold ${peerName}} {yellow ${peerVersionRange}} but found {yellow ${dep.version}}.`;

  const peerBehindMessage = chalk`The best way to fix this is for {bold ${packageName}} to update its peer dependency on {bold ${peerName}}.`;

How to use semver.SemVer:

32
33
34
35
36
37
38
39
40
41
    }
    return undefined;
}
exports.getTypescriptVersionRequirement = getTypescriptVersionRequirement;
function getNormalizedTypescriptVersion() {
    var tsVersion = new semver.SemVer(ts.version);
    // remove prerelease suffix when matching to allow testing with nightly builds
    return tsVersion.major + "." + tsVersion.minor + "." + tsVersion.patch;
}
exports.getNormalizedTypescriptVersion = getNormalizedTypescriptVersion;

How to use semver.minor:

207
208
209
210
211
212
213
214
215
216
 * @returns {int}
 */
function versionToReleaseWeight(version) {
  return semver.major(version) > 0
    ? RELEASE_WEIGHT.MAJOR
    : semver.minor(version) > 0
    ? RELEASE_WEIGHT.MINOR
    : RELEASE_WEIGHT.PATCH
}

How to use semver.subset:

67
68
69
70
71
72
73
74
75

instrumentations
  .filter(instrumentation => instrumentation.name === moduleName)
  .forEach(instrumentation => {
    instrumentation.versions
      .filter(version => !process.env.RANGE || semver.subset(version, process.env.RANGE))
      .forEach(version => {
        const min = semver.coerce(version).version
        const max = require(`../../../../versions/${moduleName}@${version}`).version()

How to use semver.ltr:

52
53
54
55
56
57
58
59
60
61
        return null;
}

// Flag generator to indecate if the generator version is fully supported or not.
// https://github.com/yeoman/yeoman-app/issues/16#issuecomment-121054821
generatorMeta.isCompatible = semver.ltr('0.17.6', generatorVersion);

// Indicator to verify official generators
generatorMeta.officialGenerator = false;
if (generatorMeta.repository && generatorMeta.repository.url) {

How to use semver.cmp:

33
34
35
36
37
38
39
40
41
42

function getNewComponentPath(customPath) {
    let newComponentPath = `${cwd}/markup/${componentsFolderName}/`;

    // Path to new component. Includes component name
    if (customPath && semver.cmp(currentTarsVersion, '>=', '1.8.0')) {
        newComponentPath += `${customPath}/${newComponentName}`;
    } else {
        newComponentPath += newComponentName;
    }

How to use semver.outside:

199
200
201
202
203
204
205
206
207
208
  }
  continue;
}
let versionRange = info.engines.arangodb;

if (!versionRange || semver.outside(serverVersion, versionRange, '<')) {
  // Explicitly backwards-incompatible with the server version: ignore
  continue;
}
if (!matchEngine || semver.satisfies(serverVersion, versionRange)) {

How to use semver.diff:

325
326
327
328
329
330
331
332
333
334
        ? 'next'
        : 'latest'
    : 'latest';
let version = info.npmPackageJson['dist-tags'][tag];
let target = info.npmPackageJson.versions[version];
const versionDiff = semver.diff(info.installed.version, version);
if (versionDiff !== 'patch' &&
    versionDiff !== 'minor' &&
    /^@(?:angular|nguniversal)\//.test(name)) {
    const installedMajorVersion = (_a = semver.parse(info.installed.version)) === null || _a === void 0 ? void 0 : _a.major;

How to use semver.minSatisfying:

56
57
58
59
60
61
62
63
64
65
66
67


/*
  Match the current tag with the most appropriate release notes.
*/
const versionsInReleaseNotes = _.map(releaseNotes, 'version');
const bestReleaseNotesForCurrentVersion = semver.minSatisfying(versionsInReleaseNotes, ">=" + currentVersion);
const currentReleaseNotes = _.find(releaseNotes, { version: bestReleaseNotesForCurrentVersion });


if (!currentReleaseNotes) {
    console.error('Could not find a release section satisfying %s in %s — did you forget to rename the "main" section to %s?', currentVersion, changelogPath, currentVersion.split("-")[0]);

How to use semver.eq:

41
42
43
44
45
46
47
48
49
50
 * @param {String} v1 - The first version to compare
 * @param {String} v2 - The second version to compare
 * @returns {Boolean} True if the versions are equal
 */
exports.eq = function eq(v1, v2) {
        return semver.eq(format(v1, 3, 3), format(v2, 3, 3));
};

/**
 * Converts two versions into 3 segment format, then checks if the first version is less than the

How to use semver.rcompare:

67
68
69
70
71
72
73
74
75
76
    !semver.prerelease(release.version) &&
    semver.satisfies(release.node, nodeVersionComparator)
);

// Sort the filtered releases by version number in descending order
filteredReleases.sort((a, b) => semver.rcompare(a.version, b.version));

const latest = filteredReleases[0].version;

console.log(

How to use semver.simplifyRange:

196
197
198
199
200
201
202
203
204
205
        : vr.join(' - '))
    }
  }
  const metavuln = ranges.join(' || ').trim()
  this.range = !metavuln ? '<0.0.0-0'
    : semver.simplifyRange(this.versions, metavuln, semverOpt)
}

// returns true if marked as vulnerable, false if ok
// spec is a dependency specifier, for metavuln cases

How to use semver.default:

104
105
106
107
108
109
110
111
112
113
// Server-side validation may be running a different SDK version than the pack maker
// is using, so some breaking changes to metadata validation can be set up to only
// take effect before or after an SDK version bump.
if (sdkVersion) {
    for (const { versionRange, schemaExtend } of packMetadataSchemaBySdkVersion) {
        if (warningMode || semver_1.default.satisfies(sdkVersion, versionRange)) {
            combinedSchema = schemaExtend(combinedSchema);
        }
    }
}

How to use semver.lte:

30
31
32
33
34
35
36
37
38
39

const lernaVersion = semver.clean(lernaConfig.version);

// Filter out versions that are greater than the lerna version
const versionInfo = versionData.filter(({ label }) =>
  semver.lte(label, lernaVersion),
);

versionInfo.sort(function(a, b) {
  return semver.rcompare(a.label, b.label);

How to use semver.intersects:

261
262
263
264
265
266
267
268
269
  return true
}

const bd = mani.bundleDependencies
const bundled = bd && bd.includes(this[_source].name)
// XXX if bundled, then semver.intersects() means vulnerable
// else, pick a manifest and see if it can't be avoided
// try to pick a version of the dep that isn't vulnerable
const avoid = this[_source].range

How to use semver.minVersion:

80
81
82
83
84
85
86
87
88
89
  return latest;
}

async function main() {
  const nodeVersionComparator = `${
    semver.minVersion(require('../package.json').engines.node).major
  }.x`;

  const latestElectronVersion =
    await getLatestElectronVersionMatchingNodeVersion(nodeVersionComparator);

How to use semver.validRange:

285
286
287
288
289
290
291
292
293
294
// try tag first
let realPkgVersion = distTags[spec];

if (!realPkgVersion) {
  const version = semver.valid(spec);
  const range = semver.validRange(spec, true);
  if (semver.satisfies(distTags.latest, spec)) {
    realPkgVersion = distTags.latest;
  } else if (version) {
    // use the valid version

How to use semver.Range:

162
163
164
165
166
167
168
169
170
171
if (r || !maybe) {
        return r;
}

// need to determine if the version is greater than any range
const range = new semver.Range(str);
for (let i = 0; i < range.set.length; i++) {
        const set = range.set[i];
        for (let j = set.length - 1; j >= 0; j--) {
                if (set[j].semver instanceof semver.SemVer) {

How to use semver.maxSatisfying:

637
638
639
640
641
642
643
644
645
646
    let version = manifest.info.version;
    version2release[version] = tag;
    return version;
  })
  .filter(version => Boolean(version));
let highestCompatibleVersion = semver.maxSatisfying(
  versionList,
  lib_range,
  { loose: true }
);

How to use semver.major:

362
363
364
365
366
367
368
369
370
371
).raw;
let fileVersion =
  lockfileContent && lockfileContent.version
    ? semver.coerce(lockfileContent.version, true).raw
    : "1.0.0";
if (semver.major(schemaVersion) > semver.major(fileVersion)) {
  if (this.argv.force) {
    let config = {
      verbose: this.argv.verbose,
      quiet: this.argv.quiet,

How to use semver.compare:

40
41
42
43
44
45
46
47
48
49
  }
}

function rcmp(a, b) {
  return icmp(a.semver, b.semver) ||
    semver.compare(a.semver, b.semver) ||
    cmp(a.operator, b.operator);
}

function min(a, b) {

How to use semver.sort:

163
164
165
166
167
168
169
170
171
172
// calling semver.simplifyRange with a massive list of versions, and those
// versions all concatenated with `||` is a geometric CPU explosion!
// we can try to be a *little* smarter up front by doing x-y for all
// contiguous version sets in the list
const ranges = []
this.versions = semver.sort(this.versions, semverOpt)
this.vulnerableVersions = semver.sort(this.vulnerableVersions, semverOpt)
for (let v = 0, vulnVer = 0; v < this.versions.length; v++) {
  // figure out the vulnerable subrange
  const vr = [this.versions[v]]

How to use semver.clean:

26
27
28
29
30
31
32
33
34
35
}

async function writeBoltVersionUrlsToJson(versionData) {
  const config = await getConfig();

  const lernaVersion = semver.clean(lernaConfig.version);

  // Filter out versions that are greater than the lerna version
  const versionInfo = versionData.filter(({ label }) =>
    semver.lte(label, lernaVersion),

How to use semver.prerelease:

18
19
20
21
22
23
24
25
26
27
// Include prelease versions, like v1.0.0-rc1 or v1.0.1-dev
if (versionConstraint == 'next') {
  version = releaseVersions[0]
} else if (versionConstraint == 'latest') {
  version = releaseVersions.filter(version => {
    const prereleaseComponents = semver.prerelease(version);
    return prereleaseComponents == null || prereleaseComponents.length == 0
  })[0];
} else if (validVersionConstraint) {
  version = matchVersion(releaseVersions, validVersionConstraint, false);

How to use semver.inc:

146
147
148
149
150
151
152
153
154
155

/**
 * Get the next version number, given the current level.
 */
async nextVersion() {
  return semver.inc(await this.lastVersion(), this.level());
}

/**
 * Get the formatted list of snippets as a string

How to use semver.valid:

77
78
79
80
81
82
83
84
85
86
    nargs: 1,
    describe: "Install a library/the given library from a local path"
  },

  "qx-version": {
    check: argv => semver.valid(argv.qxVersion),
    describe:
      "A semver string. If given, the maximum qooxdoo version for which to install a package"
  }
}