the editable site (validation-lab)

This commit is contained in:
kpgarrod committed 2026-11-21 08:03:55 +01:00
commit 3ac81d5a52
13454 files changed
+2227005

No files matched your search

+67
View File
@@ -0,0 +1,67 @@
'use strict'
// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
const SEMVER_SPEC_VERSION = '2.0.0'
const MAX_LENGTH = 256
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
/* istanbul ignore next */ 9007199254740991
// Max safe segment length for coercion.
const MAX_SAFE_COMPONENT_LENGTH = 16
// Max safe length for a build identifier. The max length minus 6 characters for
// the shortest version with a build 0.0.0+BUILD.
const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6
// ECMAScript whitespace and line terminators matched by \s.
const WHITESPACE_CHARACTERS = [
'\t',
'\n',
'\v',
'\f',
'\r',
' ',
'\u00a0',
'\u1680',
'\u2000',
'\u2001',
'\u2002',
'\u2003',
'\u2004',
'\u2005',
'\u2006',
'\u2007',
'\u2008',
'\u2009',
'\u200a',
'\u2028',
'\u2029',
'\u202f',
'\u205f',
'\u3000',
'\ufeff',
]
const RELEASE_TYPES = [
'major',
'premajor',
'minor',
'preminor',
'patch',
'prepatch',
'prerelease',
]
module.exports = {
MAX_LENGTH,
MAX_SAFE_COMPONENT_LENGTH,
MAX_SAFE_BUILD_LENGTH,
MAX_SAFE_INTEGER,
WHITESPACE_CHARACTERS,
RELEASE_TYPES,
SEMVER_SPEC_VERSION,
FLAG_INCLUDE_PRERELEASE: 0b001,
FLAG_LOOSE: 0b010,
}
+11
View File
@@ -0,0 +1,11 @@
'use strict'
const debug = (
typeof process === 'object' &&
process.env &&
process.env.NODE_DEBUG &&
/\bsemver\b/i.test(process.env.NODE_DEBUG)
) ? (...args) => console.error('SEMVER', ...args)
: () => {}
module.exports = debug
+29
View File
@@ -0,0 +1,29 @@
'use strict'
const numeric = /^[0-9]+$/
const compareIdentifiers = (a, b) => {
if (typeof a === 'number' && typeof b === 'number') {
return a === b ? 0 : a < b ? -1 : 1
}
const anum = numeric.test(a)
const bnum = numeric.test(b)
if (anum && bnum) {
a = +a
b = +b
}
return a === b ? 0
: (anum && !bnum) ? -1
: (bnum && !anum) ? 1
: a < b ? -1
: 1
}
const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
module.exports = {
compareIdentifiers,
rcompareIdentifiers,
}
+42
View File
@@ -0,0 +1,42 @@
'use strict'
class LRUCache {
constructor () {
this.max = 1000
this.map = new Map()
}
get (key) {
const value = this.map.get(key)
if (value === undefined) {
return undefined
} else {
// Remove the key from the map and add it to the end
this.map.delete(key)
this.map.set(key, value)
return value
}
}
delete (key) {
return this.map.delete(key)
}
set (key, value) {
const deleted = this.delete(key)
if (!deleted && value !== undefined) {
// If cache is full, delete the least recently used item
if (this.map.size >= this.max) {
const firstKey = this.map.keys().next().value
this.delete(firstKey)
}
this.map.set(key, value)
}
return this
}
}
module.exports = LRUCache
+17
View File
@@ -0,0 +1,17 @@
'use strict'
// parse out just the options we care about
const looseOption = Object.freeze({ loose: true })
const emptyOpts = Object.freeze({ })
const parseOptions = options => {
if (!options) {
return emptyOpts
}
if (typeof options !== 'object') {
return looseOption
}
return options
}
module.exports = parseOptions
+223
View File
@@ -0,0 +1,223 @@
'use strict'
const {
MAX_SAFE_COMPONENT_LENGTH,
MAX_SAFE_BUILD_LENGTH,
MAX_LENGTH,
} = require('./constants')
const debug = require('./debug')
exports = module.exports = {}
// The actual regexps go on exports.re
const re = exports.re = []
const safeRe = exports.safeRe = []
const src = exports.src = []
const safeSrc = exports.safeSrc = []
const t = exports.t = {}
let R = 0
const LETTERDASHNUMBER = '[a-zA-Z0-9-]'
// Replace some greedy regex tokens to prevent regex dos issues. These regex are
// used internally via the safeRe object since all inputs in this library get
// normalized first to trim and collapse all extra whitespace. The original
// regexes are exported for userland consumption and lower level usage. A
// future breaking change could export the safer regex only with a note that
// all input should have extra whitespace removed.
const safeRegexReplacements = [
['\\s', 1],
['\\d', MAX_LENGTH],
[LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
]
const makeSafeRegex = (value) => {
for (const [token, max] of safeRegexReplacements) {
value = value
.split(`${token}*`).join(`${token}{0,${max}}`)
.split(`${token}+`).join(`${token}{1,${max}}`)
}
return value
}
const createToken = (name, value, isGlobal) => {
const safe = makeSafeRegex(value)
const index = R++
debug(name, index, value)
t[name] = index
src[index] = value
safeSrc[index] = safe
re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)
}
// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.
// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.
createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
createToken('NUMERICIDENTIFIERLOOSE', '\\d+')
// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.
createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)
// ## Main Version
// Three dot-separated numeric identifiers.
createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
`(${src[t.NUMERICIDENTIFIER]})\\.` +
`(${src[t.NUMERICIDENTIFIER]})`)
createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
`(${src[t.NUMERICIDENTIFIERLOOSE]})`)
// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
// Non-numeric identifiers include numeric identifiers but can be longer.
// Therefore non-numeric identifiers must go first.
createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]
}|${src[t.NUMERICIDENTIFIER]})`)
createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]
}|${src[t.NUMERICIDENTIFIERLOOSE]})`)
// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.
createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.
createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)
// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.
createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.
// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups. The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.
createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
}${src[t.PRERELEASE]}?${
src[t.BUILD]}?`)
createToken('FULL', `^${src[t.FULLPLAIN]}$`)
// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
}${src[t.PRERELEASELOOSE]}?${
src[t.BUILD]}?`)
createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
createToken('GTLT', '((?:<|>)?=?)')
// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifier, meaning "any version"
// Only the first item is strictly required.
createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
`(?:${src[t.PRERELEASE]})?${
src[t.BUILD]}?` +
`)?)?`)
createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:${src[t.PRERELEASELOOSE]})?${
src[t.BUILD]}?` +
`)?)?`)
createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
// Coercion.
// Extract anything that could conceivably be a part of a valid semver
createToken('COERCEPLAIN', `${'(^|[^\\d])' +
'(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)
createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`)
createToken('COERCEFULL', src[t.COERCEPLAIN] +
`(?:${src[t.PRERELEASE]})?` +
`(?:${src[t.BUILD]})?` +
`(?:$|[^\\d])`)
createToken('COERCERTL', src[t.COERCE], true)
createToken('COERCERTLFULL', src[t.COERCEFULL], true)
// Tilde ranges.
// Meaning is "reasonably at or greater than"
createToken('LONETILDE', '(?:~>?)')
createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
exports.tildeTrimReplace = '$1~'
createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
// Caret ranges.
// Meaning is "at least and backwards compatible with"
createToken('LONECARET', '(?:\\^)')
createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
exports.caretTrimReplace = '$1^'
createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
// A simple gt/lt/eq thing, or just "" to indicate "any version"
createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
exports.comparatorTrimReplace = '$1$2$3'
// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
`\\s+-\\s+` +
`(${src[t.XRANGEPLAIN]})` +
`\\s*$`)
createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
`\\s+-\\s+` +
`(${src[t.XRANGEPLAINLOOSE]})` +
`\\s*$`)
// Star ranges basically just allow anything at all.
createToken('STAR', '(<|>)?=?\\s*\\*')
// >=0.0.0 is like a star
createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$')
createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$')
+438
View File
@@ -0,0 +1,438 @@
// @ts-check
'use strict'
// Reproduce safeRe[COMPARATORTRIM] replacement boundaries, not version
// validation. Each end-index finder returns an exclusive end, or its start
// on no match.
// Positions count from zero. An end of 3 means characters 0, 1, and 2 were read;
// range.slice(start, end) gives the matched text, not a converted number.
const {
MAX_LENGTH,
MAX_SAFE_BUILD_LENGTH,
WHITESPACE_CHARACTERS,
} = require('./constants')
/**
* Remembers the last two rows of digits so their characters need not be reread.
* Positions start at -1 until a row has been found.
*
* @typedef {object} DigitRunCache
* @property {number} start The first character of the most recently found row.
* @property {number} end The position after that row's last character.
* @property {number} previousStart The first character of the previous row.
* @property {number} previousEnd The position after the previous row.
*/
// One entry per UTF-16 code unit keeps membership checks constant-time.
const whitespace = new Uint8Array(0x10000)
for (const char of WHITESPACE_CHARACTERS) {
whitespace[char.charCodeAt(0)] = 1
}
/**
* Checks whether a character is whitespace, like a space, tab, or newline.
* Looking past the end of the string returns false.
*
* @param {string|undefined} char One character, or undefined past the string's end.
* @returns {boolean} Whether the character is whitespace.
* @example isWhitespace(' ') // true
* @example isWhitespace('1') // false
*/
const isWhitespace = char =>
char !== undefined && whitespace[char.charCodeAt(0)] === 1
/**
* Checks for v, =, or whitespace before the version number.
* These are historical version prefixes, not range operators:
* < and > are handled separately, as are tilde and caret ranges.
*
* @param {string|undefined} char One character to check.
* @returns {boolean} Whether the character can belong to a version prefix.
* @example isVersionPrefix('=') // true
* @example isVersionPrefix('>') // false
*/
const isVersionPrefix = char =>
char === 'v' ||
char === '=' ||
isWhitespace(char)
/**
* Checks whether a character is one of the digits 0 through 9.
*
* @param {string|undefined} char One character to check.
* @returns {boolean} Whether the character is an ASCII digit.
* @example isDigit('7') // true
* @example isDigit('.') // false
*/
const isDigit = char => char !== undefined && char >= '0' && char <= '9'
/**
* Checks whether a character is an English letter, uppercase or lowercase.
*
* @param {string|undefined} char One character to check.
* @returns {boolean} Whether the character is an ASCII letter.
* @example isLetter('b') // true
* @example isLetter('7') // false
*/
const isLetter = char =>
char !== undefined && (
(char >= 'a' && char <= 'z') ||
(char >= 'A' && char <= 'Z')
)
/**
* Checks for a letter, digit, or hyphen: the characters allowed inside
* prerelease and build names such as beta-1.
*
* @param {string|undefined} char One character to check.
* @returns {boolean} Whether the character can be part of an identifier.
* @example isIdentifierCharacter('-') // true
* @example isIdentifierCharacter('.') // false; dots separate identifiers
*/
const isIdentifierCharacter = char => isDigit(char) || isLetter(char) || char === '-'
/**
* Checks whether a version component can begin here: with a digit or
* a wildcard such as x, X, or *.
*
* @param {string|undefined} char One character to check.
* @returns {boolean} Whether a number or wildcard can start with this character.
* @example isVersionStart('x') // true
* @example isVersionStart('v') // false; v belongs to the prefix
*/
const isVersionStart = char =>
isDigit(char) ||
char === 'x' ||
char === 'X' ||
char === '*'
/**
* Finds the end of a row of digits, but returns no more than limit digits.
* Remembers the last two rows so looking at them again does not reread them.
*
* @param {string} range The text to read; it is not changed.
* @param {number} start The position of the first character to check.
* @param {number} limit The most digit characters the returned match can include.
* @param {DigitRunCache} digitRuns Shared cache of digit-run positions, updated in place.
* @returns {number} The position after the matched digits, or start if none match.
* @example findDigitsEndIndex('123abc', 0, 10, digitRuns) // 3, pointing at a
* @example findDigitsEndIndex('123abc', 0, 2, digitRuns) // 2, pointing at the unread 3
*/
const findDigitsEndIndex = (range, start, limit, digitRuns) => {
if (!isDigit(range[start])) {
return start
}
if (start >= digitRuns.start && start < digitRuns.end) {
return Math.min(start + limit, digitRuns.end)
}
if (start >= digitRuns.previousStart && start < digitRuns.previousEnd) {
return Math.min(start + limit, digitRuns.previousEnd)
}
let end = start + 1
while (isDigit(range[end])) {
end++
}
// A failed full version can rewind from its second run to its first.
digitRuns.previousStart = digitRuns.start
digitRuns.previousEnd = digitRuns.end
digitRuns.start = start
digitRuns.end = end
return Math.min(start + limit, end)
}
/**
* Reads a number using the old regex's length and leading-zero rules.
* Strict mode reads just the first zero in 012; loose mode can read all three.
*
* @param {string} range The text to read; it is not changed.
* @param {number} start The position where the number should begin.
* @param {boolean} loose Whether to allow leading zeros.
* @param {DigitRunCache} digitRuns Shared digit-run cache, updated as needed.
* @returns {number} The position after the matched digits, not their numeric value.
* @example findVersionNumberEndIndex('012', 0, false, digitRuns) // 1
* @example findVersionNumberEndIndex('012', 0, true, digitRuns) // 3
*/
const findVersionNumberEndIndex = (range, start, loose, digitRuns) => {
if (!loose && range[start] === '0') {
return start + 1
}
// Strict syntax allows an initial nonzero digit plus MAX_LENGTH digits.
return findDigitsEndIndex(range, start, loose ? MAX_LENGTH : MAX_LENGTH + 1, digitRuns)
}
/**
* Reads one piece of a prerelease name, such as beta or 1 in beta.1.
* Tries the letter-or-hyphen form first, then the number-only form.
*
* @param {string} range The text to read; it is not changed.
* @param {number} start The position where the identifier should begin.
* @param {boolean} loose Whether numeric identifiers may have leading zeros.
* @param {DigitRunCache} digitRuns Shared digit-run cache, updated as needed.
* @returns {number} The position after the identifier, or start if none matches.
* @example findPrereleaseIdentifierEndIndex('beta.1', 0, false, digitRuns) // 4, at the dot
* @example findPrereleaseIdentifierEndIndex('001beta', 0, false, digitRuns) // 7
*/
const findPrereleaseIdentifierEndIndex = (range, start, loose, digitRuns) => {
const digitsEnd = findDigitsEndIndex(range, start, MAX_LENGTH, digitRuns)
// The legacy regex tries a nonnumeric identifier before a numeric one.
if (isLetter(range[digitsEnd]) || range[digitsEnd] === '-') {
let end = digitsEnd + 1
const limit = end + MAX_SAFE_BUILD_LENGTH
while (end < limit && isIdentifierCharacter(range[end])) {
end++
}
return end
}
return findVersionNumberEndIndex(range, start, loose, digitRuns)
}
/**
* Reads a prerelease suffix such as -beta.1, one dot-separated piece at a time.
* Loose mode also allows the name without its opening hyphen.
*
* @param {string} range The text to read; it is not changed.
* @param {number} start The position where the suffix should begin, including -.
* @param {boolean} loose Whether the opening hyphen is optional and zeros allowed.
* @param {DigitRunCache} digitRuns Shared digit-run cache, updated as needed.
* @returns {number} The position after the matched suffix, or start if absent.
* @example findPrereleaseEndIndex('-beta.1+sha', 0, false, digitRuns) // 7, at the plus
* @example findPrereleaseEndIndex('beta', 0, false, digitRuns) // 0; no opening hyphen
*/
const findPrereleaseEndIndex = (range, start, loose, digitRuns) => {
const hyphen = range[start] === '-'
if (!loose && !hyphen) {
return start
}
const identifierStart = start + (hyphen ? 1 : 0)
let end = findPrereleaseIdentifierEndIndex(range, identifierStart, loose, digitRuns)
if (end === identifierStart) {
if (!loose || !hyphen) {
return start
}
// In loose syntax, a lone hyphen can itself be the identifier.
end = findPrereleaseIdentifierEndIndex(range, start, loose, digitRuns)
}
while (range[end] === '.') {
const next = findPrereleaseIdentifierEndIndex(range, end + 1, loose, digitRuns)
if (next === end + 1) {
break
}
end = next
}
return end
}
/**
* Reads one build-name piece, such as sha or 123 in +sha.123.
* Stops at a disallowed character or the old regex's length limit.
*
* @param {string} range The text to read; it is not changed.
* @param {number} start The position where the identifier should begin.
* @returns {number} The position after the identifier, or start if none matches.
* @example findBuildIdentifierEndIndex('sha.123', 0) // 3, at the dot
* @example findBuildIdentifierEndIndex('001', 0) // 3; leading zeros are allowed
*/
const findBuildIdentifierEndIndex = (range, start) => {
let end = start
while (end - start < MAX_SAFE_BUILD_LENGTH && isIdentifierCharacter(range[end])) {
end++
}
return end
}
/**
* Reads optional build metadata such as +sha.123.
* Leaves the position unchanged if there is no plus sign followed by a name.
*
* @param {string} range The text to read; it is not changed.
* @param {number} start The position where the opening + should be.
* @returns {number} The position after the matched metadata, or start if absent.
* @example findBuildEndIndex('+sha.123 <2', 0) // 8, at the space
* @example findBuildEndIndex('+', 0) // 0; a plus sign alone is not a match
*/
const findBuildEndIndex = (range, start) => {
if (range[start] !== '+') {
return start
}
let end = findBuildIdentifierEndIndex(range, start + 1)
if (end === start + 1) {
return start
}
while (range[end] === '.') {
const next = findBuildIdentifierEndIndex(range, end + 1)
if (next === end + 1) {
break
}
end = next
}
return end
}
/**
* Reads three numbers separated by dots, then any prerelease and build suffixes.
* Uses loose rules, so forms such as 01.02.03beta can match here.
*
* @param {string} range The text to read; it is not changed.
* @param {number} start The position of the first number, after any prefix.
* @param {DigitRunCache} digitRuns Shared digit-run cache, updated as needed.
* @returns {number} The position after the version match, or start if none matches.
* @example findLooseFullVersionEndIndex('1.2.3-beta+sha <2', 0, digitRuns) // 14
* @example findLooseFullVersionEndIndex('1.2', 0, digitRuns) // 0; needs three numbers
*/
const findLooseFullVersionEndIndex = (range, start, digitRuns) => {
let end = start
for (let component = 0; component < 3; component++) {
const next = findVersionNumberEndIndex(range, end, true, digitRuns)
if (next === end) {
return start
}
end = next
if (component < 2) {
if (range[end] !== '.') {
return start
}
end++
}
}
const prereleaseEnd = findPrereleaseEndIndex(range, end, true, digitRuns)
return findBuildEndIndex(range, prereleaseEnd)
}
/**
* Reads one component of a partial or wildcard version, such as 2 or x in 2.x.
* Numbers use strict leading-zero rules; wildcards take up one character.
*
* @param {string} range The text to read; it is not changed.
* @param {number} start The position where the component should begin.
* @param {DigitRunCache} digitRuns Shared digit-run cache, updated as needed.
* @returns {number} The position after the component, or start if none matches.
* @example findPartialVersionComponentEndIndex('2.x', 0, digitRuns) // 1, at the dot
* @example findPartialVersionComponentEndIndex('2.x', 2, digitRuns) // 3, after x
*/
const findPartialVersionComponentEndIndex = (range, start, digitRuns) => {
if (isDigit(range[start])) {
return findVersionNumberEndIndex(range, start, false, digitRuns)
}
return isVersionStart(range[start]) ? start + 1 : start
}
/**
* Reads up to three components, allowing forms such as 1, 1.2, or 1.x.
* After the third component, also reads any strict prerelease and build suffixes.
*
* @param {string} range The text to read; it is not changed.
* @param {number} start The position of a number or wildcard, after any prefix.
* @param {DigitRunCache} digitRuns Shared digit-run cache, updated as needed.
* @returns {number} The position after the matched version text.
* @example findPartialVersionEndIndex('1.x <2', 0, digitRuns) // 3, at the space
* @example findPartialVersionEndIndex('1.', 0, digitRuns) // 1; the trailing dot is unread
*/
const findPartialVersionEndIndex = (range, start, digitRuns) => {
let end = findPartialVersionComponentEndIndex(range, start, digitRuns)
for (let component = 0; component < 2; component++) {
if (range[end] !== '.') {
return end
}
const next = findPartialVersionComponentEndIndex(range, end + 1, digitRuns)
if (next === end + 1) {
return end
}
end = next
}
const prereleaseEnd = findPrereleaseEndIndex(range, end, false, digitRuns)
return findBuildEndIndex(range, prereleaseEnd)
}
/**
* Finds where a version match ends, without deciding whether the range is valid.
* Tries a loose full version first, then a partial or wildcard version, just
* like the old regex's LOOSEPLAIN and XRANGEPLAIN alternatives.
*
* @param {string} range The text to read; it is not changed.
* @param {number} start The position of a number or wildcard, after any prefix.
* @param {DigitRunCache} digitRuns Shared digit-run cache, updated as needed.
* @returns {number} The position where scanning the next candidate can resume.
* @example findVersionEndIndex('1.2.3 <2', 0, digitRuns) // 5, at the space
* @example findVersionEndIndex('1.x <2', 0, digitRuns) // 3, at the space
*/
const findVersionEndIndex = (range, start, digitRuns) => {
const fullVersionEnd = findLooseFullVersionEndIndex(range, start, digitRuns)
return fullVersionEnd !== start
? fullVersionEnd
: findPartialVersionEndIndex(range, start, digitRuns)
}
/**
* Finds the one whitespace character the old replacement would remove.
* Keeps leading whitespace, skips an optional operator, and checks immediately
* after it. Returns -1 if there is nothing to remove.
*
* @param {string} range The text containing a candidate already found by the caller.
* @param {number} matchStart The candidate's position, including leading whitespace.
* @returns {number} The position of the removable whitespace, or -1 if absent.
* @example findRemovableWhitespaceIndex(' > 1', 0) // 2; keep the space at position 0
* @example findRemovableWhitespaceIndex('>1', 0) // -1
*/
const findRemovableWhitespaceIndex = (range, matchStart) => {
let position = matchStart
if (isWhitespace(range[position])) {
position++
}
if (range[position] === '<' || range[position] === '>') {
position++
}
if (range[position] === '=') {
position++
}
return isWhitespace(range[position]) ? position : -1
}
/**
* Joins an operator to its version, turning > 1.2.3 into >1.2.3.
* Copies everything else according to the old regex's matching rules.
* Moves forward through prefixes and whole versions to avoid repeatedly
* searching the same characters on long inputs.
*
* @param {string} range The range text to process; the original string is unchanged.
* @returns {string} The range with matched operator whitespace removed.
* @example trimComparatorWhitespace('> 1.2.3 < 2') // '>1.2.3 <2'
* @example trimComparatorWhitespace('> invalid') // '> invalid'
*/
const trimComparatorWhitespace = range => {
let result = ''
let copyFrom = 0
let cursor = 0
const digitRuns = { start: -1, end: -1, previousStart: -1, previousEnd: -1 }
while (cursor < range.length) {
const matchStart = cursor
if (range[cursor] === '<' || range[cursor] === '>') {
cursor++
} else if (!isVersionPrefix(range[cursor]) && !isVersionStart(range[cursor])) {
cursor++
continue
}
// Consume a v/=/whitespace run once, even when no version follows it.
while (cursor < range.length && isVersionPrefix(range[cursor])) {
cursor++
}
if (!isVersionStart(range[cursor])) {
continue
}
const whitespacePosition = findRemovableWhitespaceIndex(range, matchStart)
if (whitespacePosition !== -1) {
result += range.slice(copyFrom, whitespacePosition)
copyFrom = whitespacePosition + 1
}
// Skip the entire match, so a prerelease's trailing v cannot be
// reconsidered as the prefix of another version.
cursor = findVersionEndIndex(range, cursor, digitRuns)
}
return result + range.slice(copyFrom)
}
module.exports = trimComparatorWhitespace