semver.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
  7. /** @typedef {(string|number|undefined|[])[]} SemVerRange */
  8. /**
  9. * @param {string} str version string
  10. * @returns {(string|number|undefined|[])[]} parsed version
  11. */
  12. const parseVersion = str => {
  13. var splitAndConvert = function (str) {
  14. return str.split(".").map(function (item) {
  15. // eslint-disable-next-line eqeqeq
  16. return +item == item ? +item : item;
  17. });
  18. };
  19. var match = /^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str);
  20. /** @type {(string|number|undefined|[])[]} */
  21. var ver = match[1] ? splitAndConvert(match[1]) : [];
  22. if (match[2]) {
  23. ver.length++;
  24. ver.push.apply(ver, splitAndConvert(match[2]));
  25. }
  26. if (match[3]) {
  27. ver.push([]);
  28. ver.push.apply(ver, splitAndConvert(match[3]));
  29. }
  30. return ver;
  31. };
  32. exports.parseVersion = parseVersion;
  33. /* eslint-disable eqeqeq */
  34. /**
  35. * @param {string} a version
  36. * @param {string} b version
  37. * @returns {boolean} true, iff a < b
  38. */
  39. const versionLt = (a, b) => {
  40. // @ts-expect-error
  41. a = parseVersion(a);
  42. // @ts-expect-error
  43. b = parseVersion(b);
  44. var i = 0;
  45. for (;;) {
  46. // a b EOA object undefined number string
  47. // EOA a == b a < b b < a a < b a < b
  48. // object b < a (0) b < a a < b a < b
  49. // undefined a < b a < b (0) a < b a < b
  50. // number b < a b < a b < a (1) a < b
  51. // string b < a b < a b < a b < a (1)
  52. // EOA end of array
  53. // (0) continue on
  54. // (1) compare them via "<"
  55. // Handles first row in table
  56. if (i >= a.length) return i < b.length && (typeof b[i])[0] != "u";
  57. var aValue = a[i];
  58. var aType = (typeof aValue)[0];
  59. // Handles first column in table
  60. if (i >= b.length) return aType == "u";
  61. var bValue = b[i];
  62. var bType = (typeof bValue)[0];
  63. if (aType == bType) {
  64. if (aType != "o" && aType != "u" && aValue != bValue) {
  65. return aValue < bValue;
  66. }
  67. i++;
  68. } else {
  69. // Handles remaining cases
  70. if (aType == "o" && bType == "n") return true;
  71. return bType == "s" || aType == "u";
  72. }
  73. }
  74. };
  75. /* eslint-enable eqeqeq */
  76. exports.versionLt = versionLt;
  77. /**
  78. * @param {string} str range string
  79. * @returns {SemVerRange} parsed range
  80. */
  81. exports.parseRange = str => {
  82. const splitAndConvert = str => {
  83. return str
  84. .split(".")
  85. .map(item => (item !== "NaN" && `${+item}` === item ? +item : item));
  86. };
  87. // see https://docs.npmjs.com/misc/semver#range-grammar for grammar
  88. const parsePartial = str => {
  89. const match = /^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str);
  90. /** @type {(string|number|undefined|[])[]} */
  91. const ver = match[1] ? [0, ...splitAndConvert(match[1])] : [0];
  92. if (match[2]) {
  93. ver.length++;
  94. ver.push.apply(ver, splitAndConvert(match[2]));
  95. }
  96. // remove trailing any matchers
  97. let last = ver[ver.length - 1];
  98. while (
  99. ver.length &&
  100. (last === undefined || /^[*xX]$/.test(/** @type {string} */ (last)))
  101. ) {
  102. ver.pop();
  103. last = ver[ver.length - 1];
  104. }
  105. return ver;
  106. };
  107. const toFixed = range => {
  108. if (range.length === 1) {
  109. // Special case for "*" is "x.x.x" instead of "="
  110. return [0];
  111. } else if (range.length === 2) {
  112. // Special case for "1" is "1.x.x" instead of "=1"
  113. return [1, ...range.slice(1)];
  114. } else if (range.length === 3) {
  115. // Special case for "1.2" is "1.2.x" instead of "=1.2"
  116. return [2, ...range.slice(1)];
  117. } else {
  118. return [range.length, ...range.slice(1)];
  119. }
  120. };
  121. const negate = range => {
  122. return [-range[0] - 1, ...range.slice(1)];
  123. };
  124. const parseSimple = str => {
  125. // simple ::= primitive | partial | tilde | caret
  126. // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' | '!' ) ( ' ' ) * partial
  127. // tilde ::= '~' ( ' ' ) * partial
  128. // caret ::= '^' ( ' ' ) * partial
  129. const match = /^(\^|~|<=|<|>=|>|=|v|!)/.exec(str);
  130. const start = match ? match[0] : "";
  131. const remainder = parsePartial(
  132. start.length ? str.slice(start.length).trim() : str.trim()
  133. );
  134. switch (start) {
  135. case "^":
  136. if (remainder.length > 1 && remainder[1] === 0) {
  137. if (remainder.length > 2 && remainder[2] === 0) {
  138. return [3, ...remainder.slice(1)];
  139. }
  140. return [2, ...remainder.slice(1)];
  141. }
  142. return [1, ...remainder.slice(1)];
  143. case "~":
  144. if (remainder.length === 2 && remainder[0] === 0) {
  145. return [1, ...remainder.slice(1)];
  146. }
  147. return [2, ...remainder.slice(1)];
  148. case ">=":
  149. return remainder;
  150. case "=":
  151. case "v":
  152. case "":
  153. return toFixed(remainder);
  154. case "<":
  155. return negate(remainder);
  156. case ">": {
  157. // and( >=, not( = ) ) => >=, =, not, and
  158. const fixed = toFixed(remainder);
  159. // eslint-disable-next-line no-sparse-arrays
  160. return [, fixed, 0, remainder, 2];
  161. }
  162. case "<=":
  163. // or( <, = ) => <, =, or
  164. // eslint-disable-next-line no-sparse-arrays
  165. return [, toFixed(remainder), negate(remainder), 1];
  166. case "!": {
  167. // not =
  168. const fixed = toFixed(remainder);
  169. // eslint-disable-next-line no-sparse-arrays
  170. return [, fixed, 0];
  171. }
  172. default:
  173. throw new Error("Unexpected start value");
  174. }
  175. };
  176. const combine = (items, fn) => {
  177. if (items.length === 1) return items[0];
  178. const arr = [];
  179. for (const item of items.slice().reverse()) {
  180. if (0 in item) {
  181. arr.push(item);
  182. } else {
  183. arr.push(...item.slice(1));
  184. }
  185. }
  186. // eslint-disable-next-line no-sparse-arrays
  187. return [, ...arr, ...items.slice(1).map(() => fn)];
  188. };
  189. const parseRange = str => {
  190. // range ::= hyphen | simple ( ' ' ( ' ' ) * simple ) * | ''
  191. // hyphen ::= partial ( ' ' ) * ' - ' ( ' ' ) * partial
  192. const items = str.split(/\s+-\s+/);
  193. if (items.length === 1) {
  194. const items = str
  195. .trim()
  196. .split(/(?<=[-0-9A-Za-z])\s+/g)
  197. .map(parseSimple);
  198. return combine(items, 2);
  199. }
  200. const a = parsePartial(items[0]);
  201. const b = parsePartial(items[1]);
  202. // >=a <=b => and( >=a, or( <b, =b ) ) => >=a, <b, =b, or, and
  203. // eslint-disable-next-line no-sparse-arrays
  204. return [, toFixed(b), negate(b), 1, a, 2];
  205. };
  206. const parseLogicalOr = str => {
  207. // range-set ::= range ( logical-or range ) *
  208. // logical-or ::= ( ' ' ) * '||' ( ' ' ) *
  209. const items = str.split(/\s*\|\|\s*/).map(parseRange);
  210. return combine(items, 1);
  211. };
  212. return parseLogicalOr(str);
  213. };
  214. /* eslint-disable eqeqeq */
  215. const rangeToString = range => {
  216. var fixCount = range[0];
  217. var str = "";
  218. if (range.length === 1) {
  219. return "*";
  220. } else if (fixCount + 0.5) {
  221. str +=
  222. fixCount == 0
  223. ? ">="
  224. : fixCount == -1
  225. ? "<"
  226. : fixCount == 1
  227. ? "^"
  228. : fixCount == 2
  229. ? "~"
  230. : fixCount > 0
  231. ? "="
  232. : "!=";
  233. var needDot = 1;
  234. for (var i = 1; i < range.length; i++) {
  235. var item = range[i];
  236. var t = (typeof item)[0];
  237. needDot--;
  238. str +=
  239. t == "u"
  240. ? // undefined: prerelease marker, add an "-"
  241. "-"
  242. : // number or string: add the item, set flag to add an "." between two of them
  243. (needDot > 0 ? "." : "") + ((needDot = 2), item);
  244. }
  245. return str;
  246. } else {
  247. var stack = [];
  248. // eslint-disable-next-line no-redeclare
  249. for (var i = 1; i < range.length; i++) {
  250. // eslint-disable-next-line no-redeclare
  251. var item = range[i];
  252. stack.push(
  253. item === 0
  254. ? "not(" + pop() + ")"
  255. : item === 1
  256. ? "(" + pop() + " || " + pop() + ")"
  257. : item === 2
  258. ? stack.pop() + " " + stack.pop()
  259. : rangeToString(item)
  260. );
  261. }
  262. return pop();
  263. }
  264. function pop() {
  265. return stack.pop().replace(/^\((.+)\)$/, "$1");
  266. }
  267. };
  268. /* eslint-enable eqeqeq */
  269. exports.rangeToString = rangeToString;
  270. /* eslint-disable eqeqeq */
  271. /**
  272. * @param {SemVerRange} range version range
  273. * @param {string} version the version
  274. * @returns {boolean} if version satisfy the range
  275. */
  276. const satisfy = (range, version) => {
  277. if (0 in range) {
  278. // @ts-expect-error
  279. version = parseVersion(version);
  280. var fixCount = /** @type {number} */ (range[0]);
  281. // when negated is set it swill set for < instead of >=
  282. var negated = fixCount < 0;
  283. if (negated) fixCount = -fixCount - 1;
  284. for (var i = 0, j = 1, isEqual = true; ; j++, i++) {
  285. // cspell:word nequal nequ
  286. // when isEqual = true:
  287. // range version: EOA/object undefined number string
  288. // EOA equal block big-ver big-ver
  289. // undefined bigger next big-ver big-ver
  290. // number smaller block cmp big-cmp
  291. // fixed number smaller block cmp-fix differ
  292. // string smaller block differ cmp
  293. // fixed string smaller block small-cmp cmp-fix
  294. // when isEqual = false:
  295. // range version: EOA/object undefined number string
  296. // EOA nequal block next-ver next-ver
  297. // undefined nequal block next-ver next-ver
  298. // number nequal block next next
  299. // fixed number nequal block next next (this never happens)
  300. // string nequal block next next
  301. // fixed string nequal block next next (this never happens)
  302. // EOA end of array
  303. // equal (version is equal range):
  304. // when !negated: return true,
  305. // when negated: return false
  306. // bigger (version is bigger as range):
  307. // when fixed: return false,
  308. // when !negated: return true,
  309. // when negated: return false,
  310. // smaller (version is smaller as range):
  311. // when !negated: return false,
  312. // when negated: return true
  313. // nequal (version is not equal range (> resp <)): return true
  314. // block (version is in different prerelease area): return false
  315. // differ (version is different from fixed range (string vs. number)): return false
  316. // next: continues to the next items
  317. // next-ver: when fixed: return false, continues to the next item only for the version, sets isEqual=false
  318. // big-ver: when fixed || negated: return false, continues to the next item only for the version, sets isEqual=false
  319. // next-nequ: continues to the next items, sets isEqual=false
  320. // cmp (negated === false): version < range => return false, version > range => next-nequ, else => next
  321. // cmp (negated === true): version > range => return false, version < range => next-nequ, else => next
  322. // cmp-fix: version == range => next, else => return false
  323. // big-cmp: when negated => return false, else => next-nequ
  324. // small-cmp: when negated => next-nequ, else => return false
  325. var rangeType = j < range.length ? (typeof range[j])[0] : "";
  326. var versionValue;
  327. var versionType;
  328. // Handles first column in both tables (end of version or object)
  329. if (
  330. i >= version.length ||
  331. ((versionValue = version[i]),
  332. (versionType = (typeof versionValue)[0]) == "o")
  333. ) {
  334. // Handles nequal
  335. if (!isEqual) return true;
  336. // Handles bigger
  337. if (rangeType == "u") return j > fixCount && !negated;
  338. // Handles equal and smaller: (range === EOA) XOR negated
  339. return (rangeType == "") != negated; // equal + smaller
  340. }
  341. // Handles second column in both tables (version = undefined)
  342. if (versionType == "u") {
  343. if (!isEqual || rangeType != "u") {
  344. return false;
  345. }
  346. }
  347. // switch between first and second table
  348. else if (isEqual) {
  349. // Handle diagonal
  350. if (rangeType == versionType) {
  351. if (j <= fixCount) {
  352. // Handles "cmp-fix" cases
  353. if (versionValue != range[j]) {
  354. return false;
  355. }
  356. } else {
  357. // Handles "cmp" cases
  358. if (negated ? versionValue > range[j] : versionValue < range[j]) {
  359. return false;
  360. }
  361. if (versionValue != range[j]) isEqual = false;
  362. }
  363. }
  364. // Handle big-ver
  365. else if (rangeType != "s" && rangeType != "n") {
  366. if (negated || j <= fixCount) return false;
  367. isEqual = false;
  368. j--;
  369. }
  370. // Handle differ, big-cmp and small-cmp
  371. else if (j <= fixCount || versionType < rangeType != negated) {
  372. return false;
  373. } else {
  374. isEqual = false;
  375. }
  376. } else {
  377. // Handles all "next-ver" cases in the second table
  378. if (rangeType != "s" && rangeType != "n") {
  379. isEqual = false;
  380. j--;
  381. }
  382. // next is applied by default
  383. }
  384. }
  385. }
  386. /** @type {(boolean | number)[]} */
  387. var stack = [];
  388. var p = stack.pop.bind(stack);
  389. // eslint-disable-next-line no-redeclare
  390. for (var i = 1; i < range.length; i++) {
  391. var item = /** @type {SemVerRange | 0 | 1 | 2} */ (range[i]);
  392. stack.push(
  393. item == 1
  394. ? p() | p()
  395. : item == 2
  396. ? p() & p()
  397. : item
  398. ? satisfy(item, version)
  399. : !p()
  400. );
  401. }
  402. return !!p();
  403. };
  404. /* eslint-enable eqeqeq */
  405. exports.satisfy = satisfy;
  406. exports.stringifyHoley = json => {
  407. switch (typeof json) {
  408. case "undefined":
  409. return "";
  410. case "object":
  411. if (Array.isArray(json)) {
  412. let str = "[";
  413. for (let i = 0; i < json.length; i++) {
  414. if (i !== 0) str += ",";
  415. str += this.stringifyHoley(json[i]);
  416. }
  417. str += "]";
  418. return str;
  419. } else {
  420. return JSON.stringify(json);
  421. }
  422. default:
  423. return JSON.stringify(json);
  424. }
  425. };
  426. //#region runtime code: parseVersion
  427. exports.parseVersionRuntimeCode = runtimeTemplate =>
  428. `var parseVersion = ${runtimeTemplate.basicFunction("str", [
  429. "// see webpack/lib/util/semver.js for original code",
  430. `var p=${runtimeTemplate.supportsArrowFunction() ? "p=>" : "function(p)"}{return p.split(".").map((${runtimeTemplate.supportsArrowFunction() ? "p=>" : "function(p)"}{return+p==p?+p:p}))},n=/^([^-+]+)?(?:-([^+]+))?(?:\\+(.+))?$/.exec(str),r=n[1]?p(n[1]):[];return n[2]&&(r.length++,r.push.apply(r,p(n[2]))),n[3]&&(r.push([]),r.push.apply(r,p(n[3]))),r;`
  431. ])}`;
  432. //#endregion
  433. //#region runtime code: versionLt
  434. exports.versionLtRuntimeCode = runtimeTemplate =>
  435. `var versionLt = ${runtimeTemplate.basicFunction("a, b", [
  436. "// see webpack/lib/util/semver.js for original code",
  437. 'a=parseVersion(a),b=parseVersion(b);for(var r=0;;){if(r>=a.length)return r<b.length&&"u"!=(typeof b[r])[0];var e=a[r],n=(typeof e)[0];if(r>=b.length)return"u"==n;var t=b[r],f=(typeof t)[0];if(n!=f)return"o"==n&&"n"==f||("s"==f||"u"==n);if("o"!=n&&"u"!=n&&e!=t)return e<t;r++}'
  438. ])}`;
  439. //#endregion
  440. //#region runtime code: rangeToString
  441. exports.rangeToStringRuntimeCode = runtimeTemplate =>
  442. `var rangeToString = ${runtimeTemplate.basicFunction("range", [
  443. "// see webpack/lib/util/semver.js for original code",
  444. 'var r=range[0],n="";if(1===range.length)return"*";if(r+.5){n+=0==r?">=":-1==r?"<":1==r?"^":2==r?"~":r>0?"=":"!=";for(var e=1,a=1;a<range.length;a++){e--,n+="u"==(typeof(t=range[a]))[0]?"-":(e>0?".":"")+(e=2,t)}return n}var g=[];for(a=1;a<range.length;a++){var t=range[a];g.push(0===t?"not("+o()+")":1===t?"("+o()+" || "+o()+")":2===t?g.pop()+" "+g.pop():rangeToString(t))}return o();function o(){return g.pop().replace(/^\\((.+)\\)$/,"$1")}'
  445. ])}`;
  446. //#endregion
  447. //#region runtime code: satisfy
  448. exports.satisfyRuntimeCode = runtimeTemplate =>
  449. `var satisfy = ${runtimeTemplate.basicFunction("range, version", [
  450. "// see webpack/lib/util/semver.js for original code",
  451. 'if(0 in range){version=parseVersion(version);var e=range[0],r=e<0;r&&(e=-e-1);for(var n=0,i=1,a=!0;;i++,n++){var f,s,g=i<range.length?(typeof range[i])[0]:"";if(n>=version.length||"o"==(s=(typeof(f=version[n]))[0]))return!a||("u"==g?i>e&&!r:""==g!=r);if("u"==s){if(!a||"u"!=g)return!1}else if(a)if(g==s)if(i<=e){if(f!=range[i])return!1}else{if(r?f>range[i]:f<range[i])return!1;f!=range[i]&&(a=!1)}else if("s"!=g&&"n"!=g){if(r||i<=e)return!1;a=!1,i--}else{if(i<=e||s<g!=r)return!1;a=!1}else"s"!=g&&"n"!=g&&(a=!1,i--)}}var t=[],o=t.pop.bind(t);for(n=1;n<range.length;n++){var u=range[n];t.push(1==u?o()|o():2==u?o()&o():u?satisfy(u,version):!o())}return!!o();'
  452. ])}`;
  453. //#endregion