vitest 0.29.7 → 0.29.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE.md +1 -185
  2. package/dist/browser.d.ts +12 -2
  3. package/dist/browser.js +5 -3
  4. package/dist/child.js +4 -5
  5. package/dist/{chunk-api-setup.ac7748ac.js → chunk-api-setup.3aabe9ac.js} +16 -7
  6. package/dist/{chunk-install-pkg.863031f2.js → chunk-install-pkg.6aa7cf6d.js} +7 -6
  7. package/dist/{chunk-integrations-coverage.e0a6acd2.js → chunk-integrations-coverage.d93ee824.js} +5 -5
  8. package/dist/{chunk-integrations-globals.a473e88a.js → chunk-integrations-globals.49802775.js} +8 -7
  9. package/dist/{chunk-integrations-run-once.a2b4758b.js → chunk-integrations-run-once.ea614f17.js} +2 -1
  10. package/dist/{chunk-integrations-utils.d7c85bd9.js → chunk-integrations-utils.23c19408.js} +2 -2
  11. package/dist/{chunk-node-pkg.f9696901.js → chunk-node-pkg.30d8b37e.js} +155 -2330
  12. package/dist/{chunk-runtime-mocker.344fec90.js → chunk-runtime-mocker.3283818a.js} +3 -3
  13. package/dist/{chunk-runtime-rpc.1b5714dc.js → chunk-runtime-rpc.d6aa57f8.js} +1 -1
  14. package/dist/{chunk-runtime-setup.a49dc2f9.js → chunk-runtime-setup.5d504677.js} +2 -2
  15. package/dist/{chunk-utils-base.81f83dbd.js → chunk-utils-base.b5ddfcc9.js} +4 -1
  16. package/dist/{chunk-utils-env.04ffbef7.js → chunk-utils-env.6b856dbf.js} +2 -8
  17. package/dist/chunk-utils-global.fd174983.js +8 -0
  18. package/dist/{chunk-utils-import.39ffe9c5.js → chunk-utils-import.e488ace3.js} +194 -195
  19. package/dist/{chunk-utils-tasks.b41c8284.js → chunk-utils-tasks.8781fd71.js} +2 -2
  20. package/dist/cli.js +7 -6
  21. package/dist/config.cjs +0 -5
  22. package/dist/config.d.ts +1 -5
  23. package/dist/config.js +0 -5
  24. package/dist/coverage.d.ts +1 -1
  25. package/dist/entry.js +11 -10
  26. package/dist/environments.d.ts +1 -1
  27. package/dist/index.d.ts +8 -13
  28. package/dist/index.js +9 -8
  29. package/dist/loader.js +2 -1
  30. package/dist/node.d.ts +2 -2
  31. package/dist/node.js +9 -8
  32. package/dist/runners.d.ts +1 -1
  33. package/dist/runners.js +6 -5
  34. package/dist/{types-fafda418.d.ts → types-94cfe4b4.d.ts} +23 -16
  35. package/dist/utils.d.ts +1 -0
  36. package/dist/utils.js +1 -0
  37. package/dist/worker.js +7 -8
  38. package/package.json +18 -7
  39. package/utils.d.ts +1 -0
@@ -1,10 +1,10 @@
1
1
  import { join, dirname, basename, relative, extname, resolve as resolve$2, normalize, isAbsolute, toNamespacedPath } from 'pathe';
2
2
  import { E as EXIT_CODE_RESTART, c as configFiles, d as defaultPort } from './chunk-constants.bc18a549.js';
3
- import { g as getCoverageProvider, C as CoverageProviderMap } from './chunk-integrations-coverage.e0a6acd2.js';
3
+ import { g as getCoverageProvider, C as CoverageProviderMap } from './chunk-integrations-coverage.d93ee824.js';
4
4
  import { g as getEnvPackageName } from './chunk-env-node.affdd278.js';
5
5
  import c from 'picocolors';
6
6
  import { isPackageExists, resolveModule } from 'local-pkg';
7
- import { c as isNode, d as relativePath, a as getCallLastIndex, e as removeUndefinedValues, f as isWindows } from './chunk-utils-env.04ffbef7.js';
7
+ import { a as isNode, b as relativePath, g as getCallLastIndex, c as removeUndefinedValues, d as isWindows } from './chunk-utils-env.6b856dbf.js';
8
8
  import { isCI } from 'std-env';
9
9
  import { loadConfigFromFile, createServer, mergeConfig } from 'vite';
10
10
  import path$a from 'node:path';
@@ -13,7 +13,7 @@ import process$1 from 'node:process';
13
13
  import fs$8, { promises, existsSync } from 'node:fs';
14
14
  import k from 'path';
15
15
  import require$$0 from 'os';
16
- import require$$0$1, { promisify } from 'util';
16
+ import require$$0$1 from 'util';
17
17
  import require$$0$2 from 'stream';
18
18
  import require$$2 from 'events';
19
19
  import require$$0$3, { existsSync as existsSync$1, readFileSync } from 'fs';
@@ -27,10 +27,9 @@ import K, { createRequire } from 'module';
27
27
  import { parse as parse$4 } from 'acorn';
28
28
  import { ancestor } from 'acorn-walk';
29
29
  import { generateHash, calculateSuiteHash, someTasksAreOnly, interpretTaskModes, getTasks, getTests, hasFailed, getSuites } from '@vitest/runner/utils';
30
- import require$$0$4 from 'child_process';
31
- import { createDefer, shuffle, getSafeTimers, stringify as stringify$5, toArray as toArray$1 } from '@vitest/utils';
32
- import { s as slash$1, t as toArray, g as groupBy, a as getEnvironmentTransformMode, n as notNullish, b as noop$1, d as deepMerge, c as stdout } from './chunk-utils-base.81f83dbd.js';
30
+ import { s as slash$1, t as toArray, g as groupBy, b as getEnvironmentTransformMode, n as notNullish, a as isPrimitive, c as noop$1, d as deepMerge, e as stdout } from './chunk-utils-base.b5ddfcc9.js';
33
31
  import { createHash } from 'crypto';
32
+ import { shuffle, createDefer, getSafeTimers, stringify as stringify$5, toArray as toArray$1 } from '@vitest/utils';
34
33
  import { d as distDir, r as rootDir } from './chunk-paths.e36446b4.js';
35
34
  import v8 from 'node:v8';
36
35
  import { fork } from 'node:child_process';
@@ -39,14 +38,14 @@ import { MessageChannel } from 'node:worker_threads';
39
38
  import { cpus, hostname } from 'node:os';
40
39
  import Tinypool from 'tinypool';
41
40
  import { performance } from 'perf_hooks';
42
- import { g as getFullName, h as hasFailedSnapshot, a as parseErrorStacktrace, p as positionToOffset, l as lineSplitRE } from './chunk-utils-tasks.b41c8284.js';
41
+ import { g as getFullName, h as hasFailedSnapshot, a as parseErrorStacktrace, p as positionToOffset, l as lineSplitRE } from './chunk-utils-tasks.8781fd71.js';
43
42
  import { unifiedDiff } from '@vitest/utils/diff';
44
43
  import { ViteNodeServer } from 'vite-node/server';
45
44
  import { d as decode, e as encode, M as MagicString } from './vendor-magic-string.es.b3bc5745.js';
46
45
  import { builtinModules } from 'node:module';
47
46
  import { createHash as createHash$1 } from 'node:crypto';
48
47
  import { stripLiteral } from 'strip-literal';
49
- import require$$0$5 from 'readline';
48
+ import require$$0$4 from 'readline';
50
49
 
51
50
  function _mergeNamespaces(n, m) {
52
51
  m.forEach(function (e) {
@@ -63,7 +62,7 @@ function _mergeNamespaces(n, m) {
63
62
  return Object.freeze(n);
64
63
  }
65
64
 
66
- var version$1 = "0.29.7";
65
+ var version$1 = "0.29.8";
67
66
 
68
67
  async function ensurePackageInstalled(dependency, root) {
69
68
  if (isPackageExists(dependency, { paths: [root] }))
@@ -81,7 +80,7 @@ async function ensurePackageInstalled(dependency, root) {
81
80
  message: c.reset(`Do you want to install ${c.green(dependency)}?`)
82
81
  });
83
82
  if (install) {
84
- await (await import('./chunk-install-pkg.863031f2.js')).installPackage(dependency, { dev: true });
83
+ await (await import('./chunk-install-pkg.6aa7cf6d.js')).installPackage(dependency, { dev: true });
85
84
  process.stderr.write(c.yellow(`
86
85
  Package ${dependency} installed, re-run the command to start.
87
86
  `));
@@ -7492,2265 +7491,65 @@ class Typechecker {
7492
7491
  }
7493
7492
  }
7494
7493
 
7495
- var commonName;
7496
- var hasRequiredCommonName;
7497
-
7498
- function requireCommonName () {
7499
- if (hasRequiredCommonName) return commonName;
7500
- hasRequiredCommonName = 1;
7501
- commonName = function (out) {
7502
- return (
7503
- out.isEdge ? "edge" :
7504
- out.isIE ? "ie" :
7505
- out.isFirefox ? "firefox" :
7506
- out.isChrome ? "chrome" :
7507
- out.isChromium ? "chromium" :
7508
- out.isOpera ? "opera" :
7509
- out.isSafari ? "safari" :
7510
- "unknown"
7511
- );
7512
- };
7513
- return commonName;
7514
- }
7515
-
7516
- var detectWindows10;
7517
- var hasRequiredDetectWindows10;
7518
-
7519
- function requireDetectWindows10 () {
7520
- if (hasRequiredDetectWindows10) return detectWindows10;
7521
- hasRequiredDetectWindows10 = 1;
7522
- var exec = require$$0$4.exec;
7523
-
7524
- detectWindows10 = function (callback) {
7525
-
7526
- var registryQuery = 'HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\Shell\\Associations\\URLAssociations\\http\\UserChoice';
7527
- var command = 'reg query ' + registryQuery + ' | findstr /i "ProgId"';
7528
-
7529
- exec(command, function (err, stdout, stderr) {
7530
- var value;
7531
- // parse the output which is sth like this (Windows 10):
7532
- // " ProgId REG_SZ ChromeHTML\r\n"
7533
- if (err) {
7534
- if (stderr.length > 0) {
7535
- return callback('Unable to execute the query: ' + err);
7536
- } else {
7537
- // findstr failed due to not finding match => key is empty, default browser is IE
7538
- value = 'iexplore.exe';
7539
- }
7540
- }
7541
-
7542
- if (!value) {
7543
- // merge multiple spaces to one
7544
- stdout = stdout.trim().replace(/\s\s+/g, ' ');
7545
- var split = stdout.split(' ');
7546
- // need third substr, stdout is of this form: " ProgId REG_SZ ChromeHTML\r\n"
7547
- value = split[2].toLowerCase();
7548
- }
7549
-
7550
- var out = {
7551
- isEdge: value.indexOf('msedge') > -1, // MSEdgeHTM
7552
- isIE: value.indexOf('ie.http') > -1, // IE.HTTP
7553
- isSafari: value.indexOf('safari') > -1, // SafariURL
7554
- isFirefox: value.indexOf('firefox') > -1, // FirefoxURL
7555
- isChrome: value.indexOf('chrome') > -1, // ChromeHTML
7556
- isChromium: value.indexOf('chromium') > -1,
7557
- isOpera: value.indexOf('opera') > -1, // OperaHTML
7558
- identity: value
7559
- };
7560
- out.isBlink = (out.isChrome || out.isChromium || out.isOpera);
7561
- out.isWebkit = (out.isSafari || out.isBlink);
7562
- out.commonName = requireCommonName()(out);
7563
-
7564
- callback(null, out);
7565
- });
7566
- };
7567
- return detectWindows10;
7568
- }
7569
-
7570
- var detectWindows;
7571
- var hasRequiredDetectWindows;
7572
-
7573
- function requireDetectWindows () {
7574
- if (hasRequiredDetectWindows) return detectWindows;
7575
- hasRequiredDetectWindows = 1;
7576
- var exec = require$$0$4.exec;
7577
-
7578
- detectWindows = function (callback) {
7579
-
7580
- // It seems that StartMenuInternet is more reliable; IE may be default without changing http-shell-open-command
7581
- var registryQuery = 'HKCU\\Software\\Clients\\StartMenuInternet';
7582
- //var registryQuery = 'HKCU\\Software\\Classes\\http\\shell\\open\\command'
7583
- var command = 'reg query ' + registryQuery + ' | findstr "REG_SZ"';
7584
-
7585
- exec(command, function (err, stdout, stderr) {
7586
- var value;
7587
- // parse the output which is sth like this (XP):
7588
- // ! REG.EXE VERSION 3.0
7589
- //
7590
- // HKEY_CURRENT_USER\Software\Classes\http\shell\open\command
7591
- // <NO NAME> REG_SZ "C:\Program Files\Mozilla Firefox\firefox.exe" -osint -url "%1"
7592
- if (err) {
7593
- if (stderr.length > 0) {
7594
- return callback('Unable to execute the query: ' + err);
7595
- } else {
7596
- // findstr failed due to not finding match => key is empty, default browser is IE
7597
- value = 'iexplore.exe';
7598
- }
7599
- }
7600
-
7601
- if (!value) {
7602
- // XP hack to get rid of space so we can later split on it...
7603
- stdout = stdout.replace("NO NAME", "NONAME");
7604
- // on XP it's tab-separated, on Win7 space-separated...
7605
- var split = stdout.trim().split(/(\t| +)/);
7606
- // splits to sth like [ '(Default)', ' ', 'REG_SZ', ' ', 'value' ] but for "Google Chrome" it will be further split...
7607
- value = (split[4] + (split[5] || "") + (split[6] || "")).toLowerCase();
7608
- }
7609
-
7610
- //var pos1 = value.indexOf('"') + 1;
7611
- //var pos2 = value.indexOf('"', pos1);
7612
- //var path = value.substring(pos1, pos2);
7613
-
7614
- var out = {
7615
- isIE: value.indexOf('iexplore') > -1, // IEXPLORE.EXE / -
7616
- isSafari: value.indexOf('safari') > -1, // Safari.exe
7617
- // works also for nightly
7618
- isFirefox: value.indexOf('firefox') > -1, // FIREFOX.EXE / "C:\Program Files (x86)\Mozilla Firefox\firefox.exe" -osint -url "%1"
7619
- // note that both chrome and chromium are chrome.exe! we can't look for 'chrome' hence
7620
- isChrome: value.indexOf('google') > -1, // Google Chrome / "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -- "%1"
7621
- isChromium: value.indexOf('chromium') > -1, // Chromium.<randomstring> / "C:\Users\<username>\AppData\Local\Chromium\Application\chrome.exe" -- "%1"
7622
- isOpera: value.indexOf('opera') > -1, // OperaStable / "C:\Program Files (x86)\Opera\launcher.exe" -noautoupdate -- "%1"
7623
- identity: value
7624
- };
7625
- out.isBlink = (out.isChrome || out.isChromium || out.isOpera);
7626
- out.isWebkit = (out.isSafari || out.isBlink);
7627
- out.commonName = requireCommonName()(out);
7628
-
7629
- callback(null, out);
7630
- });
7631
- };
7632
- return detectWindows;
7633
- }
7634
-
7635
- var bplistParser = {};
7636
-
7637
- var BigInteger = {exports: {}};
7638
-
7639
- var hasRequiredBigInteger;
7640
-
7641
- function requireBigInteger () {
7642
- if (hasRequiredBigInteger) return BigInteger.exports;
7643
- hasRequiredBigInteger = 1;
7644
- (function (module) {
7645
- var bigInt = (function (undefined$1) {
7646
-
7647
- var BASE = 1e7,
7648
- LOG_BASE = 7,
7649
- MAX_INT = 9007199254740992,
7650
- MAX_INT_ARR = smallToArray(MAX_INT),
7651
- DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
7652
-
7653
- var supportsNativeBigInt = typeof BigInt === "function";
7654
-
7655
- function Integer(v, radix, alphabet, caseSensitive) {
7656
- if (typeof v === "undefined") return Integer[0];
7657
- if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive);
7658
- return parseValue(v);
7659
- }
7660
-
7661
- function BigInteger(value, sign) {
7662
- this.value = value;
7663
- this.sign = sign;
7664
- this.isSmall = false;
7665
- }
7666
- BigInteger.prototype = Object.create(Integer.prototype);
7667
-
7668
- function SmallInteger(value) {
7669
- this.value = value;
7670
- this.sign = value < 0;
7671
- this.isSmall = true;
7672
- }
7673
- SmallInteger.prototype = Object.create(Integer.prototype);
7674
-
7675
- function NativeBigInt(value) {
7676
- this.value = value;
7677
- }
7678
- NativeBigInt.prototype = Object.create(Integer.prototype);
7679
-
7680
- function isPrecise(n) {
7681
- return -MAX_INT < n && n < MAX_INT;
7682
- }
7683
-
7684
- function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes
7685
- if (n < 1e7)
7686
- return [n];
7687
- if (n < 1e14)
7688
- return [n % 1e7, Math.floor(n / 1e7)];
7689
- return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];
7690
- }
7691
-
7692
- function arrayToSmall(arr) { // If BASE changes this function may need to change
7693
- trim(arr);
7694
- var length = arr.length;
7695
- if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {
7696
- switch (length) {
7697
- case 0: return 0;
7698
- case 1: return arr[0];
7699
- case 2: return arr[0] + arr[1] * BASE;
7700
- default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;
7701
- }
7702
- }
7703
- return arr;
7704
- }
7705
-
7706
- function trim(v) {
7707
- var i = v.length;
7708
- while (v[--i] === 0);
7709
- v.length = i + 1;
7710
- }
7711
-
7712
- function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger
7713
- var x = new Array(length);
7714
- var i = -1;
7715
- while (++i < length) {
7716
- x[i] = 0;
7717
- }
7718
- return x;
7719
- }
7720
-
7721
- function truncate(n) {
7722
- if (n > 0) return Math.floor(n);
7723
- return Math.ceil(n);
7724
- }
7725
-
7726
- function add(a, b) { // assumes a and b are arrays with a.length >= b.length
7727
- var l_a = a.length,
7728
- l_b = b.length,
7729
- r = new Array(l_a),
7730
- carry = 0,
7731
- base = BASE,
7732
- sum, i;
7733
- for (i = 0; i < l_b; i++) {
7734
- sum = a[i] + b[i] + carry;
7735
- carry = sum >= base ? 1 : 0;
7736
- r[i] = sum - carry * base;
7737
- }
7738
- while (i < l_a) {
7739
- sum = a[i] + carry;
7740
- carry = sum === base ? 1 : 0;
7741
- r[i++] = sum - carry * base;
7742
- }
7743
- if (carry > 0) r.push(carry);
7744
- return r;
7745
- }
7746
-
7747
- function addAny(a, b) {
7748
- if (a.length >= b.length) return add(a, b);
7749
- return add(b, a);
7750
- }
7751
-
7752
- function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT
7753
- var l = a.length,
7754
- r = new Array(l),
7755
- base = BASE,
7756
- sum, i;
7757
- for (i = 0; i < l; i++) {
7758
- sum = a[i] - base + carry;
7759
- carry = Math.floor(sum / base);
7760
- r[i] = sum - carry * base;
7761
- carry += 1;
7762
- }
7763
- while (carry > 0) {
7764
- r[i++] = carry % base;
7765
- carry = Math.floor(carry / base);
7766
- }
7767
- return r;
7768
- }
7769
-
7770
- BigInteger.prototype.add = function (v) {
7771
- var n = parseValue(v);
7772
- if (this.sign !== n.sign) {
7773
- return this.subtract(n.negate());
7774
- }
7775
- var a = this.value, b = n.value;
7776
- if (n.isSmall) {
7777
- return new BigInteger(addSmall(a, Math.abs(b)), this.sign);
7778
- }
7779
- return new BigInteger(addAny(a, b), this.sign);
7780
- };
7781
- BigInteger.prototype.plus = BigInteger.prototype.add;
7782
-
7783
- SmallInteger.prototype.add = function (v) {
7784
- var n = parseValue(v);
7785
- var a = this.value;
7786
- if (a < 0 !== n.sign) {
7787
- return this.subtract(n.negate());
7788
- }
7789
- var b = n.value;
7790
- if (n.isSmall) {
7791
- if (isPrecise(a + b)) return new SmallInteger(a + b);
7792
- b = smallToArray(Math.abs(b));
7793
- }
7794
- return new BigInteger(addSmall(b, Math.abs(a)), a < 0);
7795
- };
7796
- SmallInteger.prototype.plus = SmallInteger.prototype.add;
7797
-
7798
- NativeBigInt.prototype.add = function (v) {
7799
- return new NativeBigInt(this.value + parseValue(v).value);
7800
- };
7801
- NativeBigInt.prototype.plus = NativeBigInt.prototype.add;
7802
-
7803
- function subtract(a, b) { // assumes a and b are arrays with a >= b
7804
- var a_l = a.length,
7805
- b_l = b.length,
7806
- r = new Array(a_l),
7807
- borrow = 0,
7808
- base = BASE,
7809
- i, difference;
7810
- for (i = 0; i < b_l; i++) {
7811
- difference = a[i] - borrow - b[i];
7812
- if (difference < 0) {
7813
- difference += base;
7814
- borrow = 1;
7815
- } else borrow = 0;
7816
- r[i] = difference;
7817
- }
7818
- for (i = b_l; i < a_l; i++) {
7819
- difference = a[i] - borrow;
7820
- if (difference < 0) difference += base;
7821
- else {
7822
- r[i++] = difference;
7823
- break;
7824
- }
7825
- r[i] = difference;
7826
- }
7827
- for (; i < a_l; i++) {
7828
- r[i] = a[i];
7829
- }
7830
- trim(r);
7831
- return r;
7832
- }
7833
-
7834
- function subtractAny(a, b, sign) {
7835
- var value;
7836
- if (compareAbs(a, b) >= 0) {
7837
- value = subtract(a, b);
7838
- } else {
7839
- value = subtract(b, a);
7840
- sign = !sign;
7841
- }
7842
- value = arrayToSmall(value);
7843
- if (typeof value === "number") {
7844
- if (sign) value = -value;
7845
- return new SmallInteger(value);
7846
- }
7847
- return new BigInteger(value, sign);
7848
- }
7849
-
7850
- function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT
7851
- var l = a.length,
7852
- r = new Array(l),
7853
- carry = -b,
7854
- base = BASE,
7855
- i, difference;
7856
- for (i = 0; i < l; i++) {
7857
- difference = a[i] + carry;
7858
- carry = Math.floor(difference / base);
7859
- difference %= base;
7860
- r[i] = difference < 0 ? difference + base : difference;
7861
- }
7862
- r = arrayToSmall(r);
7863
- if (typeof r === "number") {
7864
- if (sign) r = -r;
7865
- return new SmallInteger(r);
7866
- } return new BigInteger(r, sign);
7867
- }
7868
-
7869
- BigInteger.prototype.subtract = function (v) {
7870
- var n = parseValue(v);
7871
- if (this.sign !== n.sign) {
7872
- return this.add(n.negate());
7873
- }
7874
- var a = this.value, b = n.value;
7875
- if (n.isSmall)
7876
- return subtractSmall(a, Math.abs(b), this.sign);
7877
- return subtractAny(a, b, this.sign);
7878
- };
7879
- BigInteger.prototype.minus = BigInteger.prototype.subtract;
7880
-
7881
- SmallInteger.prototype.subtract = function (v) {
7882
- var n = parseValue(v);
7883
- var a = this.value;
7884
- if (a < 0 !== n.sign) {
7885
- return this.add(n.negate());
7886
- }
7887
- var b = n.value;
7888
- if (n.isSmall) {
7889
- return new SmallInteger(a - b);
7890
- }
7891
- return subtractSmall(b, Math.abs(a), a >= 0);
7892
- };
7893
- SmallInteger.prototype.minus = SmallInteger.prototype.subtract;
7894
-
7895
- NativeBigInt.prototype.subtract = function (v) {
7896
- return new NativeBigInt(this.value - parseValue(v).value);
7897
- };
7898
- NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;
7899
-
7900
- BigInteger.prototype.negate = function () {
7901
- return new BigInteger(this.value, !this.sign);
7902
- };
7903
- SmallInteger.prototype.negate = function () {
7904
- var sign = this.sign;
7905
- var small = new SmallInteger(-this.value);
7906
- small.sign = !sign;
7907
- return small;
7908
- };
7909
- NativeBigInt.prototype.negate = function () {
7910
- return new NativeBigInt(-this.value);
7911
- };
7912
-
7913
- BigInteger.prototype.abs = function () {
7914
- return new BigInteger(this.value, false);
7915
- };
7916
- SmallInteger.prototype.abs = function () {
7917
- return new SmallInteger(Math.abs(this.value));
7918
- };
7919
- NativeBigInt.prototype.abs = function () {
7920
- return new NativeBigInt(this.value >= 0 ? this.value : -this.value);
7921
- };
7922
-
7923
-
7924
- function multiplyLong(a, b) {
7925
- var a_l = a.length,
7926
- b_l = b.length,
7927
- l = a_l + b_l,
7928
- r = createArray(l),
7929
- base = BASE,
7930
- product, carry, i, a_i, b_j;
7931
- for (i = 0; i < a_l; ++i) {
7932
- a_i = a[i];
7933
- for (var j = 0; j < b_l; ++j) {
7934
- b_j = b[j];
7935
- product = a_i * b_j + r[i + j];
7936
- carry = Math.floor(product / base);
7937
- r[i + j] = product - carry * base;
7938
- r[i + j + 1] += carry;
7939
- }
7940
- }
7941
- trim(r);
7942
- return r;
7943
- }
7944
-
7945
- function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE
7946
- var l = a.length,
7947
- r = new Array(l),
7948
- base = BASE,
7949
- carry = 0,
7950
- product, i;
7951
- for (i = 0; i < l; i++) {
7952
- product = a[i] * b + carry;
7953
- carry = Math.floor(product / base);
7954
- r[i] = product - carry * base;
7955
- }
7956
- while (carry > 0) {
7957
- r[i++] = carry % base;
7958
- carry = Math.floor(carry / base);
7959
- }
7960
- return r;
7961
- }
7962
-
7963
- function shiftLeft(x, n) {
7964
- var r = [];
7965
- while (n-- > 0) r.push(0);
7966
- return r.concat(x);
7967
- }
7968
-
7969
- function multiplyKaratsuba(x, y) {
7970
- var n = Math.max(x.length, y.length);
7971
-
7972
- if (n <= 30) return multiplyLong(x, y);
7973
- n = Math.ceil(n / 2);
7974
-
7975
- var b = x.slice(n),
7976
- a = x.slice(0, n),
7977
- d = y.slice(n),
7978
- c = y.slice(0, n);
7979
-
7980
- var ac = multiplyKaratsuba(a, c),
7981
- bd = multiplyKaratsuba(b, d),
7982
- abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));
7983
-
7984
- var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));
7985
- trim(product);
7986
- return product;
7987
- }
7988
-
7989
- // The following function is derived from a surface fit of a graph plotting the performance difference
7990
- // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.
7991
- function useKaratsuba(l1, l2) {
7992
- return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;
7993
- }
7994
-
7995
- BigInteger.prototype.multiply = function (v) {
7996
- var n = parseValue(v),
7997
- a = this.value, b = n.value,
7998
- sign = this.sign !== n.sign,
7999
- abs;
8000
- if (n.isSmall) {
8001
- if (b === 0) return Integer[0];
8002
- if (b === 1) return this;
8003
- if (b === -1) return this.negate();
8004
- abs = Math.abs(b);
8005
- if (abs < BASE) {
8006
- return new BigInteger(multiplySmall(a, abs), sign);
8007
- }
8008
- b = smallToArray(abs);
8009
- }
8010
- if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes
8011
- return new BigInteger(multiplyKaratsuba(a, b), sign);
8012
- return new BigInteger(multiplyLong(a, b), sign);
8013
- };
8014
-
8015
- BigInteger.prototype.times = BigInteger.prototype.multiply;
8016
-
8017
- function multiplySmallAndArray(a, b, sign) { // a >= 0
8018
- if (a < BASE) {
8019
- return new BigInteger(multiplySmall(b, a), sign);
8020
- }
8021
- return new BigInteger(multiplyLong(b, smallToArray(a)), sign);
8022
- }
8023
- SmallInteger.prototype._multiplyBySmall = function (a) {
8024
- if (isPrecise(a.value * this.value)) {
8025
- return new SmallInteger(a.value * this.value);
8026
- }
8027
- return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);
8028
- };
8029
- BigInteger.prototype._multiplyBySmall = function (a) {
8030
- if (a.value === 0) return Integer[0];
8031
- if (a.value === 1) return this;
8032
- if (a.value === -1) return this.negate();
8033
- return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);
8034
- };
8035
- SmallInteger.prototype.multiply = function (v) {
8036
- return parseValue(v)._multiplyBySmall(this);
8037
- };
8038
- SmallInteger.prototype.times = SmallInteger.prototype.multiply;
8039
-
8040
- NativeBigInt.prototype.multiply = function (v) {
8041
- return new NativeBigInt(this.value * parseValue(v).value);
8042
- };
8043
- NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;
8044
-
8045
- function square(a) {
8046
- //console.assert(2 * BASE * BASE < MAX_INT);
8047
- var l = a.length,
8048
- r = createArray(l + l),
8049
- base = BASE,
8050
- product, carry, i, a_i, a_j;
8051
- for (i = 0; i < l; i++) {
8052
- a_i = a[i];
8053
- carry = 0 - a_i * a_i;
8054
- for (var j = i; j < l; j++) {
8055
- a_j = a[j];
8056
- product = 2 * (a_i * a_j) + r[i + j] + carry;
8057
- carry = Math.floor(product / base);
8058
- r[i + j] = product - carry * base;
8059
- }
8060
- r[i + l] = carry;
8061
- }
8062
- trim(r);
8063
- return r;
8064
- }
8065
-
8066
- BigInteger.prototype.square = function () {
8067
- return new BigInteger(square(this.value), false);
8068
- };
8069
-
8070
- SmallInteger.prototype.square = function () {
8071
- var value = this.value * this.value;
8072
- if (isPrecise(value)) return new SmallInteger(value);
8073
- return new BigInteger(square(smallToArray(Math.abs(this.value))), false);
8074
- };
8075
-
8076
- NativeBigInt.prototype.square = function (v) {
8077
- return new NativeBigInt(this.value * this.value);
8078
- };
8079
-
8080
- function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.
8081
- var a_l = a.length,
8082
- b_l = b.length,
8083
- base = BASE,
8084
- result = createArray(b.length),
8085
- divisorMostSignificantDigit = b[b_l - 1],
8086
- // normalization
8087
- lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),
8088
- remainder = multiplySmall(a, lambda),
8089
- divisor = multiplySmall(b, lambda),
8090
- quotientDigit, shift, carry, borrow, i, l, q;
8091
- if (remainder.length <= a_l) remainder.push(0);
8092
- divisor.push(0);
8093
- divisorMostSignificantDigit = divisor[b_l - 1];
8094
- for (shift = a_l - b_l; shift >= 0; shift--) {
8095
- quotientDigit = base - 1;
8096
- if (remainder[shift + b_l] !== divisorMostSignificantDigit) {
8097
- quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);
8098
- }
8099
- // quotientDigit <= base - 1
8100
- carry = 0;
8101
- borrow = 0;
8102
- l = divisor.length;
8103
- for (i = 0; i < l; i++) {
8104
- carry += quotientDigit * divisor[i];
8105
- q = Math.floor(carry / base);
8106
- borrow += remainder[shift + i] - (carry - q * base);
8107
- carry = q;
8108
- if (borrow < 0) {
8109
- remainder[shift + i] = borrow + base;
8110
- borrow = -1;
8111
- } else {
8112
- remainder[shift + i] = borrow;
8113
- borrow = 0;
8114
- }
8115
- }
8116
- while (borrow !== 0) {
8117
- quotientDigit -= 1;
8118
- carry = 0;
8119
- for (i = 0; i < l; i++) {
8120
- carry += remainder[shift + i] - base + divisor[i];
8121
- if (carry < 0) {
8122
- remainder[shift + i] = carry + base;
8123
- carry = 0;
8124
- } else {
8125
- remainder[shift + i] = carry;
8126
- carry = 1;
8127
- }
8128
- }
8129
- borrow += carry;
8130
- }
8131
- result[shift] = quotientDigit;
8132
- }
8133
- // denormalization
8134
- remainder = divModSmall(remainder, lambda)[0];
8135
- return [arrayToSmall(result), arrayToSmall(remainder)];
8136
- }
8137
-
8138
- function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/
8139
- // Performs faster than divMod1 on larger input sizes.
8140
- var a_l = a.length,
8141
- b_l = b.length,
8142
- result = [],
8143
- part = [],
8144
- base = BASE,
8145
- guess, xlen, highx, highy, check;
8146
- while (a_l) {
8147
- part.unshift(a[--a_l]);
8148
- trim(part);
8149
- if (compareAbs(part, b) < 0) {
8150
- result.push(0);
8151
- continue;
8152
- }
8153
- xlen = part.length;
8154
- highx = part[xlen - 1] * base + part[xlen - 2];
8155
- highy = b[b_l - 1] * base + b[b_l - 2];
8156
- if (xlen > b_l) {
8157
- highx = (highx + 1) * base;
8158
- }
8159
- guess = Math.ceil(highx / highy);
8160
- do {
8161
- check = multiplySmall(b, guess);
8162
- if (compareAbs(check, part) <= 0) break;
8163
- guess--;
8164
- } while (guess);
8165
- result.push(guess);
8166
- part = subtract(part, check);
8167
- }
8168
- result.reverse();
8169
- return [arrayToSmall(result), arrayToSmall(part)];
8170
- }
8171
-
8172
- function divModSmall(value, lambda) {
8173
- var length = value.length,
8174
- quotient = createArray(length),
8175
- base = BASE,
8176
- i, q, remainder, divisor;
8177
- remainder = 0;
8178
- for (i = length - 1; i >= 0; --i) {
8179
- divisor = remainder * base + value[i];
8180
- q = truncate(divisor / lambda);
8181
- remainder = divisor - q * lambda;
8182
- quotient[i] = q | 0;
8183
- }
8184
- return [quotient, remainder | 0];
8185
- }
8186
-
8187
- function divModAny(self, v) {
8188
- var value, n = parseValue(v);
8189
- if (supportsNativeBigInt) {
8190
- return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)];
8191
- }
8192
- var a = self.value, b = n.value;
8193
- var quotient;
8194
- if (b === 0) throw new Error("Cannot divide by zero");
8195
- if (self.isSmall) {
8196
- if (n.isSmall) {
8197
- return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];
8198
- }
8199
- return [Integer[0], self];
8200
- }
8201
- if (n.isSmall) {
8202
- if (b === 1) return [self, Integer[0]];
8203
- if (b == -1) return [self.negate(), Integer[0]];
8204
- var abs = Math.abs(b);
8205
- if (abs < BASE) {
8206
- value = divModSmall(a, abs);
8207
- quotient = arrayToSmall(value[0]);
8208
- var remainder = value[1];
8209
- if (self.sign) remainder = -remainder;
8210
- if (typeof quotient === "number") {
8211
- if (self.sign !== n.sign) quotient = -quotient;
8212
- return [new SmallInteger(quotient), new SmallInteger(remainder)];
8213
- }
8214
- return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];
8215
- }
8216
- b = smallToArray(abs);
8217
- }
8218
- var comparison = compareAbs(a, b);
8219
- if (comparison === -1) return [Integer[0], self];
8220
- if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];
8221
-
8222
- // divMod1 is faster on smaller input sizes
8223
- if (a.length + b.length <= 200)
8224
- value = divMod1(a, b);
8225
- else value = divMod2(a, b);
8226
-
8227
- quotient = value[0];
8228
- var qSign = self.sign !== n.sign,
8229
- mod = value[1],
8230
- mSign = self.sign;
8231
- if (typeof quotient === "number") {
8232
- if (qSign) quotient = -quotient;
8233
- quotient = new SmallInteger(quotient);
8234
- } else quotient = new BigInteger(quotient, qSign);
8235
- if (typeof mod === "number") {
8236
- if (mSign) mod = -mod;
8237
- mod = new SmallInteger(mod);
8238
- } else mod = new BigInteger(mod, mSign);
8239
- return [quotient, mod];
8240
- }
8241
-
8242
- BigInteger.prototype.divmod = function (v) {
8243
- var result = divModAny(this, v);
8244
- return {
8245
- quotient: result[0],
8246
- remainder: result[1]
8247
- };
8248
- };
8249
- NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;
8250
-
8251
-
8252
- BigInteger.prototype.divide = function (v) {
8253
- return divModAny(this, v)[0];
8254
- };
8255
- NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) {
8256
- return new NativeBigInt(this.value / parseValue(v).value);
8257
- };
8258
- SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;
8259
-
8260
- BigInteger.prototype.mod = function (v) {
8261
- return divModAny(this, v)[1];
8262
- };
8263
- NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) {
8264
- return new NativeBigInt(this.value % parseValue(v).value);
8265
- };
8266
- SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;
8267
-
8268
- BigInteger.prototype.pow = function (v) {
8269
- var n = parseValue(v),
8270
- a = this.value,
8271
- b = n.value,
8272
- value, x, y;
8273
- if (b === 0) return Integer[1];
8274
- if (a === 0) return Integer[0];
8275
- if (a === 1) return Integer[1];
8276
- if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];
8277
- if (n.sign) {
8278
- return Integer[0];
8279
- }
8280
- if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large.");
8281
- if (this.isSmall) {
8282
- if (isPrecise(value = Math.pow(a, b)))
8283
- return new SmallInteger(truncate(value));
8284
- }
8285
- x = this;
8286
- y = Integer[1];
8287
- while (true) {
8288
- if (b & 1 === 1) {
8289
- y = y.times(x);
8290
- --b;
8291
- }
8292
- if (b === 0) break;
8293
- b /= 2;
8294
- x = x.square();
8295
- }
8296
- return y;
8297
- };
8298
- SmallInteger.prototype.pow = BigInteger.prototype.pow;
8299
-
8300
- NativeBigInt.prototype.pow = function (v) {
8301
- var n = parseValue(v);
8302
- var a = this.value, b = n.value;
8303
- var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2);
8304
- if (b === _0) return Integer[1];
8305
- if (a === _0) return Integer[0];
8306
- if (a === _1) return Integer[1];
8307
- if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];
8308
- if (n.isNegative()) return new NativeBigInt(_0);
8309
- var x = this;
8310
- var y = Integer[1];
8311
- while (true) {
8312
- if ((b & _1) === _1) {
8313
- y = y.times(x);
8314
- --b;
8315
- }
8316
- if (b === _0) break;
8317
- b /= _2;
8318
- x = x.square();
8319
- }
8320
- return y;
8321
- };
8322
-
8323
- BigInteger.prototype.modPow = function (exp, mod) {
8324
- exp = parseValue(exp);
8325
- mod = parseValue(mod);
8326
- if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0");
8327
- var r = Integer[1],
8328
- base = this.mod(mod);
8329
- if (exp.isNegative()) {
8330
- exp = exp.multiply(Integer[-1]);
8331
- base = base.modInv(mod);
8332
- }
8333
- while (exp.isPositive()) {
8334
- if (base.isZero()) return Integer[0];
8335
- if (exp.isOdd()) r = r.multiply(base).mod(mod);
8336
- exp = exp.divide(2);
8337
- base = base.square().mod(mod);
8338
- }
8339
- return r;
8340
- };
8341
- NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;
8342
-
8343
- function compareAbs(a, b) {
8344
- if (a.length !== b.length) {
8345
- return a.length > b.length ? 1 : -1;
8346
- }
8347
- for (var i = a.length - 1; i >= 0; i--) {
8348
- if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;
8349
- }
8350
- return 0;
8351
- }
8352
-
8353
- BigInteger.prototype.compareAbs = function (v) {
8354
- var n = parseValue(v),
8355
- a = this.value,
8356
- b = n.value;
8357
- if (n.isSmall) return 1;
8358
- return compareAbs(a, b);
8359
- };
8360
- SmallInteger.prototype.compareAbs = function (v) {
8361
- var n = parseValue(v),
8362
- a = Math.abs(this.value),
8363
- b = n.value;
8364
- if (n.isSmall) {
8365
- b = Math.abs(b);
8366
- return a === b ? 0 : a > b ? 1 : -1;
8367
- }
8368
- return -1;
8369
- };
8370
- NativeBigInt.prototype.compareAbs = function (v) {
8371
- var a = this.value;
8372
- var b = parseValue(v).value;
8373
- a = a >= 0 ? a : -a;
8374
- b = b >= 0 ? b : -b;
8375
- return a === b ? 0 : a > b ? 1 : -1;
8376
- };
8377
-
8378
- BigInteger.prototype.compare = function (v) {
8379
- // See discussion about comparison with Infinity:
8380
- // https://github.com/peterolson/BigInteger.js/issues/61
8381
- if (v === Infinity) {
8382
- return -1;
8383
- }
8384
- if (v === -Infinity) {
8385
- return 1;
8386
- }
8387
-
8388
- var n = parseValue(v),
8389
- a = this.value,
8390
- b = n.value;
8391
- if (this.sign !== n.sign) {
8392
- return n.sign ? 1 : -1;
8393
- }
8394
- if (n.isSmall) {
8395
- return this.sign ? -1 : 1;
8396
- }
8397
- return compareAbs(a, b) * (this.sign ? -1 : 1);
8398
- };
8399
- BigInteger.prototype.compareTo = BigInteger.prototype.compare;
8400
-
8401
- SmallInteger.prototype.compare = function (v) {
8402
- if (v === Infinity) {
8403
- return -1;
8404
- }
8405
- if (v === -Infinity) {
8406
- return 1;
8407
- }
8408
-
8409
- var n = parseValue(v),
8410
- a = this.value,
8411
- b = n.value;
8412
- if (n.isSmall) {
8413
- return a == b ? 0 : a > b ? 1 : -1;
8414
- }
8415
- if (a < 0 !== n.sign) {
8416
- return a < 0 ? -1 : 1;
8417
- }
8418
- return a < 0 ? 1 : -1;
8419
- };
8420
- SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;
8421
-
8422
- NativeBigInt.prototype.compare = function (v) {
8423
- if (v === Infinity) {
8424
- return -1;
8425
- }
8426
- if (v === -Infinity) {
8427
- return 1;
8428
- }
8429
- var a = this.value;
8430
- var b = parseValue(v).value;
8431
- return a === b ? 0 : a > b ? 1 : -1;
8432
- };
8433
- NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;
8434
-
8435
- BigInteger.prototype.equals = function (v) {
8436
- return this.compare(v) === 0;
8437
- };
8438
- NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;
8439
-
8440
- BigInteger.prototype.notEquals = function (v) {
8441
- return this.compare(v) !== 0;
8442
- };
8443
- NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;
8444
-
8445
- BigInteger.prototype.greater = function (v) {
8446
- return this.compare(v) > 0;
8447
- };
8448
- NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;
8449
-
8450
- BigInteger.prototype.lesser = function (v) {
8451
- return this.compare(v) < 0;
8452
- };
8453
- NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;
8454
-
8455
- BigInteger.prototype.greaterOrEquals = function (v) {
8456
- return this.compare(v) >= 0;
8457
- };
8458
- NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;
8459
-
8460
- BigInteger.prototype.lesserOrEquals = function (v) {
8461
- return this.compare(v) <= 0;
8462
- };
8463
- NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;
8464
-
8465
- BigInteger.prototype.isEven = function () {
8466
- return (this.value[0] & 1) === 0;
8467
- };
8468
- SmallInteger.prototype.isEven = function () {
8469
- return (this.value & 1) === 0;
8470
- };
8471
- NativeBigInt.prototype.isEven = function () {
8472
- return (this.value & BigInt(1)) === BigInt(0);
8473
- };
8474
-
8475
- BigInteger.prototype.isOdd = function () {
8476
- return (this.value[0] & 1) === 1;
8477
- };
8478
- SmallInteger.prototype.isOdd = function () {
8479
- return (this.value & 1) === 1;
8480
- };
8481
- NativeBigInt.prototype.isOdd = function () {
8482
- return (this.value & BigInt(1)) === BigInt(1);
8483
- };
8484
-
8485
- BigInteger.prototype.isPositive = function () {
8486
- return !this.sign;
8487
- };
8488
- SmallInteger.prototype.isPositive = function () {
8489
- return this.value > 0;
8490
- };
8491
- NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;
8492
-
8493
- BigInteger.prototype.isNegative = function () {
8494
- return this.sign;
8495
- };
8496
- SmallInteger.prototype.isNegative = function () {
8497
- return this.value < 0;
8498
- };
8499
- NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;
8500
-
8501
- BigInteger.prototype.isUnit = function () {
8502
- return false;
8503
- };
8504
- SmallInteger.prototype.isUnit = function () {
8505
- return Math.abs(this.value) === 1;
8506
- };
8507
- NativeBigInt.prototype.isUnit = function () {
8508
- return this.abs().value === BigInt(1);
8509
- };
8510
-
8511
- BigInteger.prototype.isZero = function () {
8512
- return false;
8513
- };
8514
- SmallInteger.prototype.isZero = function () {
8515
- return this.value === 0;
8516
- };
8517
- NativeBigInt.prototype.isZero = function () {
8518
- return this.value === BigInt(0);
8519
- };
8520
-
8521
- BigInteger.prototype.isDivisibleBy = function (v) {
8522
- var n = parseValue(v);
8523
- if (n.isZero()) return false;
8524
- if (n.isUnit()) return true;
8525
- if (n.compareAbs(2) === 0) return this.isEven();
8526
- return this.mod(n).isZero();
8527
- };
8528
- NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;
8529
-
8530
- function isBasicPrime(v) {
8531
- var n = v.abs();
8532
- if (n.isUnit()) return false;
8533
- if (n.equals(2) || n.equals(3) || n.equals(5)) return true;
8534
- if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;
8535
- if (n.lesser(49)) return true;
8536
- // we don't know if it's prime: let the other functions figure it out
8537
- }
8538
-
8539
- function millerRabinTest(n, a) {
8540
- var nPrev = n.prev(),
8541
- b = nPrev,
8542
- r = 0,
8543
- d, i, x;
8544
- while (b.isEven()) b = b.divide(2), r++;
8545
- next: for (i = 0; i < a.length; i++) {
8546
- if (n.lesser(a[i])) continue;
8547
- x = bigInt(a[i]).modPow(b, n);
8548
- if (x.isUnit() || x.equals(nPrev)) continue;
8549
- for (d = r - 1; d != 0; d--) {
8550
- x = x.square().mod(n);
8551
- if (x.isUnit()) return false;
8552
- if (x.equals(nPrev)) continue next;
8553
- }
8554
- return false;
8555
- }
8556
- return true;
8557
- }
8558
-
8559
- // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2
8560
- BigInteger.prototype.isPrime = function (strict) {
8561
- var isPrime = isBasicPrime(this);
8562
- if (isPrime !== undefined$1) return isPrime;
8563
- var n = this.abs();
8564
- var bits = n.bitLength();
8565
- if (bits <= 64)
8566
- return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);
8567
- var logN = Math.log(2) * bits.toJSNumber();
8568
- var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);
8569
- for (var a = [], i = 0; i < t; i++) {
8570
- a.push(bigInt(i + 2));
8571
- }
8572
- return millerRabinTest(n, a);
8573
- };
8574
- NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;
8575
-
8576
- BigInteger.prototype.isProbablePrime = function (iterations, rng) {
8577
- var isPrime = isBasicPrime(this);
8578
- if (isPrime !== undefined$1) return isPrime;
8579
- var n = this.abs();
8580
- var t = iterations === undefined$1 ? 5 : iterations;
8581
- for (var a = [], i = 0; i < t; i++) {
8582
- a.push(bigInt.randBetween(2, n.minus(2), rng));
8583
- }
8584
- return millerRabinTest(n, a);
8585
- };
8586
- NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;
8587
-
8588
- BigInteger.prototype.modInv = function (n) {
8589
- var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;
8590
- while (!newR.isZero()) {
8591
- q = r.divide(newR);
8592
- lastT = t;
8593
- lastR = r;
8594
- t = newT;
8595
- r = newR;
8596
- newT = lastT.subtract(q.multiply(newT));
8597
- newR = lastR.subtract(q.multiply(newR));
8598
- }
8599
- if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime");
8600
- if (t.compare(0) === -1) {
8601
- t = t.add(n);
8602
- }
8603
- if (this.isNegative()) {
8604
- return t.negate();
8605
- }
8606
- return t;
8607
- };
8608
-
8609
- NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;
8610
-
8611
- BigInteger.prototype.next = function () {
8612
- var value = this.value;
8613
- if (this.sign) {
8614
- return subtractSmall(value, 1, this.sign);
8615
- }
8616
- return new BigInteger(addSmall(value, 1), this.sign);
8617
- };
8618
- SmallInteger.prototype.next = function () {
8619
- var value = this.value;
8620
- if (value + 1 < MAX_INT) return new SmallInteger(value + 1);
8621
- return new BigInteger(MAX_INT_ARR, false);
8622
- };
8623
- NativeBigInt.prototype.next = function () {
8624
- return new NativeBigInt(this.value + BigInt(1));
8625
- };
8626
-
8627
- BigInteger.prototype.prev = function () {
8628
- var value = this.value;
8629
- if (this.sign) {
8630
- return new BigInteger(addSmall(value, 1), true);
8631
- }
8632
- return subtractSmall(value, 1, this.sign);
8633
- };
8634
- SmallInteger.prototype.prev = function () {
8635
- var value = this.value;
8636
- if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);
8637
- return new BigInteger(MAX_INT_ARR, true);
8638
- };
8639
- NativeBigInt.prototype.prev = function () {
8640
- return new NativeBigInt(this.value - BigInt(1));
8641
- };
8642
-
8643
- var powersOfTwo = [1];
8644
- while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);
8645
- var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];
8646
-
8647
- function shift_isSmall(n) {
8648
- return Math.abs(n) <= BASE;
8649
- }
8650
-
8651
- BigInteger.prototype.shiftLeft = function (v) {
8652
- var n = parseValue(v).toJSNumber();
8653
- if (!shift_isSmall(n)) {
8654
- throw new Error(String(n) + " is too large for shifting.");
8655
- }
8656
- if (n < 0) return this.shiftRight(-n);
8657
- var result = this;
8658
- if (result.isZero()) return result;
8659
- while (n >= powers2Length) {
8660
- result = result.multiply(highestPower2);
8661
- n -= powers2Length - 1;
8662
- }
8663
- return result.multiply(powersOfTwo[n]);
8664
- };
8665
- NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;
8666
-
8667
- BigInteger.prototype.shiftRight = function (v) {
8668
- var remQuo;
8669
- var n = parseValue(v).toJSNumber();
8670
- if (!shift_isSmall(n)) {
8671
- throw new Error(String(n) + " is too large for shifting.");
8672
- }
8673
- if (n < 0) return this.shiftLeft(-n);
8674
- var result = this;
8675
- while (n >= powers2Length) {
8676
- if (result.isZero() || (result.isNegative() && result.isUnit())) return result;
8677
- remQuo = divModAny(result, highestPower2);
8678
- result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
8679
- n -= powers2Length - 1;
8680
- }
8681
- remQuo = divModAny(result, powersOfTwo[n]);
8682
- return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
8683
- };
8684
- NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;
8685
-
8686
- function bitwise(x, y, fn) {
8687
- y = parseValue(y);
8688
- var xSign = x.isNegative(), ySign = y.isNegative();
8689
- var xRem = xSign ? x.not() : x,
8690
- yRem = ySign ? y.not() : y;
8691
- var xDigit = 0, yDigit = 0;
8692
- var xDivMod = null, yDivMod = null;
8693
- var result = [];
8694
- while (!xRem.isZero() || !yRem.isZero()) {
8695
- xDivMod = divModAny(xRem, highestPower2);
8696
- xDigit = xDivMod[1].toJSNumber();
8697
- if (xSign) {
8698
- xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers
8699
- }
8700
-
8701
- yDivMod = divModAny(yRem, highestPower2);
8702
- yDigit = yDivMod[1].toJSNumber();
8703
- if (ySign) {
8704
- yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers
8705
- }
8706
-
8707
- xRem = xDivMod[0];
8708
- yRem = yDivMod[0];
8709
- result.push(fn(xDigit, yDigit));
8710
- }
8711
- var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);
8712
- for (var i = result.length - 1; i >= 0; i -= 1) {
8713
- sum = sum.multiply(highestPower2).add(bigInt(result[i]));
8714
- }
8715
- return sum;
8716
- }
8717
-
8718
- BigInteger.prototype.not = function () {
8719
- return this.negate().prev();
8720
- };
8721
- NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;
8722
-
8723
- BigInteger.prototype.and = function (n) {
8724
- return bitwise(this, n, function (a, b) { return a & b; });
8725
- };
8726
- NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;
8727
-
8728
- BigInteger.prototype.or = function (n) {
8729
- return bitwise(this, n, function (a, b) { return a | b; });
8730
- };
8731
- NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;
8732
-
8733
- BigInteger.prototype.xor = function (n) {
8734
- return bitwise(this, n, function (a, b) { return a ^ b; });
8735
- };
8736
- NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;
8737
-
8738
- var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;
8739
- function roughLOB(n) { // get lowestOneBit (rough)
8740
- // SmallInteger: return Min(lowestOneBit(n), 1 << 30)
8741
- // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]
8742
- var v = n.value,
8743
- x = typeof v === "number" ? v | LOBMASK_I :
8744
- typeof v === "bigint" ? v | BigInt(LOBMASK_I) :
8745
- v[0] + v[1] * BASE | LOBMASK_BI;
8746
- return x & -x;
8747
- }
8748
-
8749
- function integerLogarithm(value, base) {
8750
- if (base.compareTo(value) <= 0) {
8751
- var tmp = integerLogarithm(value, base.square(base));
8752
- var p = tmp.p;
8753
- var e = tmp.e;
8754
- var t = p.multiply(base);
8755
- return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };
8756
- }
8757
- return { p: bigInt(1), e: 0 };
8758
- }
8759
-
8760
- BigInteger.prototype.bitLength = function () {
8761
- var n = this;
8762
- if (n.compareTo(bigInt(0)) < 0) {
8763
- n = n.negate().subtract(bigInt(1));
8764
- }
8765
- if (n.compareTo(bigInt(0)) === 0) {
8766
- return bigInt(0);
8767
- }
8768
- return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));
8769
- };
8770
- NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;
8771
-
8772
- function max(a, b) {
8773
- a = parseValue(a);
8774
- b = parseValue(b);
8775
- return a.greater(b) ? a : b;
8776
- }
8777
- function min(a, b) {
8778
- a = parseValue(a);
8779
- b = parseValue(b);
8780
- return a.lesser(b) ? a : b;
8781
- }
8782
- function gcd(a, b) {
8783
- a = parseValue(a).abs();
8784
- b = parseValue(b).abs();
8785
- if (a.equals(b)) return a;
8786
- if (a.isZero()) return b;
8787
- if (b.isZero()) return a;
8788
- var c = Integer[1], d, t;
8789
- while (a.isEven() && b.isEven()) {
8790
- d = min(roughLOB(a), roughLOB(b));
8791
- a = a.divide(d);
8792
- b = b.divide(d);
8793
- c = c.multiply(d);
8794
- }
8795
- while (a.isEven()) {
8796
- a = a.divide(roughLOB(a));
8797
- }
8798
- do {
8799
- while (b.isEven()) {
8800
- b = b.divide(roughLOB(b));
8801
- }
8802
- if (a.greater(b)) {
8803
- t = b; b = a; a = t;
8804
- }
8805
- b = b.subtract(a);
8806
- } while (!b.isZero());
8807
- return c.isUnit() ? a : a.multiply(c);
8808
- }
8809
- function lcm(a, b) {
8810
- a = parseValue(a).abs();
8811
- b = parseValue(b).abs();
8812
- return a.divide(gcd(a, b)).multiply(b);
8813
- }
8814
- function randBetween(a, b, rng) {
8815
- a = parseValue(a);
8816
- b = parseValue(b);
8817
- var usedRNG = rng || Math.random;
8818
- var low = min(a, b), high = max(a, b);
8819
- var range = high.subtract(low).add(1);
8820
- if (range.isSmall) return low.add(Math.floor(usedRNG() * range));
8821
- var digits = toBase(range, BASE).value;
8822
- var result = [], restricted = true;
8823
- for (var i = 0; i < digits.length; i++) {
8824
- var top = restricted ? digits[i] + (i + 1 < digits.length ? digits[i + 1] / BASE : 0) : BASE;
8825
- var digit = truncate(usedRNG() * top);
8826
- result.push(digit);
8827
- if (digit < digits[i]) restricted = false;
8828
- }
8829
- return low.add(Integer.fromArray(result, BASE, false));
8830
- }
8831
-
8832
- var parseBase = function (text, base, alphabet, caseSensitive) {
8833
- alphabet = alphabet || DEFAULT_ALPHABET;
8834
- text = String(text);
8835
- if (!caseSensitive) {
8836
- text = text.toLowerCase();
8837
- alphabet = alphabet.toLowerCase();
8838
- }
8839
- var length = text.length;
8840
- var i;
8841
- var absBase = Math.abs(base);
8842
- var alphabetValues = {};
8843
- for (i = 0; i < alphabet.length; i++) {
8844
- alphabetValues[alphabet[i]] = i;
8845
- }
8846
- for (i = 0; i < length; i++) {
8847
- var c = text[i];
8848
- if (c === "-") continue;
8849
- if (c in alphabetValues) {
8850
- if (alphabetValues[c] >= absBase) {
8851
- if (c === "1" && absBase === 1) continue;
8852
- throw new Error(c + " is not a valid digit in base " + base + ".");
8853
- }
8854
- }
8855
- }
8856
- base = parseValue(base);
8857
- var digits = [];
8858
- var isNegative = text[0] === "-";
8859
- for (i = isNegative ? 1 : 0; i < text.length; i++) {
8860
- var c = text[i];
8861
- if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));
8862
- else if (c === "<") {
8863
- var start = i;
8864
- do { i++; } while (text[i] !== ">" && i < text.length);
8865
- digits.push(parseValue(text.slice(start + 1, i)));
8866
- }
8867
- else throw new Error(c + " is not a valid character");
8868
- }
8869
- return parseBaseFromArray(digits, base, isNegative);
8870
- };
8871
-
8872
- function parseBaseFromArray(digits, base, isNegative) {
8873
- var val = Integer[0], pow = Integer[1], i;
8874
- for (i = digits.length - 1; i >= 0; i--) {
8875
- val = val.add(digits[i].times(pow));
8876
- pow = pow.times(base);
8877
- }
8878
- return isNegative ? val.negate() : val;
8879
- }
8880
-
8881
- function stringify(digit, alphabet) {
8882
- alphabet = alphabet || DEFAULT_ALPHABET;
8883
- if (digit < alphabet.length) {
8884
- return alphabet[digit];
8885
- }
8886
- return "<" + digit + ">";
8887
- }
8888
-
8889
- function toBase(n, base) {
8890
- base = bigInt(base);
8891
- if (base.isZero()) {
8892
- if (n.isZero()) return { value: [0], isNegative: false };
8893
- throw new Error("Cannot convert nonzero numbers to base 0.");
8894
- }
8895
- if (base.equals(-1)) {
8896
- if (n.isZero()) return { value: [0], isNegative: false };
8897
- if (n.isNegative())
8898
- return {
8899
- value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber()))
8900
- .map(Array.prototype.valueOf, [1, 0])
8901
- ),
8902
- isNegative: false
8903
- };
8904
-
8905
- var arr = Array.apply(null, Array(n.toJSNumber() - 1))
8906
- .map(Array.prototype.valueOf, [0, 1]);
8907
- arr.unshift([1]);
8908
- return {
8909
- value: [].concat.apply([], arr),
8910
- isNegative: false
8911
- };
8912
- }
8913
-
8914
- var neg = false;
8915
- if (n.isNegative() && base.isPositive()) {
8916
- neg = true;
8917
- n = n.abs();
8918
- }
8919
- if (base.isUnit()) {
8920
- if (n.isZero()) return { value: [0], isNegative: false };
8921
-
8922
- return {
8923
- value: Array.apply(null, Array(n.toJSNumber()))
8924
- .map(Number.prototype.valueOf, 1),
8925
- isNegative: neg
8926
- };
8927
- }
8928
- var out = [];
8929
- var left = n, divmod;
8930
- while (left.isNegative() || left.compareAbs(base) >= 0) {
8931
- divmod = left.divmod(base);
8932
- left = divmod.quotient;
8933
- var digit = divmod.remainder;
8934
- if (digit.isNegative()) {
8935
- digit = base.minus(digit).abs();
8936
- left = left.next();
8937
- }
8938
- out.push(digit.toJSNumber());
8939
- }
8940
- out.push(left.toJSNumber());
8941
- return { value: out.reverse(), isNegative: neg };
8942
- }
8943
-
8944
- function toBaseString(n, base, alphabet) {
8945
- var arr = toBase(n, base);
8946
- return (arr.isNegative ? "-" : "") + arr.value.map(function (x) {
8947
- return stringify(x, alphabet);
8948
- }).join('');
8949
- }
8950
-
8951
- BigInteger.prototype.toArray = function (radix) {
8952
- return toBase(this, radix);
8953
- };
8954
-
8955
- SmallInteger.prototype.toArray = function (radix) {
8956
- return toBase(this, radix);
8957
- };
8958
-
8959
- NativeBigInt.prototype.toArray = function (radix) {
8960
- return toBase(this, radix);
8961
- };
8962
-
8963
- BigInteger.prototype.toString = function (radix, alphabet) {
8964
- if (radix === undefined$1) radix = 10;
8965
- if (radix !== 10) return toBaseString(this, radix, alphabet);
8966
- var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit;
8967
- while (--l >= 0) {
8968
- digit = String(v[l]);
8969
- str += zeros.slice(digit.length) + digit;
8970
- }
8971
- var sign = this.sign ? "-" : "";
8972
- return sign + str;
8973
- };
8974
-
8975
- SmallInteger.prototype.toString = function (radix, alphabet) {
8976
- if (radix === undefined$1) radix = 10;
8977
- if (radix != 10) return toBaseString(this, radix, alphabet);
8978
- return String(this.value);
8979
- };
8980
-
8981
- NativeBigInt.prototype.toString = SmallInteger.prototype.toString;
8982
-
8983
- NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); };
8984
-
8985
- BigInteger.prototype.valueOf = function () {
8986
- return parseInt(this.toString(), 10);
8987
- };
8988
- BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;
8989
-
8990
- SmallInteger.prototype.valueOf = function () {
8991
- return this.value;
8992
- };
8993
- SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;
8994
- NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () {
8995
- return parseInt(this.toString(), 10);
8996
- };
8997
-
8998
- function parseStringValue(v) {
8999
- if (isPrecise(+v)) {
9000
- var x = +v;
9001
- if (x === truncate(x))
9002
- return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x);
9003
- throw new Error("Invalid integer: " + v);
9004
- }
9005
- var sign = v[0] === "-";
9006
- if (sign) v = v.slice(1);
9007
- var split = v.split(/e/i);
9008
- if (split.length > 2) throw new Error("Invalid integer: " + split.join("e"));
9009
- if (split.length === 2) {
9010
- var exp = split[1];
9011
- if (exp[0] === "+") exp = exp.slice(1);
9012
- exp = +exp;
9013
- if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent.");
9014
- var text = split[0];
9015
- var decimalPlace = text.indexOf(".");
9016
- if (decimalPlace >= 0) {
9017
- exp -= text.length - decimalPlace - 1;
9018
- text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);
9019
- }
9020
- if (exp < 0) throw new Error("Cannot include negative exponent part for integers");
9021
- text += (new Array(exp + 1)).join("0");
9022
- v = text;
9023
- }
9024
- var isValid = /^([0-9][0-9]*)$/.test(v);
9025
- if (!isValid) throw new Error("Invalid integer: " + v);
9026
- if (supportsNativeBigInt) {
9027
- return new NativeBigInt(BigInt(sign ? "-" + v : v));
9028
- }
9029
- var r = [], max = v.length, l = LOG_BASE, min = max - l;
9030
- while (max > 0) {
9031
- r.push(+v.slice(min, max));
9032
- min -= l;
9033
- if (min < 0) min = 0;
9034
- max -= l;
9035
- }
9036
- trim(r);
9037
- return new BigInteger(r, sign);
9038
- }
9039
-
9040
- function parseNumberValue(v) {
9041
- if (supportsNativeBigInt) {
9042
- return new NativeBigInt(BigInt(v));
9043
- }
9044
- if (isPrecise(v)) {
9045
- if (v !== truncate(v)) throw new Error(v + " is not an integer.");
9046
- return new SmallInteger(v);
9047
- }
9048
- return parseStringValue(v.toString());
9049
- }
9050
-
9051
- function parseValue(v) {
9052
- if (typeof v === "number") {
9053
- return parseNumberValue(v);
9054
- }
9055
- if (typeof v === "string") {
9056
- return parseStringValue(v);
9057
- }
9058
- if (typeof v === "bigint") {
9059
- return new NativeBigInt(v);
9060
- }
9061
- return v;
9062
- }
9063
- // Pre-define numbers in range [-999,999]
9064
- for (var i = 0; i < 1000; i++) {
9065
- Integer[i] = parseValue(i);
9066
- if (i > 0) Integer[-i] = parseValue(-i);
9067
- }
9068
- // Backwards compatibility
9069
- Integer.one = Integer[1];
9070
- Integer.zero = Integer[0];
9071
- Integer.minusOne = Integer[-1];
9072
- Integer.max = max;
9073
- Integer.min = min;
9074
- Integer.gcd = gcd;
9075
- Integer.lcm = lcm;
9076
- Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; };
9077
- Integer.randBetween = randBetween;
9078
-
9079
- Integer.fromArray = function (digits, base, isNegative) {
9080
- return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);
9081
- };
9082
-
9083
- return Integer;
9084
- })();
9085
-
9086
- // Node.js check
9087
- if (module.hasOwnProperty("exports")) {
9088
- module.exports = bigInt;
9089
- }
9090
- } (BigInteger));
9091
- return BigInteger.exports;
9092
- }
9093
-
9094
- var hasRequiredBplistParser;
9095
-
9096
- function requireBplistParser () {
9097
- if (hasRequiredBplistParser) return bplistParser;
9098
- hasRequiredBplistParser = 1;
9099
- (function (exports) {
9100
-
9101
- // adapted from http://code.google.com/p/plist/source/browse/trunk/src/com/dd/plist/BinaryPropertyListParser.java
9102
-
9103
- var fs = require$$0$3;
9104
- var bigInt = requireBigInteger();
9105
-
9106
- exports.maxObjectSize = 100 * 1000 * 1000; // 100Meg
9107
- exports.maxObjectCount = 32768;
9108
-
9109
- // EPOCH = new SimpleDateFormat("yyyy MM dd zzz").parse("2001 01 01 GMT").getTime();
9110
- // ...but that's annoying in a static initializer because it can throw exceptions, ick.
9111
- // So we just hardcode the correct value.
9112
- var EPOCH = 978307200000;
9113
-
9114
- // UID object definition
9115
- var UID = exports.UID = function(id) {
9116
- this.UID = id;
9117
- };
9118
-
9119
- exports.parseFile = function (fileNameOrBuffer, callback) {
9120
- function tryParseBuffer(buffer) {
9121
- var err = null;
9122
- var result;
9123
- try {
9124
- result = parseBuffer(buffer);
9125
- } catch (ex) {
9126
- err = ex;
9127
- }
9128
- callback(err, result);
9129
- }
9130
-
9131
- if (Buffer.isBuffer(fileNameOrBuffer)) {
9132
- return tryParseBuffer(fileNameOrBuffer);
9133
- } else {
9134
- fs.readFile(fileNameOrBuffer, function (err, data) {
9135
- if (err) { return callback(err); }
9136
- tryParseBuffer(data);
9137
- });
9138
- }
9139
- };
9140
-
9141
- var parseBuffer = exports.parseBuffer = function (buffer) {
9142
-
9143
- // check header
9144
- var header = buffer.slice(0, 'bplist'.length).toString('utf8');
9145
- if (header !== 'bplist') {
9146
- throw new Error("Invalid binary plist. Expected 'bplist' at offset 0.");
9147
- }
9148
-
9149
- // Handle trailer, last 32 bytes of the file
9150
- var trailer = buffer.slice(buffer.length - 32, buffer.length);
9151
- // 6 null bytes (index 0 to 5)
9152
- var offsetSize = trailer.readUInt8(6);
9153
- var objectRefSize = trailer.readUInt8(7);
9154
- var numObjects = readUInt64BE(trailer, 8);
9155
- var topObject = readUInt64BE(trailer, 16);
9156
- var offsetTableOffset = readUInt64BE(trailer, 24);
9157
-
9158
- if (numObjects > exports.maxObjectCount) {
9159
- throw new Error("maxObjectCount exceeded");
9160
- }
9161
-
9162
- // Handle offset table
9163
- var offsetTable = [];
9164
-
9165
- for (var i = 0; i < numObjects; i++) {
9166
- var offsetBytes = buffer.slice(offsetTableOffset + i * offsetSize, offsetTableOffset + (i + 1) * offsetSize);
9167
- offsetTable[i] = readUInt(offsetBytes, 0);
9168
- }
9169
-
9170
- // Parses an object inside the currently parsed binary property list.
9171
- // For the format specification check
9172
- // <a href="http://www.opensource.apple.com/source/CF/CF-635/CFBinaryPList.c">
9173
- // Apple's binary property list parser implementation</a>.
9174
- function parseObject(tableOffset) {
9175
- var offset = offsetTable[tableOffset];
9176
- var type = buffer[offset];
9177
- var objType = (type & 0xF0) >> 4; //First 4 bits
9178
- var objInfo = (type & 0x0F); //Second 4 bits
9179
- switch (objType) {
9180
- case 0x0:
9181
- return parseSimple();
9182
- case 0x1:
9183
- return parseInteger();
9184
- case 0x8:
9185
- return parseUID();
9186
- case 0x2:
9187
- return parseReal();
9188
- case 0x3:
9189
- return parseDate();
9190
- case 0x4:
9191
- return parseData();
9192
- case 0x5: // ASCII
9193
- return parsePlistString();
9194
- case 0x6: // UTF-16
9195
- return parsePlistString(true);
9196
- case 0xA:
9197
- return parseArray();
9198
- case 0xD:
9199
- return parseDictionary();
9200
- default:
9201
- throw new Error("Unhandled type 0x" + objType.toString(16));
9202
- }
9203
-
9204
- function parseSimple() {
9205
- //Simple
9206
- switch (objInfo) {
9207
- case 0x0: // null
9208
- return null;
9209
- case 0x8: // false
9210
- return false;
9211
- case 0x9: // true
9212
- return true;
9213
- case 0xF: // filler byte
9214
- return null;
9215
- default:
9216
- throw new Error("Unhandled simple type 0x" + objType.toString(16));
9217
- }
9218
- }
9219
-
9220
- function bufferToHexString(buffer) {
9221
- var str = '';
9222
- var i;
9223
- for (i = 0; i < buffer.length; i++) {
9224
- if (buffer[i] != 0x00) {
9225
- break;
9226
- }
9227
- }
9228
- for (; i < buffer.length; i++) {
9229
- var part = '00' + buffer[i].toString(16);
9230
- str += part.substr(part.length - 2);
9231
- }
9232
- return str;
9233
- }
9234
-
9235
- function parseInteger() {
9236
- var length = Math.pow(2, objInfo);
9237
- if (length > 4) {
9238
- var data = buffer.slice(offset + 1, offset + 1 + length);
9239
- var str = bufferToHexString(data);
9240
- return bigInt(str, 16);
9241
- } if (length < exports.maxObjectSize) {
9242
- return readUInt(buffer.slice(offset + 1, offset + 1 + length));
9243
- } else {
9244
- throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
9245
- }
9246
- }
9247
-
9248
- function parseUID() {
9249
- var length = objInfo + 1;
9250
- if (length < exports.maxObjectSize) {
9251
- return new UID(readUInt(buffer.slice(offset + 1, offset + 1 + length)));
9252
- } else {
9253
- throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
9254
- }
9255
- }
9256
-
9257
- function parseReal() {
9258
- var length = Math.pow(2, objInfo);
9259
- if (length < exports.maxObjectSize) {
9260
- var realBuffer = buffer.slice(offset + 1, offset + 1 + length);
9261
- if (length === 4) {
9262
- return realBuffer.readFloatBE(0);
9263
- }
9264
- else if (length === 8) {
9265
- return realBuffer.readDoubleBE(0);
9266
- }
9267
- } else {
9268
- throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
9269
- }
9270
- }
9271
-
9272
- function parseDate() {
9273
- if (objInfo != 0x3) {
9274
- console.error("Unknown date type :" + objInfo + ". Parsing anyway...");
9275
- }
9276
- var dateBuffer = buffer.slice(offset + 1, offset + 9);
9277
- return new Date(EPOCH + (1000 * dateBuffer.readDoubleBE(0)));
9278
- }
9279
-
9280
- function parseData() {
9281
- var dataoffset = 1;
9282
- var length = objInfo;
9283
- if (objInfo == 0xF) {
9284
- var int_type = buffer[offset + 1];
9285
- var intType = (int_type & 0xF0) / 0x10;
9286
- if (intType != 0x1) {
9287
- console.error("0x4: UNEXPECTED LENGTH-INT TYPE! " + intType);
9288
- }
9289
- var intInfo = int_type & 0x0F;
9290
- var intLength = Math.pow(2, intInfo);
9291
- dataoffset = 2 + intLength;
9292
- if (intLength < 3) {
9293
- length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
9294
- } else {
9295
- length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
9296
- }
9297
- }
9298
- if (length < exports.maxObjectSize) {
9299
- return buffer.slice(offset + dataoffset, offset + dataoffset + length);
9300
- } else {
9301
- throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
9302
- }
9303
- }
9304
-
9305
- function parsePlistString (isUtf16) {
9306
- isUtf16 = isUtf16 || 0;
9307
- var enc = "utf8";
9308
- var length = objInfo;
9309
- var stroffset = 1;
9310
- if (objInfo == 0xF) {
9311
- var int_type = buffer[offset + 1];
9312
- var intType = (int_type & 0xF0) / 0x10;
9313
- if (intType != 0x1) {
9314
- console.err("UNEXPECTED LENGTH-INT TYPE! " + intType);
9315
- }
9316
- var intInfo = int_type & 0x0F;
9317
- var intLength = Math.pow(2, intInfo);
9318
- var stroffset = 2 + intLength;
9319
- if (intLength < 3) {
9320
- length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
9321
- } else {
9322
- length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
9323
- }
9324
- }
9325
- // length is String length -> to get byte length multiply by 2, as 1 character takes 2 bytes in UTF-16
9326
- length *= (isUtf16 + 1);
9327
- if (length < exports.maxObjectSize) {
9328
- var plistString = new Buffer(buffer.slice(offset + stroffset, offset + stroffset + length));
9329
- if (isUtf16) {
9330
- plistString = swapBytes(plistString);
9331
- enc = "ucs2";
9332
- }
9333
- return plistString.toString(enc);
9334
- } else {
9335
- throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
9336
- }
9337
- }
9338
-
9339
- function parseArray() {
9340
- var length = objInfo;
9341
- var arrayoffset = 1;
9342
- if (objInfo == 0xF) {
9343
- var int_type = buffer[offset + 1];
9344
- var intType = (int_type & 0xF0) / 0x10;
9345
- if (intType != 0x1) {
9346
- console.error("0xa: UNEXPECTED LENGTH-INT TYPE! " + intType);
9347
- }
9348
- var intInfo = int_type & 0x0F;
9349
- var intLength = Math.pow(2, intInfo);
9350
- arrayoffset = 2 + intLength;
9351
- if (intLength < 3) {
9352
- length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
9353
- } else {
9354
- length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
9355
- }
9356
- }
9357
- if (length * objectRefSize > exports.maxObjectSize) {
9358
- throw new Error("To little heap space available!");
9359
- }
9360
- var array = [];
9361
- for (var i = 0; i < length; i++) {
9362
- var objRef = readUInt(buffer.slice(offset + arrayoffset + i * objectRefSize, offset + arrayoffset + (i + 1) * objectRefSize));
9363
- array[i] = parseObject(objRef);
9364
- }
9365
- return array;
9366
- }
9367
-
9368
- function parseDictionary() {
9369
- var length = objInfo;
9370
- var dictoffset = 1;
9371
- if (objInfo == 0xF) {
9372
- var int_type = buffer[offset + 1];
9373
- var intType = (int_type & 0xF0) / 0x10;
9374
- if (intType != 0x1) {
9375
- console.error("0xD: UNEXPECTED LENGTH-INT TYPE! " + intType);
9376
- }
9377
- var intInfo = int_type & 0x0F;
9378
- var intLength = Math.pow(2, intInfo);
9379
- dictoffset = 2 + intLength;
9380
- if (intLength < 3) {
9381
- length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
9382
- } else {
9383
- length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
9384
- }
9385
- }
9386
- if (length * 2 * objectRefSize > exports.maxObjectSize) {
9387
- throw new Error("To little heap space available!");
9388
- }
9389
- var dict = {};
9390
- for (var i = 0; i < length; i++) {
9391
- var keyRef = readUInt(buffer.slice(offset + dictoffset + i * objectRefSize, offset + dictoffset + (i + 1) * objectRefSize));
9392
- var valRef = readUInt(buffer.slice(offset + dictoffset + (length * objectRefSize) + i * objectRefSize, offset + dictoffset + (length * objectRefSize) + (i + 1) * objectRefSize));
9393
- var key = parseObject(keyRef);
9394
- var val = parseObject(valRef);
9395
- dict[key] = val;
9396
- }
9397
- return dict;
9398
- }
9399
- }
9400
-
9401
- return [ parseObject(topObject) ];
9402
- };
9403
-
9404
- function readUInt(buffer, start) {
9405
- start = start || 0;
9406
-
9407
- var l = 0;
9408
- for (var i = start; i < buffer.length; i++) {
9409
- l <<= 8;
9410
- l |= buffer[i] & 0xFF;
9411
- }
9412
- return l;
9413
- }
9414
-
9415
- // we're just going to toss the high order bits because javascript doesn't have 64-bit ints
9416
- function readUInt64BE(buffer, start) {
9417
- var data = buffer.slice(start, start + 8);
9418
- return data.readUInt32BE(4, 8);
9419
- }
9420
-
9421
- function swapBytes(buffer) {
9422
- var len = buffer.length;
9423
- for (var i = 0; i < len; i += 2) {
9424
- var a = buffer[i];
9425
- buffer[i] = buffer[i+1];
9426
- buffer[i+1] = a;
9427
- }
9428
- return buffer;
9429
- }
9430
- } (bplistParser));
9431
- return bplistParser;
9432
- }
9433
-
9434
- var osHomedir;
9435
- var hasRequiredOsHomedir;
9436
-
9437
- function requireOsHomedir () {
9438
- if (hasRequiredOsHomedir) return osHomedir;
9439
- hasRequiredOsHomedir = 1;
9440
- var os = require$$0;
9441
-
9442
- function homedir() {
9443
- var env = process.env;
9444
- var home = env.HOME;
9445
- var user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME;
9446
-
9447
- if (process.platform === 'win32') {
9448
- return env.USERPROFILE || env.HOMEDRIVE + env.HOMEPATH || home || null;
9449
- }
9450
-
9451
- if (process.platform === 'darwin') {
9452
- return home || (user ? '/Users/' + user : null);
9453
- }
9454
-
9455
- if (process.platform === 'linux') {
9456
- return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null));
9457
- }
9458
-
9459
- return home || null;
9460
- }
9461
-
9462
- osHomedir = typeof os.homedir === 'function' ? os.homedir : homedir;
9463
- return osHomedir;
9464
- }
9465
-
9466
- var untildify;
9467
- var hasRequiredUntildify;
9468
-
9469
- function requireUntildify () {
9470
- if (hasRequiredUntildify) return untildify;
9471
- hasRequiredUntildify = 1;
9472
- var osHomedir = requireOsHomedir();
9473
- var home = osHomedir();
9474
-
9475
- untildify = function (str) {
9476
- if (typeof str !== 'string') {
9477
- throw new TypeError('Expected a string');
9478
- }
9479
-
9480
- return home ? str.replace(/^~($|\/|\\)/, home + '$1') : str;
9481
- };
9482
- return untildify;
9483
- }
9484
-
9485
- var pify = {exports: {}};
9486
-
9487
- var hasRequiredPify;
9488
-
9489
- function requirePify () {
9490
- if (hasRequiredPify) return pify.exports;
9491
- hasRequiredPify = 1;
9492
-
9493
- var processFn = function (fn, P, opts) {
9494
- return function () {
9495
- var that = this;
9496
- var args = new Array(arguments.length);
9497
-
9498
- for (var i = 0; i < arguments.length; i++) {
9499
- args[i] = arguments[i];
9500
- }
9501
-
9502
- return new P(function (resolve, reject) {
9503
- args.push(function (err, result) {
9504
- if (err) {
9505
- reject(err);
9506
- } else if (opts.multiArgs) {
9507
- var results = new Array(arguments.length - 1);
9508
-
9509
- for (var i = 1; i < arguments.length; i++) {
9510
- results[i - 1] = arguments[i];
9511
- }
9512
-
9513
- resolve(results);
9514
- } else {
9515
- resolve(result);
9516
- }
9517
- });
9518
-
9519
- fn.apply(that, args);
9520
- });
9521
- };
9522
- };
9523
-
9524
- var pify$1 = pify.exports = function (obj, P, opts) {
9525
- if (typeof P !== 'function') {
9526
- opts = P;
9527
- P = Promise;
9528
- }
9529
-
9530
- opts = opts || {};
9531
- opts.exclude = opts.exclude || [/.+Sync$/];
9532
-
9533
- var filter = function (key) {
9534
- var match = function (pattern) {
9535
- return typeof pattern === 'string' ? key === pattern : pattern.test(key);
9536
- };
9537
-
9538
- return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
9539
- };
9540
-
9541
- var ret = typeof obj === 'function' ? function () {
9542
- if (opts.excludeMain) {
9543
- return obj.apply(this, arguments);
9544
- }
9545
-
9546
- return processFn(obj, P, opts).apply(this, arguments);
9547
- } : {};
9548
-
9549
- return Object.keys(obj).reduce(function (ret, key) {
9550
- var x = obj[key];
9551
-
9552
- ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x;
9553
-
9554
- return ret;
9555
- }, ret);
9556
- };
9557
-
9558
- pify$1.all = pify$1;
9559
- return pify.exports;
9560
- }
9561
-
9562
- var defaultBrowserId;
9563
- var hasRequiredDefaultBrowserId;
9564
-
9565
- function requireDefaultBrowserId () {
9566
- if (hasRequiredDefaultBrowserId) return defaultBrowserId;
9567
- hasRequiredDefaultBrowserId = 1;
9568
- const os = require$$0;
9569
- const bplist = requireBplistParser();
9570
- const untildify = requireUntildify();
9571
- const pify = requirePify();
9572
- const osxVersion = Number(os.release().split('.')[0]);
9573
- const file = untildify(osxVersion >= 14 ? '~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist' : '~/Library/Preferences/com.apple.LaunchServices.plist');
9574
-
9575
- defaultBrowserId = () => {
9576
- if (process.platform !== 'darwin') {
9577
- return Promise.reject(new Error('Only OS X is supported'));
9578
- }
9579
-
9580
- let bundleId = 'com.apple.Safari';
9581
-
9582
- return pify(bplist.parseFile)(file).then(data => {
9583
- const handlers = data && data[0].LSHandlers;
9584
-
9585
- if (!handlers || handlers.length === 0) {
9586
- return bundleId;
9587
- }
9588
-
9589
- for (const el of handlers) {
9590
- if (el.LSHandlerURLScheme === 'http' && el.LSHandlerRoleAll) {
9591
- bundleId = el.LSHandlerRoleAll;
9592
- break;
9593
- }
9594
- }
9595
-
9596
- return bundleId;
9597
- });
9598
- };
9599
- return defaultBrowserId;
9600
- }
9601
-
9602
- var detectMac;
9603
- var hasRequiredDetectMac;
9604
-
9605
- function requireDetectMac () {
9606
- if (hasRequiredDetectMac) return detectMac;
9607
- hasRequiredDetectMac = 1;
9608
- var defaultBrowserMac = requireDefaultBrowserId();
9609
-
9610
- require$$0$4.exec;
9611
-
9612
- detectMac = function (callback) {
9613
- defaultBrowserMac()
9614
- .then(function (browserId) {
9615
- var value = browserId;
9616
- var valueLC = value.toLowerCase();
9617
-
9618
- /*
9619
- Safari com.apple.Safari
9620
- Google Chrome com.google.chrome
9621
- Opera com.operasoftware.Opera
9622
- Firefox org.mozilla.firefox
9623
- */
9624
- var out = {
9625
- isIE: false,
9626
- isSafari: valueLC.indexOf("safari") > -1,
9627
- isFirefox: valueLC.indexOf("firefox") > -1,
9628
- isChrome: valueLC.indexOf("google") > -1,
9629
- isChromium: valueLC.indexOf("chromium") > -1, // untested
9630
- isOpera: valueLC.indexOf("opera") > -1,
9631
- identity: value,
9632
- };
9633
- out.isBlink = out.isChrome || out.isChromium || out.isOpera;
9634
- out.isWebkit = out.isSafari || out.isBlink;
9635
- out.commonName = requireCommonName()(out);
9636
-
9637
- callback(null, out);
9638
- })
9639
- .catch(function (err) {
9640
- if (err) {
9641
- callback("Unable to retrieve default browser: " + err);
9642
- }
9643
- });
9644
- };
9645
- return detectMac;
9646
- }
9647
-
9648
- var detectLinux;
9649
- var hasRequiredDetectLinux;
9650
-
9651
- function requireDetectLinux () {
9652
- if (hasRequiredDetectLinux) return detectLinux;
9653
- hasRequiredDetectLinux = 1;
9654
- var exec = require$$0$4.exec;
9655
-
9656
- detectLinux = function (callback) {
9657
-
9658
- var command = 'xdg-mime query default x-scheme-handler/http';
9659
-
9660
- exec(command, function (err, stdout, stderr) {
9661
- if(err) {
9662
- callback('Unable to execute the query: ' + err + '\n' + stderr);
9663
- return;
9664
- }
9665
-
9666
- var value = stdout;
9667
-
9668
- /*
9669
- * ubuntu 14.04.1:
9670
- * --------
9671
- * firefox.desktop
9672
- * google-chrome.desktop
9673
- * chromium-browser.desktop
9674
- * opera.desktop
9675
- */
9676
- var out = {
9677
- isIE: false,
9678
- isSafari: false,
9679
- isFirefox: value.indexOf('firefox') > -1,
9680
- isChrome: value.indexOf('google') > -1,
9681
- isChromium: value.indexOf('chromium') > -1,
9682
- isOpera: value.indexOf('opera') > -1,
9683
- identity: value
9684
- };
9685
- out.isWebkit = out.isBlink = (out.isChrome || out.isChromium || out.isOpera);
9686
- out.commonName = requireCommonName()(out);
9687
-
9688
- callback(null, out);
9689
- });
9690
- };
9691
- return detectLinux;
9692
- }
9693
-
9694
- var detectStub;
9695
- var hasRequiredDetectStub;
9696
-
9697
- function requireDetectStub () {
9698
- if (hasRequiredDetectStub) return detectStub;
9699
- hasRequiredDetectStub = 1;
9700
- detectStub = function (callback) {
9701
- callback('Your platform is not supported, sorry. Patches welcome.');
9702
- };
9703
- return detectStub;
9704
- }
9705
-
9706
- var detect;
9707
- var os = require$$0;
9708
-
9709
- if (os.platform() == "win32") {
9710
- // Windows 11 still returns 10.: https://stackoverflow.com/a/69922526/
9711
- if (os.release().indexOf("10.") === 0)
9712
- detect = requireDetectWindows10();
9713
- else detect = requireDetectWindows();
9714
- } else if (os.platform() == "darwin") {
9715
- detect = requireDetectMac();
9716
- } else if (os.platform() == "linux" || os.platform() == "freebsd") {
9717
- detect = requireDetectLinux();
9718
- } else {
9719
- detect = requireDetectStub();
7494
+ const playwrightBrowsers = ["firefox", "webkit", "chromium"];
7495
+ class PlaywrightBrowserProvider {
7496
+ constructor() {
7497
+ this.name = "playwright";
7498
+ this.cachedBrowser = null;
7499
+ }
7500
+ getSupportedBrowsers() {
7501
+ return playwrightBrowsers;
7502
+ }
7503
+ async initialize(ctx, { browser }) {
7504
+ this.ctx = ctx;
7505
+ this.browser = browser;
7506
+ const root = this.ctx.config.root;
7507
+ if (!await ensurePackageInstalled("playwright", root))
7508
+ throw new Error('Cannot find "playwright" package. Please install it manually.');
7509
+ }
7510
+ async openBrowser() {
7511
+ if (this.cachedBrowser)
7512
+ return this.cachedBrowser;
7513
+ const options = this.ctx.config.browser;
7514
+ const playwright = await import('playwright');
7515
+ const playwrightInstance = await playwright[this.browser].launch({ headless: options.headless });
7516
+ this.cachedBrowser = await playwrightInstance.newPage();
7517
+ this.cachedBrowser.on("close", () => {
7518
+ playwrightInstance.close();
7519
+ });
7520
+ return this.cachedBrowser;
7521
+ }
7522
+ async openPage(url) {
7523
+ const browserInstance = await this.openBrowser();
7524
+ await browserInstance.goto(url);
7525
+ }
7526
+ async close() {
7527
+ var _a;
7528
+ await ((_a = this.cachedBrowser) == null ? void 0 : _a.close());
7529
+ process.exit();
7530
+ }
9720
7531
  }
9721
7532
 
9722
- var xDefaultBrowser = detect;
9723
-
7533
+ const webdriverBrowsers = ["firefox", "chrome", "edge", "safari"];
9724
7534
  class WebdriverBrowserProvider {
9725
7535
  constructor() {
7536
+ this.name = "webdriverio";
9726
7537
  this.cachedBrowser = null;
9727
- this.testDefers = /* @__PURE__ */ new Map();
9728
7538
  this.stopSafari = () => {
9729
7539
  };
9730
- this.host = "";
9731
- this.browser = "unknown";
9732
7540
  }
9733
- async initialize(ctx) {
9734
- var _a;
7541
+ getSupportedBrowsers() {
7542
+ return webdriverBrowsers;
7543
+ }
7544
+ async initialize(ctx, { browser }) {
9735
7545
  this.ctx = ctx;
9736
- this.host = `http://${((_a = ctx.config.browser.api) == null ? void 0 : _a.host) || "localhost"}:${ctx.browser.config.server.port}`;
9737
- const root = this.ctx.config.root;
9738
- const browser = await this.getBrowserName();
9739
7546
  this.browser = browser;
9740
- if (browser === "unknown" || !browser)
9741
- throw new Error("Cannot detect browser. Please specify it in the config file.");
7547
+ const root = this.ctx.config.root;
9742
7548
  if (!await ensurePackageInstalled("webdriverio", root))
9743
7549
  throw new Error('Cannot find "webdriverio" package. Please install it manually.');
9744
7550
  if (browser === "safari" && !await ensurePackageInstalled("safaridriver", root))
9745
7551
  throw new Error('Cannot find "safaridriver" package. Please install it manually.');
9746
7552
  }
9747
- async resolveBrowserName() {
9748
- const browser = await promisify(xDefaultBrowser)();
9749
- return browser.commonName;
9750
- }
9751
- async getBrowserName() {
9752
- return this.ctx.config.browser.name ?? await this.resolveBrowserName();
9753
- }
9754
7553
  async openBrowser() {
9755
7554
  if (this.cachedBrowser)
9756
7555
  return this.cachedBrowser;
@@ -9773,54 +7572,28 @@ class WebdriverBrowserProvider {
9773
7572
  });
9774
7573
  return this.cachedBrowser;
9775
7574
  }
9776
- testFinished(id) {
9777
- var _a;
9778
- (_a = this.testDefers.get(id)) == null ? void 0 : _a.resolve(true);
9779
- }
9780
- waitForTest(id) {
9781
- const defer = createDefer();
9782
- this.testDefers.set(id, defer);
9783
- return defer;
7575
+ async openPage(url) {
7576
+ const browserInstance = await this.openBrowser();
7577
+ await browserInstance.url(url);
9784
7578
  }
9785
- createPool() {
9786
- const runTests = async (files) => {
9787
- const paths = files.map((file) => relative(this.ctx.config.root, file));
9788
- const browserInstance = await this.openBrowser();
9789
- const isolate = this.ctx.config.isolate;
9790
- if (isolate) {
9791
- for (const path of paths) {
9792
- const url = new URL(this.host);
9793
- url.searchParams.append("path", path);
9794
- url.searchParams.set("id", path);
9795
- await browserInstance.url(url.toString());
9796
- await this.waitForTest(path);
9797
- }
9798
- } else {
9799
- const url = new URL(this.host);
9800
- url.searchParams.set("id", "no-isolate");
9801
- paths.forEach((path) => url.searchParams.append("path", path));
9802
- await browserInstance.url(url.toString());
9803
- await this.waitForTest("no-isolate");
9804
- }
9805
- };
9806
- return {
9807
- runTests,
9808
- close: async () => {
9809
- var _a, _b, _c;
9810
- this.testDefers.clear();
9811
- await Promise.all([
9812
- this.stopSafari(),
9813
- ((_a = this.cachedBrowser) == null ? void 0 : _a.sessionId) ? (_c = (_b = this.cachedBrowser) == null ? void 0 : _b.deleteSession) == null ? void 0 : _c.call(_b) : null
9814
- ]);
9815
- process.exit();
9816
- }
9817
- };
7579
+ async close() {
7580
+ var _a, _b, _c;
7581
+ await Promise.all([
7582
+ this.stopSafari(),
7583
+ ((_a = this.cachedBrowser) == null ? void 0 : _a.sessionId) ? (_c = (_b = this.cachedBrowser) == null ? void 0 : _b.deleteSession) == null ? void 0 : _c.call(_b) : null
7584
+ ]);
7585
+ process.exit();
9818
7586
  }
9819
7587
  }
9820
7588
 
9821
7589
  async function getBrowserProvider(options, loader) {
9822
- if (!options.provider || options.provider === "webdriverio")
9823
- return WebdriverBrowserProvider;
7590
+ switch (options.provider) {
7591
+ case void 0:
7592
+ case "webdriverio":
7593
+ return WebdriverBrowserProvider;
7594
+ case "playwright":
7595
+ return PlaywrightBrowserProvider;
7596
+ }
9824
7597
  let customProviderModule;
9825
7598
  try {
9826
7599
  customProviderModule = await loader.executeId(options.provider);
@@ -9864,10 +7637,6 @@ const coverageConfigDefaults = {
9864
7637
  reporter: [["text", {}], ["html", {}], ["clover", {}], ["json", {}]],
9865
7638
  extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte"]
9866
7639
  };
9867
- const browserConfigDefaults = {
9868
- enabled: false,
9869
- headless: isCI
9870
- };
9871
7640
  const fakeTimersDefaults = {
9872
7641
  loopLimit: 1e4,
9873
7642
  shouldClearNativeTimers: true,
@@ -9896,7 +7665,6 @@ const config = {
9896
7665
  hookTimeout: 1e4,
9897
7666
  teardownTimeout: 1e4,
9898
7667
  isolate: true,
9899
- browser: browserConfigDefaults,
9900
7668
  watchExclude: ["**/node_modules/**", "**/dist/**"],
9901
7669
  forceRerunTriggers: [
9902
7670
  "**/package.json/**",
@@ -10152,6 +7920,8 @@ function resolveConfig(mode, options, viteConfig) {
10152
7920
  throw new Error(`You cannot use ${inspectOption} without "threads: false" or "singleThread: true"`);
10153
7921
  }
10154
7922
  }
7923
+ if (resolved.coverage.provider === "c8" && resolved.coverage.enabled && isBrowserEnabled(resolved))
7924
+ throw new Error("@vitest/coverage-c8 does not work with --browser. Use @vitest/coverage-istanbul instead");
10155
7925
  resolved.deps = resolved.deps || {};
10156
7926
  if (resolved.deps.inline !== true) {
10157
7927
  const ssrOptions = viteConfig.ssr;
@@ -10244,6 +8014,7 @@ function resolveConfig(mode, options, viteConfig) {
10244
8014
  resolved.include = resolved.typecheck.include;
10245
8015
  resolved.exclude = resolved.typecheck.exclude;
10246
8016
  }
8017
+ resolved.browser ?? (resolved.browser = {});
10247
8018
  (_i = resolved.browser).enabled ?? (_i.enabled = false);
10248
8019
  (_j = resolved.browser).headless ?? (_j.headless = isCI);
10249
8020
  resolved.browser.api = resolveApiServerConfig(resolved.browser) || {
@@ -10251,6 +8022,22 @@ function resolveConfig(mode, options, viteConfig) {
10251
8022
  };
10252
8023
  return resolved;
10253
8024
  }
8025
+ function isBrowserEnabled(config) {
8026
+ var _a, _b;
8027
+ if ((_a = config.browser) == null ? void 0 : _a.enabled)
8028
+ return true;
8029
+ return ((_b = config.poolMatchGlobs) == null ? void 0 : _b.length) && config.poolMatchGlobs.some(([, pool]) => pool === "browser");
8030
+ }
8031
+
8032
+ function CoverageTransform(ctx) {
8033
+ return {
8034
+ name: "vitest:coverage-transform",
8035
+ transform(srcCode, id) {
8036
+ var _a, _b;
8037
+ return (_b = (_a = ctx.coverageProvider) == null ? void 0 : _a.onFileTransform) == null ? void 0 : _b.call(_a, srcCode, normalizeRequestId(id), this);
8038
+ }
8039
+ };
8040
+ }
10254
8041
 
10255
8042
  async function createBrowserServer(ctx, options) {
10256
8043
  const root = ctx.config.root;
@@ -10268,30 +8055,35 @@ async function createBrowserServer(ctx, options) {
10268
8055
  },
10269
8056
  plugins: [
10270
8057
  (await import('@vitest/browser')).default("/"),
8058
+ CoverageTransform(ctx),
10271
8059
  {
10272
8060
  enforce: "post",
10273
8061
  name: "vitest:browser:config",
10274
8062
  async config(config) {
10275
- var _a, _b;
8063
+ var _a, _b, _c;
10276
8064
  const server2 = resolveApiServerConfig(((_a = config.test) == null ? void 0 : _a.browser) || {}) || {
10277
8065
  port: 63315
10278
8066
  };
10279
8067
  config.server = server2;
10280
8068
  config.optimizeDeps ?? (config.optimizeDeps = {});
10281
8069
  (_b = config.optimizeDeps).entries ?? (_b.entries = []);
10282
- const root2 = config.root || process.cwd();
10283
- const [...entries] = await ctx.globAllTestFiles(ctx.config, ctx.config.dir || root2);
8070
+ const [...entries] = await ctx.globAllTestFiles(ctx.config, ctx.config.dir || root);
10284
8071
  entries.push(...ctx.config.setupFiles);
10285
8072
  if (typeof config.optimizeDeps.entries === "string")
10286
8073
  config.optimizeDeps.entries = [config.optimizeDeps.entries];
10287
8074
  config.optimizeDeps.entries.push(...entries);
8075
+ return {
8076
+ resolve: {
8077
+ alias: (_c = config.test) == null ? void 0 : _c.alias
8078
+ }
8079
+ };
10288
8080
  }
10289
8081
  }
10290
8082
  ]
10291
8083
  });
10292
8084
  await server.listen();
10293
8085
  await server.watcher.close();
10294
- (await import('./chunk-api-setup.ac7748ac.js')).setup(ctx, server);
8086
+ (await import('./chunk-api-setup.3aabe9ac.js')).setup(ctx, server);
10295
8087
  return server;
10296
8088
  }
10297
8089
 
@@ -10588,6 +8380,43 @@ function createThreadsPool(ctx, { execArgv, env }) {
10588
8380
  };
10589
8381
  }
10590
8382
 
8383
+ function createBrowserPool(ctx) {
8384
+ var _a;
8385
+ const provider = ctx.browserProvider;
8386
+ const origin = `http://${((_a = ctx.config.browser.api) == null ? void 0 : _a.host) || "localhost"}:${ctx.browser.config.server.port}`;
8387
+ const waitForTest = (id) => {
8388
+ const defer = createDefer();
8389
+ ctx.state.browserTestPromises.set(id, defer);
8390
+ return defer;
8391
+ };
8392
+ const runTests = async (files) => {
8393
+ const paths = files.map((file) => relative(ctx.config.root, file));
8394
+ const isolate = ctx.config.isolate;
8395
+ if (isolate) {
8396
+ for (const path of paths) {
8397
+ const url = new URL("/", origin);
8398
+ url.searchParams.append("path", path);
8399
+ url.searchParams.set("id", path);
8400
+ await provider.openPage(url.toString());
8401
+ await waitForTest(path);
8402
+ }
8403
+ } else {
8404
+ const url = new URL("/", origin);
8405
+ url.searchParams.set("id", "no-isolate");
8406
+ paths.forEach((path) => url.searchParams.append("path", path));
8407
+ await provider.openPage(url.toString());
8408
+ await waitForTest("no-isolate");
8409
+ }
8410
+ };
8411
+ return {
8412
+ async close() {
8413
+ ctx.state.browserTestPromises.clear();
8414
+ await provider.close();
8415
+ },
8416
+ runTests
8417
+ };
8418
+ }
8419
+
10591
8420
  const loaderPath = pathToFileURL(resolve$2(distDir, "./loader.js")).href;
10592
8421
  const suppressLoaderWarningsPath = resolve$2(rootDir, "./suppress-warnings.cjs");
10593
8422
  function createPool(ctx) {
@@ -10654,7 +8483,7 @@ function createPool(ctx) {
10654
8483
  if (!files2.length)
10655
8484
  return null;
10656
8485
  if (ctx.browserProvider && pool === "browser") {
10657
- pools.browser ?? (pools.browser = ctx.browserProvider.createPool());
8486
+ pools.browser ?? (pools.browser = createBrowserPool(ctx));
10658
8487
  return pools.browser.runTests(files2, invalidate);
10659
8488
  }
10660
8489
  if (pool === "threads") {
@@ -13153,6 +10982,7 @@ class StateManager {
13153
10982
  this.filesMap = /* @__PURE__ */ new Map();
13154
10983
  this.pathsSet = /* @__PURE__ */ new Set();
13155
10984
  this.collectingPromise = void 0;
10985
+ this.browserTestPromises = /* @__PURE__ */ new Map();
13156
10986
  this.idMap = /* @__PURE__ */ new Map();
13157
10987
  this.taskFileMap = /* @__PURE__ */ new WeakMap();
13158
10988
  this.errorsSet = /* @__PURE__ */ new Set();
@@ -13781,15 +11611,15 @@ createLogUpdate(process$1.stdout);
13781
11611
 
13782
11612
  createLogUpdate(process$1.stderr);
13783
11613
 
13784
- var version = "0.29.7";
11614
+ var version = "0.29.8";
13785
11615
 
13786
11616
  async function printError(error, ctx, options = {}) {
13787
11617
  const { showCodeFrame = true, fullStack = false, type } = options;
13788
11618
  let e = error;
13789
- if (typeof error === "string") {
11619
+ if (isPrimitive(e)) {
13790
11620
  e = {
13791
- message: error.split(/\n/g)[0],
13792
- stack: error
11621
+ message: String(error).split(/\n/g)[0],
11622
+ stack: String(error)
13793
11623
  };
13794
11624
  }
13795
11625
  if (!e) {
@@ -15183,7 +13013,13 @@ class Vitest {
15183
13013
  return this.browserProvider;
15184
13014
  const Provider = await getBrowserProvider(this.config.browser, this.runner);
15185
13015
  this.browserProvider = new Provider();
15186
- await this.browserProvider.initialize(this);
13016
+ const browser = this.config.browser.name;
13017
+ const supportedBrowsers = this.browserProvider.getSupportedBrowsers();
13018
+ if (!browser)
13019
+ throw new Error("Browser name is required. Please, set `test.browser.name` option manually.");
13020
+ if (!supportedBrowsers.includes(browser))
13021
+ throw new Error(`Browser "${browser}" is not supported by the browser provider "${this.browserProvider.name}". Supported browsers: ${supportedBrowsers.join(", ")}.`);
13022
+ await this.browserProvider.initialize(this, { browser });
15187
13023
  return this.browserProvider;
15188
13024
  }
15189
13025
  getSerializableConfig() {
@@ -15284,6 +13120,7 @@ class Vitest {
15284
13120
  );
15285
13121
  if (!files.length) {
15286
13122
  const exitCode = this.config.passWithNoTests ? 0 : 1;
13123
+ await this.reportCoverage(true);
15287
13124
  this.logger.printNoTestFound(filters);
15288
13125
  process.exit(exitCode);
15289
13126
  }
@@ -15630,9 +13467,7 @@ class Vitest {
15630
13467
  return false;
15631
13468
  }
15632
13469
  isBrowserEnabled() {
15633
- if (this.config.browser.enabled)
15634
- return true;
15635
- return (this.config.poolMatchGlobs || []).some(([, pool]) => pool === "browser");
13470
+ return isBrowserEnabled(this.config);
15636
13471
  }
15637
13472
  shouldKeepServer() {
15638
13473
  var _a;
@@ -15818,16 +13653,6 @@ function CSSEnablerPlugin(ctx) {
15818
13653
  ];
15819
13654
  }
15820
13655
 
15821
- function CoverageTransform(ctx) {
15822
- return {
15823
- name: "vitest:coverage-transform",
15824
- transform(srcCode, id) {
15825
- var _a, _b;
15826
- return (_b = (_a = ctx.coverageProvider) == null ? void 0 : _a.onFileTransform) == null ? void 0 : _b.call(_a, srcCode, id, this);
15827
- }
15828
- };
15829
- }
15830
-
15831
13656
  async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
15832
13657
  const userConfig = deepMerge({}, options);
15833
13658
  const getRoot = () => {
@@ -15990,7 +13815,7 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
15990
13815
  await ctx.setServer(options, server);
15991
13816
  await ctx.initBrowserServer(options);
15992
13817
  if (options.api && options.watch)
15993
- (await import('./chunk-api-setup.ac7748ac.js')).setup(ctx);
13818
+ (await import('./chunk-api-setup.3aabe9ac.js')).setup(ctx);
15994
13819
  } catch (err) {
15995
13820
  await ctx.logger.printError(err, true);
15996
13821
  process.exit(1);
@@ -16518,7 +14343,7 @@ function requirePrompt$1 () {
16518
14343
  if (hasRequiredPrompt$1) return prompt$1;
16519
14344
  hasRequiredPrompt$1 = 1;
16520
14345
 
16521
- const readline = require$$0$5;
14346
+ const readline = require$$0$4;
16522
14347
 
16523
14348
  const _require = requireUtil$1(),
16524
14349
  action = _require.action;
@@ -19683,7 +17508,7 @@ function requirePrompt () {
19683
17508
  if (hasRequiredPrompt) return prompt;
19684
17509
  hasRequiredPrompt = 1;
19685
17510
 
19686
- const readline = require$$0$5;
17511
+ const readline = require$$0$4;
19687
17512
  const { action } = requireUtil();
19688
17513
  const EventEmitter = require$$2;
19689
17514
  const { beep, cursor } = requireSrc();
@@ -22374,8 +20199,8 @@ function registerConsoleShortcuts(ctx) {
22374
20199
  let rl;
22375
20200
  function on() {
22376
20201
  off();
22377
- rl = require$$0$5.createInterface({ input: process.stdin, escapeCodeTimeout: 50 });
22378
- require$$0$5.emitKeypressEvents(process.stdin, rl);
20202
+ rl = require$$0$4.createInterface({ input: process.stdin, escapeCodeTimeout: 50 });
20203
+ require$$0$4.emitKeypressEvents(process.stdin, rl);
22379
20204
  if (process.stdin.isTTY)
22380
20205
  process.stdin.setRawMode(true);
22381
20206
  process.stdin.on("keypress", keypressHandler);