choi

fix dependencies

Showing 152 changed files with 4700 additions and 0 deletions
#### 9.0.0
* 27/05/2019
* For compatibility with legacy browsers, remove `Symbol` references.
#### 8.1.1
* 24/02/2019
* [BUGFIX] #222 Restore missing `var` to `export BigNumber`.
* Allow any key in BigNumber.Instance in *bignumber.d.ts*.
#### 8.1.0
* 23/02/2019
* [NEW FEATURE] #220 Create a BigNumber using `{s, e, c}`.
* [NEW FEATURE] `isBigNumber`: if `BigNumber.DEBUG` is `true`, also check that the BigNumber instance is well-formed.
* Remove `instanceof` checks; just use `_isBigNumber` to identify a BigNumber instance.
* Add `_isBigNumber` to prototype in *bignumber.mjs*.
* Add tests for BigNumber creation from object.
* Update *API.html*.
#### 8.0.2
* 13/01/2019
* #209 `toPrecision` without argument should follow `toString`.
* Improve *Use* section of *README*.
* Optimise `toString(10)`.
* Add verson number to API doc.
#### 8.0.1
* 01/11/2018
* Rest parameter must be array type in *bignumber.d.ts*.
#### 8.0.0
* 01/11/2018
* [NEW FEATURE] Add `BigNumber.sum` method.
* [NEW FEATURE]`toFormat`: add `prefix` and `suffix` options.
* [NEW FEATURE] #178 Pass custom formatting to `toFormat`.
* [BREAKING CHANGE] #184 `toFraction`: return array of BigNumbers not strings.
* [NEW FEATURE] #185 Enable overwrite of `valueOf` to prevent accidental addition to string.
* #183 Add Node.js `crypto` requirement to documentation.
* [BREAKING CHANGE] #198 Disallow signs and whitespace in custom alphabet.
* [NEW FEATURE] #188 Implement `util.inspect.custom` for Node.js REPL.
* #170 Make `isBigNumber` a type guard in *bignumber.d.ts*.
* [BREAKING CHANGE] `BigNumber.min` and `BigNumber.max`: don't accept an array.
* Update *.travis.yml*.
* Remove *bower.json*.
#### 7.2.1
* 24/05/2018
* Add `browser` field to *package.json*.
#### 7.2.0
* 22/05/2018
* #166 Correct *.mjs* file. Remove extension from `main` field in *package.json*.
#### 7.1.0
* 18/05/2018
* Add `module` field to *package.json* for *bignumber.mjs*.
#### 7.0.2
* 17/05/2018
* #165 Bugfix: upper-case letters for bases 11-36 in a custom alphabet.
* Add note to *README* regarding creating BigNumbers from Number values.
#### 7.0.1
* 26/04/2018
* #158 Fix global object variable name typo.
#### 7.0.0
* 26/04/2018
* #143 Remove global BigNumber from typings.
* #144 Enable compatibility with `Object.freeze(Object.prototype)`.
* #148 #123 #11 Only throw on a number primitive with more than 15 significant digits if `BigNumber.DEBUG` is `true`.
* Only throw on an invalid BigNumber value if `BigNumber.DEBUG` is `true`. Return BigNumber `NaN` instead.
* #154 `exponentiatedBy`: allow BigNumber exponent.
* #156 Prevent Content Security Policy *unsafe-eval* issue.
* `toFraction`: allow `Infinity` maximum denominator.
* Comment-out some excess tests to reduce test time.
* Amend indentation and other spacing.
#### 6.0.0
* 26/01/2018
* #137 Implement `APLHABET` configuration option.
* Remove `ERRORS` configuration option.
* Remove `toDigits` method; extend `precision` method accordingly.
* Remove s`round` method; extend `decimalPlaces` method accordingly.
* Remove methods: `ceil`, `floor`, and `truncated`.
* Remove method aliases: `add`, `cmp`, `isInt`, `isNeg`, `trunc`, `mul`, `neg` and `sub`.
* Rename methods: `shift` to `shiftedBy`, `another` to `clone`, `toPower` to `exponentiatedBy`, and `equals` to `isEqualTo`.
* Rename methods: add `is` prefix to `greaterThan`, `greaterThanOrEqualTo`, `lessThan` and `lessThanOrEqualTo`.
* Add methods: `multipliedBy`, `isBigNumber`, `isPositive`, `integerValue`, `maximum` and `minimum`.
* Refactor test suite.
* Add *CHANGELOG.md*.
* Rewrite *bignumber.d.ts*.
* Redo API image.
#### 5.0.0
* 27/11/2017
* #81 Don't throw on constructor call without `new`.
#### 4.1.0
* 26/09/2017
* Remove node 0.6 from *.travis.yml*.
* Add *bignumber.mjs*.
#### 4.0.4
* 03/09/2017
* Add missing aliases to *bignumber.d.ts*.
#### 4.0.3
* 30/08/2017
* Add types: *bignumber.d.ts*.
#### 4.0.2
* 03/05/2017
* #120 Workaround Safari/Webkit bug.
#### 4.0.1
* 05/04/2017
* #121 BigNumber.default to BigNumber['default'].
#### 4.0.0
* 09/01/2017
* Replace BigNumber.isBigNumber method with isBigNumber prototype property.
#### 3.1.2
* 08/01/2017
* Minor documentation edit.
#### 3.1.1
* 08/01/2017
* Uncomment `isBigNumber` tests.
* Ignore dot files.
#### 3.1.0
* 08/01/2017
* Add `isBigNumber` method.
#### 3.0.2
* 08/01/2017
* Bugfix: Possible incorrect value of `ERRORS` after a `BigNumber.another` call (due to `parseNumeric` declaration in outer scope).
#### 3.0.1
* 23/11/2016
* Apply fix for old ipads with `%` issue, see #57 and #102.
* Correct error message.
#### 3.0.0
* 09/11/2016
* Remove `require('crypto')` - leave it to the user.
* Add `BigNumber.set` as `BigNumber.config` alias.
* Default `POW_PRECISION` to `0`.
#### 2.4.0
* 14/07/2016
* #97 Add exports to support ES6 imports.
#### 2.3.0
* 07/03/2016
* #86 Add modulus parameter to `toPower`.
#### 2.2.0
* 03/03/2016
* #91 Permit larger JS integers.
#### 2.1.4
* 15/12/2015
* Correct UMD.
#### 2.1.3
* 13/12/2015
* Refactor re global object and crypto availability when bundling.
#### 2.1.2
* 10/12/2015
* Bugfix: `window.crypto` not assigned to `crypto`.
#### 2.1.1
* 09/12/2015
* Prevent code bundler from adding `crypto` shim.
#### 2.1.0
* 26/10/2015
* For `valueOf` and `toJSON`, include the minus sign with negative zero.
#### 2.0.8
* 2/10/2015
* Internal round function bugfix.
#### 2.0.6
* 31/03/2015
* Add bower.json. Tweak division after in-depth review.
#### 2.0.5
* 25/03/2015
* Amend README. Remove bitcoin address.
#### 2.0.4
* 25/03/2015
* Critical bugfix #58: division.
#### 2.0.3
* 18/02/2015
* Amend README. Add source map.
#### 2.0.2
* 18/02/2015
* Correct links.
#### 2.0.1
* 18/02/2015
* Add `max`, `min`, `precision`, `random`, `shiftedBy`, `toDigits` and `truncated` methods.
* Add the short-forms: `add`, `mul`, `sd`, `sub` and `trunc`.
* Add an `another` method to enable multiple independent constructors to be created.
* Add support for the base 2, 8 and 16 prefixes `0b`, `0o` and `0x`.
* Enable a rounding mode to be specified as a second parameter to `toExponential`, `toFixed`, `toFormat` and `toPrecision`.
* Add a `CRYPTO` configuration property so cryptographically-secure pseudo-random number generation can be specified.
* Add a `MODULO_MODE` configuration property to enable the rounding mode used by the `modulo` operation to be specified.
* Add a `POW_PRECISION` configuration property to enable the number of significant digits calculated by the power operation to be limited.
* Improve code quality.
* Improve documentation.
#### 2.0.0
* 29/12/2014
* Add `dividedToIntegerBy`, `isInteger` and `toFormat` methods.
* Remove the following short-forms: `isF`, `isZ`, `toE`, `toF`, `toFr`, `toN`, `toP`, `toS`.
* Store a BigNumber's coefficient in base 1e14, rather than base 10.
* Add fast path for integers to BigNumber constructor.
* Incorporate the library into the online documentation.
#### 1.5.0
* 13/11/2014
* Add `toJSON` and `decimalPlaces` methods.
#### 1.4.1
* 08/06/2014
* Amend README.
#### 1.4.0
* 08/05/2014
* Add `toNumber`.
#### 1.3.0
* 08/11/2013
* Ensure correct rounding of `sqrt` in all, rather than almost all, cases.
* Maximum radix to 64.
#### 1.2.1
* 17/10/2013
* Sign of zero when x < 0 and x + (-x) = 0.
#### 1.2.0
* 19/9/2013
* Throw Error objects for stack.
#### 1.1.1
* 22/8/2013
* Show original value in constructor error message.
#### 1.1.0
* 1/8/2013
* Allow numbers with trailing radix point.
#### 1.0.1
* Bugfix: error messages with incorrect method name
#### 1.0.0
* 8/11/2012
* Initial release
The MIT Licence.
Copyright (c) 2019 Michael Mclaughlin
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
![bignumber.js](https://raw.githubusercontent.com/MikeMcl/bignumber.js/gh-pages/bignumberjs.png)
A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic.
[![Build Status](https://travis-ci.org/MikeMcl/bignumber.js.svg)](https://travis-ci.org/MikeMcl/bignumber.js)
<br />
## Features
- Integers and decimals
- Simple API but full-featured
- Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal
- 8 KB minified and gzipped
- Replicates the `toExponential`, `toFixed`, `toPrecision` and `toString` methods of JavaScript's Number type
- Includes a `toFraction` and a correctly-rounded `squareRoot` method
- Supports cryptographically-secure pseudo-random number generation
- No dependencies
- Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only
- Comprehensive [documentation](http://mikemcl.github.io/bignumber.js/) and test set
![API](https://raw.githubusercontent.com/MikeMcl/bignumber.js/gh-pages/API.png)
If a smaller and simpler library is required see [big.js](https://github.com/MikeMcl/big.js/).
It's less than half the size but only works with decimal numbers and only has half the methods.
It also does not allow `NaN` or `Infinity`, or have the configuration options of this library.
See also [decimal.js](https://github.com/MikeMcl/decimal.js/), which among other things adds support for non-integer powers, and performs all operations to a specified number of significant digits.
## Load
The library is the single JavaScript file *bignumber.js* (or minified, *bignumber.min.js*).
Browser:
```html
<script src='path/to/bignumber.js'></script>
```
[Node.js](http://nodejs.org):
```bash
$ npm install bignumber.js
```
```javascript
const BigNumber = require('bignumber.js');
```
ES6 module:
```javascript
import BigNumber from "./bignumber.mjs"
```
AMD loader libraries such as [requireJS](http://requirejs.org/):
```javascript
require(['bignumber'], function(BigNumber) {
// Use BigNumber here in local scope. No global BigNumber.
});
```
## Use
The library exports a single constructor function, [`BigNumber`](http://mikemcl.github.io/bignumber.js/#bignumber), which accepts a value of type Number, String or BigNumber,
```javascript
let x = new BigNumber(123.4567);
let y = BigNumber('123456.7e-3');
let z = new BigNumber(x);
x.isEqualTo(y) && y.isEqualTo(z) && x.isEqualTo(z); // true
```
To get the string value of a BigNumber use [`toString()`](http://mikemcl.github.io/bignumber.js/#toS) or [`toFixed()`](http://mikemcl.github.io/bignumber.js/#toFix). Using `toFixed()` prevents exponential notation being returned, no matter how large or small the value.
```javascript
let x = new BigNumber('1111222233334444555566');
x.toString(); // "1.111222233334444555566e+21"
x.toFixed(); // "1111222233334444555566"
```
If the limited precision of Number values is not well understood, it is recommended to create BigNumbers from String values rather than Number values to avoid a potential loss of precision.
*In all further examples below, `let`, semicolons and `toString` calls are not shown. If a commented-out value is in quotes it means `toString` has been called on the preceding expression.*
```javascript
// Precision loss from using numeric literals with more than 15 significant digits.
new BigNumber(1.0000000000000001) // '1'
new BigNumber(88259496234518.57) // '88259496234518.56'
new BigNumber(99999999999999999999) // '100000000000000000000'
// Precision loss from using numeric literals outside the range of Number values.
new BigNumber(2e+308) // 'Infinity'
new BigNumber(1e-324) // '0'
// Precision loss from the unexpected result of arithmetic with Number values.
new BigNumber(0.7 + 0.1) // '0.7999999999999999'
```
When creating a BigNumber from a Number, note that a BigNumber is created from a Number's decimal `toString()` value not from its underlying binary value. If the latter is required, then pass the Number's `toString(2)` value and specify base 2.
```javascript
new BigNumber(Number.MAX_VALUE.toString(2), 2)
```
BigNumbers can be created from values in bases from 2 to 36. See [`ALPHABET`](http://mikemcl.github.io/bignumber.js/#alphabet) to extend this range.
```javascript
a = new BigNumber(1011, 2) // "11"
b = new BigNumber('zz.9', 36) // "1295.25"
c = a.plus(b) // "1306.25"
```
Performance is better if base 10 is NOT specified for decimal values. Only specify base 10 when it is desired that the number of decimal places of the input value be limited to the current [`DECIMAL_PLACES`](http://mikemcl.github.io/bignumber.js/#decimal-places) setting.
A BigNumber is immutable in the sense that it is not changed by its methods.
```javascript
0.3 - 0.1 // 0.19999999999999998
x = new BigNumber(0.3)
x.minus(0.1) // "0.2"
x // "0.3"
```
The methods that return a BigNumber can be chained.
```javascript
x.dividedBy(y).plus(z).times(9)
x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').integerValue()
```
Some of the longer method names have a shorter alias.
```javascript
x.squareRoot().dividedBy(y).exponentiatedBy(3).isEqualTo(x.sqrt().div(y).pow(3)) // true
x.modulo(y).multipliedBy(z).eq(x.mod(y).times(z)) // true
```
As with JavaScript's Number type, there are [`toExponential`](http://mikemcl.github.io/bignumber.js/#toE), [`toFixed`](http://mikemcl.github.io/bignumber.js/#toFix) and [`toPrecision`](http://mikemcl.github.io/bignumber.js/#toP) methods.
```javascript
x = new BigNumber(255.5)
x.toExponential(5) // "2.55500e+2"
x.toFixed(5) // "255.50000"
x.toPrecision(5) // "255.50"
x.toNumber() // 255.5
```
A base can be specified for [`toString`](http://mikemcl.github.io/bignumber.js/#toS). Performance is better if base 10 is NOT specified, i.e. use `toString()` not `toString(10)`. Only specify base 10 when it is desired that the number of decimal places be limited to the current [`DECIMAL_PLACES`](http://mikemcl.github.io/bignumber.js/#decimal-places) setting.
```javascript
x.toString(16) // "ff.8"
```
There is a [`toFormat`](http://mikemcl.github.io/bignumber.js/#toFor) method which may be useful for internationalisation.
```javascript
y = new BigNumber('1234567.898765')
y.toFormat(2) // "1,234,567.90"
```
The maximum number of decimal places of the result of an operation involving division (i.e. a division, square root, base conversion or negative power operation) is set using the `set` or `config` method of the `BigNumber` constructor.
The other arithmetic operations always give the exact result.
```javascript
BigNumber.set({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 })
x = new BigNumber(2)
y = new BigNumber(3)
z = x.dividedBy(y) // "0.6666666667"
z.squareRoot() // "0.8164965809"
z.exponentiatedBy(-3) // "3.3749999995"
z.toString(2) // "0.1010101011"
z.multipliedBy(z) // "0.44444444448888888889"
z.multipliedBy(z).decimalPlaces(10) // "0.4444444445"
```
There is a [`toFraction`](http://mikemcl.github.io/bignumber.js/#toFr) method with an optional *maximum denominator* argument
```javascript
y = new BigNumber(355)
pi = y.dividedBy(113) // "3.1415929204"
pi.toFraction() // [ "7853982301", "2500000000" ]
pi.toFraction(1000) // [ "355", "113" ]
```
and [`isNaN`](http://mikemcl.github.io/bignumber.js/#isNaN) and [`isFinite`](http://mikemcl.github.io/bignumber.js/#isF) methods, as `NaN` and `Infinity` are valid `BigNumber` values.
```javascript
x = new BigNumber(NaN) // "NaN"
y = new BigNumber(Infinity) // "Infinity"
x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true
```
The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign.
```javascript
x = new BigNumber(-123.456);
x.c // [ 123, 45600000000000 ] coefficient (i.e. significand)
x.e // 2 exponent
x.s // -1 sign
```
For advanced usage, multiple BigNumber constructors can be created, each with their own independent configuration.
```javascript
// Set DECIMAL_PLACES for the original BigNumber constructor
BigNumber.set({ DECIMAL_PLACES: 10 })
// Create another BigNumber constructor, optionally passing in a configuration object
BN = BigNumber.clone({ DECIMAL_PLACES: 5 })
x = new BigNumber(1)
y = new BN(1)
x.div(3) // '0.3333333333'
y.div(3) // '0.33333'
```
For further information see the [API](http://mikemcl.github.io/bignumber.js/) reference in the *doc* directory.
## Test
The *test/modules* directory contains the test scripts for each method.
The tests can be run with Node.js or a browser. For Node.js use
$ npm test
or
$ node test/test
To test a single method, use, for example
$ node test/methods/toFraction
For the browser, open *test/test.html*.
## Build
For Node, if [uglify-js](https://github.com/mishoo/UglifyJS2) is installed
npm install uglify-js -g
then
npm run build
will create *bignumber.min.js*.
A source map will also be created in the root directory.
## Feedback
Open an issue, or email
Michael
<a href="mailto:M8ch88l@gmail.com">M8ch88l@gmail.com</a>
## Licence
The MIT Licence.
See [LICENCE](https://github.com/MikeMcl/bignumber.js/blob/master/LICENCE).
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
{
"_from": "bignumber.js@9.0.0",
"_id": "bignumber.js@9.0.0",
"_inBundle": false,
"_integrity": "sha512-t/OYhhJ2SD+YGBQcjY8GzzDHEk9f3nerxjtfa6tlMXfe7frs/WozhvCNoGvpM0P3bNf3Gq5ZRMlGr5f3r4/N8A==",
"_location": "/bignumber.js",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "bignumber.js@9.0.0",
"name": "bignumber.js",
"escapedName": "bignumber.js",
"rawSpec": "9.0.0",
"saveSpec": null,
"fetchSpec": "9.0.0"
},
"_requiredBy": [
"/mysql"
],
"_resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz",
"_shasum": "805880f84a329b5eac6e7cb6f8274b6d82bdf075",
"_spec": "bignumber.js@9.0.0",
"_where": "C:\\Users\\user\\Desktop\\Singer-Composer\\node_modules\\mysql",
"author": {
"name": "Michael Mclaughlin",
"email": "M8ch88l@gmail.com"
},
"browser": "bignumber.js",
"bugs": {
"url": "https://github.com/MikeMcl/bignumber.js/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "A library for arbitrary-precision decimal and non-decimal arithmetic",
"engines": {
"node": "*"
},
"homepage": "https://github.com/MikeMcl/bignumber.js#readme",
"keywords": [
"arbitrary",
"precision",
"arithmetic",
"big",
"number",
"decimal",
"float",
"biginteger",
"bigdecimal",
"bignumber",
"bigint",
"bignum"
],
"license": "MIT",
"main": "bignumber",
"module": "bignumber.mjs",
"name": "bignumber.js",
"repository": {
"type": "git",
"url": "git+https://github.com/MikeMcl/bignumber.js.git"
},
"scripts": {
"build": "uglifyjs bignumber.js --source-map -c -m -o bignumber.min.js",
"test": "node test/test"
},
"types": "bignumber.d.ts",
"version": "9.0.0"
}
language: node_js
node_js:
- "0.8"
- "0.10"
test:
@node_modules/.bin/tape test.js
.PHONY: test
# isarray
`Array#isArray` for older browsers.
[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray)
[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray)
[![browser support](https://ci.testling.com/juliangruber/isarray.png)
](https://ci.testling.com/juliangruber/isarray)
## Usage
```js
var isArray = require('isarray');
console.log(isArray([])); // => true
console.log(isArray({})); // => false
```
## Installation
With [npm](http://npmjs.org) do
```bash
$ npm install isarray
```
Then bundle for the browser with
[browserify](https://github.com/substack/browserify).
With [component](http://component.io) do
```bash
$ component install juliangruber/isarray
```
## License
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
{
"name" : "isarray",
"description" : "Array#isArray for older browsers",
"version" : "0.0.1",
"repository" : "juliangruber/isarray",
"homepage": "https://github.com/juliangruber/isarray",
"main" : "index.js",
"scripts" : [
"index.js"
],
"dependencies" : {},
"keywords": ["browser","isarray","array"],
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"license": "MIT"
}
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
{
"_from": "isarray@~1.0.0",
"_id": "isarray@1.0.0",
"_inBundle": false,
"_integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=",
"_location": "/isarray",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "isarray@~1.0.0",
"name": "isarray",
"escapedName": "isarray",
"rawSpec": "~1.0.0",
"saveSpec": null,
"fetchSpec": "~1.0.0"
},
"_requiredBy": [
"/readable-stream"
],
"_resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"_shasum": "bb935d48582cba168c06834957a54a3e07124f11",
"_spec": "isarray@~1.0.0",
"_where": "C:\\Users\\user\\Desktop\\Singer-Composer\\node_modules\\readable-stream",
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"bugs": {
"url": "https://github.com/juliangruber/isarray/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "Array#isArray for older browsers",
"devDependencies": {
"tape": "~2.13.4"
},
"homepage": "https://github.com/juliangruber/isarray",
"keywords": [
"browser",
"isarray",
"array"
],
"license": "MIT",
"main": "index.js",
"name": "isarray",
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/isarray.git"
},
"scripts": {
"test": "tape test.js"
},
"testling": {
"files": "test.js",
"browsers": [
"ie/8..latest",
"firefox/17..latest",
"firefox/nightly",
"chrome/22..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
},
"version": "1.0.0"
}
var isArray = require('./');
var test = require('tape');
test('is array', function(t){
t.ok(isArray([]));
t.notOk(isArray({}));
t.notOk(isArray(null));
t.notOk(isArray(false));
var obj = {};
obj[0] = true;
t.notOk(isArray(obj));
var arr = [];
arr.foo = 'bar';
t.ok(isArray(arr));
t.end();
});
language: node_js
sudo: false
script: npm run coverage
node_js:
- '6'
- '7'
cache:
directories:
- node_modules
## [v2.0.0]
> Jun 5, 2018
See [Upgrading to v2.0.0](https://github.com/rstacruz/mocha-jsdom#upgrading-to-v200) for notes on how to update from an older version.
* [#32] - `jsdom` is now a direct dependency of `mocha-jsdom` :tada:
[#32]: https://github.com/rstacruz/mocha-jsdom/issues/32
[v2.0.0]: https://github.com/rstacruz/mocha-jsdom/compare/v1.2.0...v2.0.0
## [v1.2.0]
> Jun 5, 2018
* [#29] - Update Jsdom compatibility ([@RobLoach])
* [#31] - Update all npm dependencies
[#29]: https://github.com/rstacruz/mocha-jsdom/issues/29
[#31]: https://github.com/rstacruz/mocha-jsdom/issues/31
[@RobLoach]: https://github.com/robloach
[v1.2.0]: https://github.com/rstacruz/mocha-jsdom/compare/v1.1.0...v1.2.0
## [v1.1.0]
> Feb 22, 2016
* [#18] - Initialize global.window when it is undefined; fixes compatibility with [airbnb/enzyme][]. ([@moonboots])
[v1.1.0]: https://github.com/rstacruz/mocha-jsdom/compare/v1.0.0...v1.1.0
## [v1.0.0] - Jul 4, 2015
* Add testling/browserify support.
* Add more examples.
[v1.0.0]: https://github.com/rstacruz/mocha-jsdom/compare/v0.5.0...v1.0.0
## [v0.5.0] - Jun 26, 2015
* Add `rerequire()` to help with using mocha-jsdom with `mocha --watch`.
* Internal: change coding standard to feross/standard.
## [v0.4.0] - May 25, 2015
* [#5] - Add `useEach` option. ([@jasco], [#6])
* [#7] - Add a `skipWindowCheck` option.
## [v0.3.0] - Apr 3, 2015
* [#3] - Bump `jsdom` dependency version. This fixes the "needs a context" error ([@nacyot], [#3])
[#3]: https://github.com/rstacruz/mocha-jsdom/issues/3
[#4]: https://github.com/rstacruz/mocha-jsdom/issues/4
[@nacyot]: https://github.com/nacyot
## [v0.2.1] - Feb 19, 2014
* Add `LICENSE` file
* Update documentation
* No functionality changes
## [v0.2.0] - November 5, 2014
* Skip warnings. Add `JSDOM_VERBOSE=1` to your env to reenable them.
## [v0.1.2] - September 27, 2014
* Throw a useful error when invoked twice.
## [v0.1.1] - September 27, 2014
* Re-release with updated Readme.
[airbnb/enzyme]: https://github.com/airbnb/enzyme
## v0.1.0 - September 25, 2014
* Initial version.
[#5]: https://github.com/rstacruz/mocha-jsdom/issues/5
[#6]: https://github.com/rstacruz/mocha-jsdom/issues/6
[#7]: https://github.com/rstacruz/mocha-jsdom/issues/7
[@jasco]: https://github.com/jasco
[v0.5.0]: https://github.com/rstacruz/mocha-jsdom/compare/v0.4.0...v0.5.0
[v0.4.0]: https://github.com/rstacruz/mocha-jsdom/compare/v0.3.0...v0.4.0
[v0.3.0]: https://github.com/rstacruz/mocha-jsdom/compare/v0.2.1...v0.3.0
[v0.2.1]: https://github.com/rstacruz/mocha-jsdom/compare/v0.2.0...v0.2.1
[v0.2.0]: https://github.com/rstacruz/mocha-jsdom/compare/v0.1.2...v0.2.0
[v0.1.2]: https://github.com/rstacruz/mocha-jsdom/compare/v0.1.1...v0.1.2
[v0.1.1]: https://github.com/rstacruz/mocha-jsdom/compare/v0.1.0...v0.1.1
[#18]: https://github.com/rstacruz/mocha-jsdom/issues/18
[@moonboots]: https://github.com/moonboots
Copyright © 2015 Rico Sta. Cruz
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
> _Deprecation notice:_
> Consider [jsdom-global](https://github.com/rstacruz/jsdom-global) instead, a simpler alternative that also works outside of Mocha. `mocha-jsdom` still works, but `jsdom-global` is better supported.
---
# mocha-jsdom
> Test frontend libraries in the console using Node.js, [mocha] and [jsdom].
[![Status](https://travis-ci.org/rstacruz/mocha-jsdom.svg?branch=master)](https://travis-ci.org/rstacruz/mocha-jsdom "See test builds")
<br>
## Usage
```sh
$ npm i --save-dev mocha-jsdom
```
[![npm version](http://img.shields.io/npm/v/mocha-jsdom.svg?style=flat)](https://npmjs.org/package/mocha-jsdom "View this project on npm")
Use `jsdom()` inside your `describe(...)` block (or the global context). It will
turn your Node.js environment into a mock browser environment supporting the
full DOM and browser API. The variables `window`, `document`, `history` (and so
on) will then be available for use.
```js
var jsdom = require('mocha-jsdom')
var expect = require('chai').expect
describe('mocha tests', function () {
jsdom()
it('has document', function () {
var div = document.createElement('div')
expect(div.nodeName).eql('DIV')
})
})
```
See [examples/basic](examples/basic) for an example of a basic setup.
<br>
## Upgrading to v2.0.0
If you are coming from mocha-jsdom v1.x, remove `jsdom` if you're not using it before upgrading. `jsdom` is now a direct dependency of `mocha-jsdom`.
```bash
# using Yarn
yarn remove jsdom
yarn upgrade mocha-jsdom
```
```bash
# using npm
npm uninstall -S -D jsdom
npm upgrade mocha-jsdom
```
<br>
## Node and io.js information
As of jsdom 4.0.0, [jsdom now requires io.js](https://github.com/tmpvar/jsdom/blob/master/Changelog.md#400) and will not work with Node.js 0.12 or below.
<br>
## How it works
mocha-jsdom is a simple glue to integrate [jsdom] to mocha.
Invoking `jsdom()` will inject `before` and `after` handlers to the current
mocha suite which will setup and teardown jsdom. Here's what it does:
* __Window__: `global.window` will be available as the jsdom.
* __Globals__: global variables like `document` and `history` are propagated,
and they're cleaned up after tests run.
* __Error handling__: jsdom errors are sanitized so that their stack traces are
shortened.
__NB:__ Before you try this library, learn about jsdom first. In fact, you may be
able to integrate jsdom into your tests *without* this library; this is mostly
syntactic sugar and reasonable defaults.
<br>
## Using with a library
Perfect for testing small DOM-consuming utilities in the console. See
[test/jquery.js](test/jquery.js) for an example.
```js
describe('mocha tests', function () {
var $
jsdom()
before(function () {
$ = require('jquery')
})
it('works', function () {
document.body.innerHTML = '<div>hola</div>'
expect($("div").html()).eql('hola')
})
})
```
See [examples/basic](examples/basic) for an example of a basic setup.
<br>
## Using with a library, alternate
You can also pass the source code via `src`:
```js
describe('mocha tests', function () {
jsdom({
src: fs.readFileSync('jquery.js', 'utf-8')
})
...
})
```
<br>
## Configuration
You can pass jsdom options:
```js
describe('mocha tests', function () {
jsdom({
parsingMode: 'xml'
})
...
})
```
<br>
## Working with mocha --watch
When using with `--watch`, you my encounter strange errors from 3rd-party
libraries like jQuery not working properly.
In these cases, use `require('mocha-jsdom').rerequire` instead of `require()`.
This will ensure that the `require()` call will always happen.
```js
var $
var jsdom = require('mocha-jsdom')
var rerequire = jsdom.rerequire
jsdom()
before(function () {
$ = rerequire('jquery')
})
```
<br>
## Special config
Other mocha-jsdom specific options:
* `globalize` - propagates to values in `window` to `global`. defaults to true.
* `console` - allows you to use `console.log` inside a jsdom script. defaults
to true.
* `useEach` - bind to Mocha's `beforeEach`/`afterEach` rather than `before`/`after`.
defaults to false.
* `skipWindowCheck` - skips checking of `window` at startup. When false,
mocha-jsdom will throw an error if `window` already exists. Defaults to false.
[jsdom]: https://www.npmjs.org/package/jsdom
[mocha]: https://www.npmjs.com/package/mocha
<br>
## Testling support
Yes, fully compatible with testling. A test suite using jsdom should be able to use testling.
See [examples/basic](examples/basic/) for a setup that allows for testing via iojs (jsdom), testling, and mocha via the browser.
<br>
## Thanks
> **mocha-jsdom** © 2014-2018 Rico Sta. Cruz. Released under the [MIT] License.<br>
> Authored and maintained by Rico Sta. Cruz with help from contributors ([list][contributors]).
[![](https://img.shields.io/github/followers/rstacruz.svg?style=social&label=@rstacruz)](https://github.com/rstacruz)
&nbsp;&nbsp;
[![](https://img.shields.io/twitter/follow/rstacruz.svg?style=social&label=@rstacruz)](https://twitter.com/rstacruz)
&nbsp;&nbsp;
**[ricostacruz.com](http://ricostacruz.com)**
[mit]: http://mit-license.org/
[contributors]: http://github.com/rstacruz/mocha-jsdom/contributors
/*
* A noop version in case your tests are browserified (eg, when using
* testling).
*/
module.exports = function () {}
This is a basic example of what you can put in your project's `test/` folder.
It will allow you to run tests in both jsdom (iojs/node) and the browser.
<!doctype html>
<html>
<head>
<title>Mocha</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet" />
</head>
<body>
<div id="mocha"></div>
<script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
<script src="https://cdn.rawgit.com/chaijs/chai/2.3.0/chai.js"></script>
<script>mocha.setup('bdd')</script>
<!-- thing to test -->
<script src="../index.js"></script>
<!-- your test files -->
<script src="setup.js"></script>
<script src="test.js"></script>
<script>mocha.run()</script>
</body>
</html>
if (typeof process === 'object') {
// Initialize node environment
global.expect = require('chai').expect
require('mocha-jsdom')()
} else {
window.expect = window.chai.expect
window.require = function () { /* noop */ }
}
/* global describe, it, before, expect */
require('./setup')
describe('my library', function () {
var mylib
before(function () {
mylib = require('mylib') || window.mylib
})
it('works', function () {
expect(mylib.greet()).to.eql('hola')
})
})
These examples are here so you can see what failures look like.
Run `mocha one.js` or `mocha two.js` to see.
/* global it, expect, describe */
/* jshint expr: true */
var jsdom = require('../../index')
describe('error', function () {
jsdom({
src: "(function () { throw new Error('ffff'); })()"
})
it('fails', function () {
expect(global.document).be.undefined // eslint-disable-line no-unused-expressions
})
})
/* global describe, it, expect */
describe('src', function () {
require('../../index')({
src: '}}'
})
it('works', function () {
expect(window.lol()).eql('DIV')
})
})
var extend = Object.assign || require('util')._extend // eslint-disable-line node/no-deprecated-api
var Path = require('path')
/*
* store original global keys
*/
var blacklist = Object.keys(global)
blacklist.push('constructor')
/*
* default config
*/
var defaults = {
globalize: true,
console: true,
useEach: false,
skipWindowCheck: false,
html:
"<!doctype html><html><head><meta charset='utf-8'></head>" +
'<body></body></html>'
}
/*
* simple jsdom integration.
* You can pass jsdom options in, too:
*
* require('./support/jsdom')({
* src: [ jquery ]
* })
*/
module.exports = function (_options) {
var options = extend(extend({}, defaults), _options)
var keys = []
var before = options.useEach ? global.beforeEach : global.before
var after = options.useEach ? global.afterEach : global.after
/*
* register jsdom before the entire test suite
*/
before(function (next) {
if (global.window && !options.skipWindowCheck) {
throw new Error(
'mocha-jsdom: already a browser environment, or mocha-jsdom invoked ' +
"twice. use 'skipWindowCheck' to disable this check."
)
}
require('jsdom/lib/old-api').env(
extend(extend({}, options), { done: done })
)
function done (errors, window) {
if (options.globalize) {
propagateToGlobal(window)
} else {
global.window = window
}
if (options.console) {
window.console = global.console
}
if (errors) {
return next(getError(errors))
}
next(null)
}
})
/*
* undo keys from being propagated to global after the test suite
*/
after(function () {
if (options.globalize) {
keys.forEach(function (key) {
delete global[key]
})
} else {
delete global.window
}
})
/*
* propagate keys from `window` to `global`
*/
function propagateToGlobal (window) {
for (var key in window) {
if (!window.hasOwnProperty(key)) continue
if (~blacklist.indexOf(key)) continue
if (global[key]) {
if (process.env.JSDOM_VERBOSE) {
console.warn(
"[jsdom] Warning: skipping cleanup of global['" + key + "']"
)
}
continue
}
keys.push(key)
global[key] = window[key]
}
}
/*
* re-throws jsdom errors
*/
function getError (errors) {
var data = errors[0].data
var err = data.error
err.message = err.message + ' [jsdom]'
// clean up stack trace
if (err.stack) {
err.stack = err.stack
.split('\n')
.reduce(function (list, line) {
if (line.match(/node_modules.+(jsdom|mocha)/)) {
return list
}
line = line
.replace(/file:\/\/.*<script>/g, '<script>')
.replace(/:undefined:undefined/g, '')
list.push(line)
return list
}, [])
.join('\n')
}
return err
}
}
module.exports.rerequire = rerequire
/**
* Requires a module via `require()`, but invalidates the cache so it may be
* called again in the future. Useful for `mocha --watch`.
*
* var rerequire = require('mocha-jsdom').rerequire
* var $ = rerequire('jquery')
*/
function rerequire (module) {
if (module[0] === '.') {
module = Path.join(Path.dirname(getCaller()), module)
}
var oldkeys = Object.keys(require.cache)
var result = require(module)
var newkeys = Object.keys(require.cache)
newkeys.forEach(function (newkey) {
if (!~oldkeys.indexOf(newkey)) {
delete require.cache[newkey]
}
})
return result
}
/**
* Internal: gets the filename of the caller function. The `offset` defines how
* many hops away it's expected to be from in the stack trace.
*
* See: http://stackoverflow.com/questions/16697791/nodejs-get-filename-of-caller-function
*/
function getCaller (offset) {
/* eslint-disable handle-callback-err */
if (typeof offset !== 'number') offset = 1
var old = Error.prepareStackTrace
var err = new Error()
Error.prepareStackTrace = function (err, stack) {
return stack
}
var fname = err.stack[1 + offset].getFileName()
Error.prepareStackTrace = old
return fname
}
{
"_args": [
[
"mocha-jsdom@2.0.0",
"C:\\Users\\user\\Desktop\\Singer-Composer"
]
],
"_development": true,
"_from": "mocha-jsdom@2.0.0",
"_id": "mocha-jsdom@2.0.0",
"_inBundle": false,
"_integrity": "sha512-+3D++FPXHXEesbBD7Q/r4dkc3XzVFMPLJVIECaQ685dj9qKQYzliqX8IXyIUbUL4x1QfgD9h8Zao8cn03NKKEA==",
"_location": "/mocha-jsdom",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "mocha-jsdom@2.0.0",
"name": "mocha-jsdom",
"escapedName": "mocha-jsdom",
"rawSpec": "2.0.0",
"saveSpec": null,
"fetchSpec": "2.0.0"
},
"_requiredBy": [
"#DEV:/"
],
"_resolved": "https://registry.npmjs.org/mocha-jsdom/-/mocha-jsdom-2.0.0.tgz",
"_spec": "2.0.0",
"_where": "C:\\Users\\user\\Desktop\\Singer-Composer",
"author": {
"name": "Rico Sta. Cruz",
"email": "rico@ricostacruz.com"
},
"browser": "browser.js",
"bugs": {
"url": "https://github.com/rstacruz/mocha-jsdom/issues"
},
"dependencies": {
"jsdom": "^11.11.0"
},
"description": "Simple integration of jsdom into mocha tests",
"devDependencies": {
"chai": "4.1.2",
"istanbul": "0.4.5",
"jquery": "3.3.1",
"mocha": "5.2.0",
"mocha-standard": "1.0.0",
"standard": "11.0.1"
},
"directories": {
"test": "test"
},
"homepage": "https://github.com/rstacruz/mocha-jsdom#readme",
"keywords": [
"jsdom",
"mocha"
],
"license": "MIT",
"main": "index.js",
"name": "mocha-jsdom",
"peerDependencies": {
"mocha": "*"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rstacruz/mocha-jsdom.git"
},
"scripts": {
"coverage": "istanbul cover _mocha -- -R spec",
"test": "mocha"
},
"version": "2.0.0"
}
/* this module will have side effects if it's ran more than once.
* we're gonna test for that. */
global._rerequirable_count++
/* global describe, it, expect */
/* jshint expr: true */
var jsdom = require('../index')
describe('globalize', function () {
jsdom({ globalize: false })
it('does not globalize', function () {
expect(global.document).be.undefined // eslint-disable-line no-unused-expressions
})
})
/* global describe, before, it, document, expect */
var jsdom = require('../index')
describe('jquery', function () {
var $
jsdom()
before(function () {
$ = require('jquery')
})
it('creating elements works', function () {
var div = $('<div>hello <b>world</b></div>')
expect(div.html()).to.eql('hello <b>world</b>')
})
it('lookup works', function () {
document.body.innerHTML = '<div>hola</div>'
expect($('div').html()).eql('hola')
})
})
--require test/setup
--timeout 5000
/* global describe, it, beforeEach, expect */
var rerequire = require('../index').rerequire
describe('rerequire', function () {
beforeEach(function () {
global._rerequirable_count = 0
})
it('has a fixture that works', function () {
rerequire('./fixtures/rerequirable')
expect(global._rerequirable_count).eql(1)
})
// ensure that subsequent runs don't bother
it('has a fixture that really works', function () {
rerequire('./fixtures/rerequirable')
expect(global._rerequirable_count).eql(1)
})
it('works 5x', function () {
rerequire('./fixtures/rerequirable')
rerequire('./fixtures/rerequirable')
rerequire('./fixtures/rerequirable')
rerequire('./fixtures/rerequirable')
rerequire('./fixtures/rerequirable')
expect(global._rerequirable_count).eql(5)
})
})
/* global it, before, window, describe, expect */
var jsdom = require('../index')
describe('robust', function () {
before(function () {
// User or another test framework redefines global.window
global.window = undefined
})
jsdom()
it('has window', function () {
expect(global.window).to.not.be.undefined // eslint-disable-line no-unused-expressions
})
})
global.expect = require('chai').expect
/* global it, history, describe, location, expect */
var jsdom = require('../index')
describe('simple', function () {
jsdom()
it('has document', function () {
var div = document.createElement('div')
expect(div.nodeName).eql('DIV')
})
it('has history', function () {
history.pushState({}, 'abc', '#/a/b/c')
expect(location.href).match(/\/a\/b\/c$/)
})
})
/* global describe, it, before, after, expect */
/* jshint expr: true */
var jsdom = require('../index')
describe('skipWindowCheck: true', function () {
before(function () {
global.window = {}
})
after(function () {
delete global.window
})
jsdom({ skipWindowCheck: true })
it('does not throw errors', function () {
var div = document.createElement('div')
expect(div.nodeName).eql('DIV')
})
})
/* global describe, it */
describe('standard', function () {
it('is conformed to', require('mocha-standard'))
})
/* global describe, it, expect */
/* jshint expr: true */
var jsdom = require('../index')
describe('check useEach false (default)', function () {
var someContent = '<div>hola</div>'
jsdom()
it('check that html body is empty', function () {
expect(document.body.innerHTML).to.be.empty // eslint-disable-line no-unused-expressions
})
it('accepts an html body', function () {
document.body.innerHTML = someContent
expect(document.body.innerHTML).eql(someContent)
})
it('has document persisting across tests', function () {
expect(document.body.innerHTML).eql(someContent)
})
})
describe('check useEach true', function () {
var someContent = '<div>hola</div>'
jsdom({ useEach: true })
it('check that html body is empty', function () {
expect(document.body.innerHTML).to.be.empty // eslint-disable-line no-unused-expressions
})
it('accepts an html body', function () {
document.body.innerHTML = someContent
expect(document.body.innerHTML).eql(someContent)
})
it('changes to the dom do not persist between tests', function () {
expect(document.body.innerHTML).to.be.empty // eslint-disable-line no-unused-expressions
})
})
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
This diff is collapsed. Click to expand it.
var Classes = Object.create(null);
/**
* Create a new Connection instance.
* @param {object|string} config Configuration or connection string for new MySQL connection
* @return {Connection} A new MySQL connection
* @public
*/
exports.createConnection = function createConnection(config) {
var Connection = loadClass('Connection');
var ConnectionConfig = loadClass('ConnectionConfig');
return new Connection({config: new ConnectionConfig(config)});
};
/**
* Create a new Pool instance.
* @param {object|string} config Configuration or connection string for new MySQL connections
* @return {Pool} A new MySQL pool
* @public
*/
exports.createPool = function createPool(config) {
var Pool = loadClass('Pool');
var PoolConfig = loadClass('PoolConfig');
return new Pool({config: new PoolConfig(config)});
};
/**
* Create a new PoolCluster instance.
* @param {object} [config] Configuration for pool cluster
* @return {PoolCluster} New MySQL pool cluster
* @public
*/
exports.createPoolCluster = function createPoolCluster(config) {
var PoolCluster = loadClass('PoolCluster');
return new PoolCluster(config);
};
/**
* Create a new Query instance.
* @param {string} sql The SQL for the query
* @param {array} [values] Any values to insert into placeholders in sql
* @param {function} [callback] The callback to use when query is complete
* @return {Query} New query object
* @public
*/
exports.createQuery = function createQuery(sql, values, callback) {
var Connection = loadClass('Connection');
return Connection.createQuery(sql, values, callback);
};
/**
* Escape a value for SQL.
* @param {*} value The value to escape
* @param {boolean} [stringifyObjects=false] Setting if objects should be stringified
* @param {string} [timeZone=local] Setting for time zone to use for Date conversion
* @return {string} Escaped string value
* @public
*/
exports.escape = function escape(value, stringifyObjects, timeZone) {
var SqlString = loadClass('SqlString');
return SqlString.escape(value, stringifyObjects, timeZone);
};
/**
* Escape an identifier for SQL.
* @param {*} value The value to escape
* @param {boolean} [forbidQualified=false] Setting to treat '.' as part of identifier
* @return {string} Escaped string value
* @public
*/
exports.escapeId = function escapeId(value, forbidQualified) {
var SqlString = loadClass('SqlString');
return SqlString.escapeId(value, forbidQualified);
};
/**
* Format SQL and replacement values into a SQL string.
* @param {string} sql The SQL for the query
* @param {array} [values] Any values to insert into placeholders in sql
* @param {boolean} [stringifyObjects=false] Setting if objects should be stringified
* @param {string} [timeZone=local] Setting for time zone to use for Date conversion
* @return {string} Formatted SQL string
* @public
*/
exports.format = function format(sql, values, stringifyObjects, timeZone) {
var SqlString = loadClass('SqlString');
return SqlString.format(sql, values, stringifyObjects, timeZone);
};
/**
* Wrap raw SQL strings from escape overriding.
* @param {string} sql The raw SQL
* @return {object} Wrapped object
* @public
*/
exports.raw = function raw(sql) {
var SqlString = loadClass('SqlString');
return SqlString.raw(sql);
};
/**
* The type constants.
* @public
*/
Object.defineProperty(exports, 'Types', {
get: loadClass.bind(null, 'Types')
});
/**
* Load the given class.
* @param {string} className Name of class to default
* @return {function|object} Class constructor or exports
* @private
*/
function loadClass(className) {
var Class = Classes[className];
if (Class !== undefined) {
return Class;
}
// This uses a switch for static require analysis
switch (className) {
case 'Connection':
Class = require('./lib/Connection');
break;
case 'ConnectionConfig':
Class = require('./lib/ConnectionConfig');
break;
case 'Pool':
Class = require('./lib/Pool');
break;
case 'PoolCluster':
Class = require('./lib/PoolCluster');
break;
case 'PoolConfig':
Class = require('./lib/PoolConfig');
break;
case 'SqlString':
Class = require('./lib/protocol/SqlString');
break;
case 'Types':
Class = require('./lib/protocol/constants/types');
break;
default:
throw new Error('Cannot find class \'' + className + '\'');
}
// Store to prevent invoking require()
Classes[className] = Class;
return Class;
}
This diff is collapsed. Click to expand it.
var urlParse = require('url').parse;
var ClientConstants = require('./protocol/constants/client');
var Charsets = require('./protocol/constants/charsets');
var SSLProfiles = null;
module.exports = ConnectionConfig;
function ConnectionConfig(options) {
if (typeof options === 'string') {
options = ConnectionConfig.parseUrl(options);
}
this.host = options.host || 'localhost';
this.port = options.port || 3306;
this.localAddress = options.localAddress;
this.socketPath = options.socketPath;
this.user = options.user || undefined;
this.password = options.password || undefined;
this.database = options.database;
this.connectTimeout = (options.connectTimeout === undefined)
? (10 * 1000)
: options.connectTimeout;
this.insecureAuth = options.insecureAuth || false;
this.supportBigNumbers = options.supportBigNumbers || false;
this.bigNumberStrings = options.bigNumberStrings || false;
this.dateStrings = options.dateStrings || false;
this.debug = options.debug;
this.trace = options.trace !== false;
this.stringifyObjects = options.stringifyObjects || false;
this.timezone = options.timezone || 'local';
this.flags = options.flags || '';
this.queryFormat = options.queryFormat;
this.pool = options.pool || undefined;
this.ssl = (typeof options.ssl === 'string')
? ConnectionConfig.getSSLProfile(options.ssl)
: (options.ssl || false);
this.localInfile = (options.localInfile === undefined)
? true
: options.localInfile;
this.multipleStatements = options.multipleStatements || false;
this.typeCast = (options.typeCast === undefined)
? true
: options.typeCast;
if (this.timezone[0] === ' ') {
// "+" is a url encoded char for space so it
// gets translated to space when giving a
// connection string..
this.timezone = '+' + this.timezone.substr(1);
}
if (this.ssl) {
// Default rejectUnauthorized to true
this.ssl.rejectUnauthorized = this.ssl.rejectUnauthorized !== false;
}
this.maxPacketSize = 0;
this.charsetNumber = (options.charset)
? ConnectionConfig.getCharsetNumber(options.charset)
: options.charsetNumber || Charsets.UTF8_GENERAL_CI;
// Set the client flags
var defaultFlags = ConnectionConfig.getDefaultFlags(options);
this.clientFlags = ConnectionConfig.mergeFlags(defaultFlags, options.flags);
}
ConnectionConfig.mergeFlags = function mergeFlags(defaultFlags, userFlags) {
var allFlags = ConnectionConfig.parseFlagList(defaultFlags);
var newFlags = ConnectionConfig.parseFlagList(userFlags);
// Merge the new flags
for (var flag in newFlags) {
if (allFlags[flag] !== false) {
allFlags[flag] = newFlags[flag];
}
}
// Build flags
var flags = 0x0;
for (var flag in allFlags) {
if (allFlags[flag]) {
// TODO: Throw here on some future release
flags |= ClientConstants['CLIENT_' + flag] || 0x0;
}
}
return flags;
};
ConnectionConfig.getCharsetNumber = function getCharsetNumber(charset) {
var num = Charsets[charset.toUpperCase()];
if (num === undefined) {
throw new TypeError('Unknown charset \'' + charset + '\'');
}
return num;
};
ConnectionConfig.getDefaultFlags = function getDefaultFlags(options) {
var defaultFlags = [
'-COMPRESS', // Compression protocol *NOT* supported
'-CONNECT_ATTRS', // Does *NOT* send connection attributes in Protocol::HandshakeResponse41
'+CONNECT_WITH_DB', // One can specify db on connect in Handshake Response Packet
'+FOUND_ROWS', // Send found rows instead of affected rows
'+IGNORE_SIGPIPE', // Don't issue SIGPIPE if network failures
'+IGNORE_SPACE', // Let the parser ignore spaces before '('
'+LOCAL_FILES', // Can use LOAD DATA LOCAL
'+LONG_FLAG', // Longer flags in Protocol::ColumnDefinition320
'+LONG_PASSWORD', // Use the improved version of Old Password Authentication
'+MULTI_RESULTS', // Can handle multiple resultsets for COM_QUERY
'+ODBC', // Special handling of ODBC behaviour
'-PLUGIN_AUTH', // Does *NOT* support auth plugins
'+PROTOCOL_41', // Uses the 4.1 protocol
'+PS_MULTI_RESULTS', // Can handle multiple resultsets for COM_STMT_EXECUTE
'+RESERVED', // Unused
'+SECURE_CONNECTION', // Supports Authentication::Native41
'+TRANSACTIONS' // Expects status flags
];
if (options && options.localInfile !== undefined && !options.localInfile) {
// Disable LOCAL modifier for LOAD DATA INFILE
defaultFlags.push('-LOCAL_FILES');
}
if (options && options.multipleStatements) {
// May send multiple statements per COM_QUERY and COM_STMT_PREPARE
defaultFlags.push('+MULTI_STATEMENTS');
}
return defaultFlags;
};
ConnectionConfig.getSSLProfile = function getSSLProfile(name) {
if (!SSLProfiles) {
SSLProfiles = require('./protocol/constants/ssl_profiles');
}
var ssl = SSLProfiles[name];
if (ssl === undefined) {
throw new TypeError('Unknown SSL profile \'' + name + '\'');
}
return ssl;
};
ConnectionConfig.parseFlagList = function parseFlagList(flagList) {
var allFlags = Object.create(null);
if (!flagList) {
return allFlags;
}
var flags = !Array.isArray(flagList)
? String(flagList || '').toUpperCase().split(/\s*,+\s*/)
: flagList;
for (var i = 0; i < flags.length; i++) {
var flag = flags[i];
var offset = 1;
var state = flag[0];
if (state === undefined) {
// TODO: throw here on some future release
continue;
}
if (state !== '-' && state !== '+') {
offset = 0;
state = '+';
}
allFlags[flag.substr(offset)] = state === '+';
}
return allFlags;
};
ConnectionConfig.parseUrl = function(url) {
url = urlParse(url, true);
var options = {
host : url.hostname,
port : url.port,
database : url.pathname.substr(1)
};
if (url.auth) {
var auth = url.auth.split(':');
options.user = auth.shift();
options.password = auth.join(':');
}
if (url.query) {
for (var key in url.query) {
var value = url.query[key];
try {
// Try to parse this as a JSON expression first
options[key] = JSON.parse(value);
} catch (err) {
// Otherwise assume it is a plain string
options[key] = value;
}
}
}
return options;
};
var mysql = require('../');
var Connection = require('./Connection');
var EventEmitter = require('events').EventEmitter;
var Util = require('util');
var PoolConnection = require('./PoolConnection');
module.exports = Pool;
Util.inherits(Pool, EventEmitter);
function Pool(options) {
EventEmitter.call(this);
this.config = options.config;
this.config.connectionConfig.pool = this;
this._acquiringConnections = [];
this._allConnections = [];
this._freeConnections = [];
this._connectionQueue = [];
this._closed = false;
}
Pool.prototype.getConnection = function (cb) {
if (this._closed) {
var err = new Error('Pool is closed.');
err.code = 'POOL_CLOSED';
process.nextTick(function () {
cb(err);
});
return;
}
var connection;
var pool = this;
if (this._freeConnections.length > 0) {
connection = this._freeConnections.shift();
this.acquireConnection(connection, cb);
return;
}
if (this.config.connectionLimit === 0 || this._allConnections.length < this.config.connectionLimit) {
connection = new PoolConnection(this, { config: this.config.newConnectionConfig() });
this._acquiringConnections.push(connection);
this._allConnections.push(connection);
connection.connect({timeout: this.config.acquireTimeout}, function onConnect(err) {
spliceConnection(pool._acquiringConnections, connection);
if (pool._closed) {
err = new Error('Pool is closed.');
err.code = 'POOL_CLOSED';
}
if (err) {
pool._purgeConnection(connection);
cb(err);
return;
}
pool.emit('connection', connection);
pool.emit('acquire', connection);
cb(null, connection);
});
return;
}
if (!this.config.waitForConnections) {
process.nextTick(function(){
var err = new Error('No connections available.');
err.code = 'POOL_CONNLIMIT';
cb(err);
});
return;
}
this._enqueueCallback(cb);
};
Pool.prototype.acquireConnection = function acquireConnection(connection, cb) {
if (connection._pool !== this) {
throw new Error('Connection acquired from wrong pool.');
}
var changeUser = this._needsChangeUser(connection);
var pool = this;
this._acquiringConnections.push(connection);
function onOperationComplete(err) {
spliceConnection(pool._acquiringConnections, connection);
if (pool._closed) {
err = new Error('Pool is closed.');
err.code = 'POOL_CLOSED';
}
if (err) {
pool._connectionQueue.unshift(cb);
pool._purgeConnection(connection);
return;
}
if (changeUser) {
pool.emit('connection', connection);
}
pool.emit('acquire', connection);
cb(null, connection);
}
if (changeUser) {
// restore user back to pool configuration
connection.config = this.config.newConnectionConfig();
connection.changeUser({timeout: this.config.acquireTimeout}, onOperationComplete);
} else {
// ping connection
connection.ping({timeout: this.config.acquireTimeout}, onOperationComplete);
}
};
Pool.prototype.releaseConnection = function releaseConnection(connection) {
if (this._acquiringConnections.indexOf(connection) !== -1) {
// connection is being acquired
return;
}
if (connection._pool) {
if (connection._pool !== this) {
throw new Error('Connection released to wrong pool');
}
if (this._freeConnections.indexOf(connection) !== -1) {
// connection already in free connection pool
// this won't catch all double-release cases
throw new Error('Connection already released');
} else {
// add connection to end of free queue
this._freeConnections.push(connection);
this.emit('release', connection);
}
}
if (this._closed) {
// empty the connection queue
this._connectionQueue.splice(0).forEach(function (cb) {
var err = new Error('Pool is closed.');
err.code = 'POOL_CLOSED';
process.nextTick(function () {
cb(err);
});
});
} else if (this._connectionQueue.length) {
// get connection with next waiting callback
this.getConnection(this._connectionQueue.shift());
}
};
Pool.prototype.end = function (cb) {
this._closed = true;
if (typeof cb !== 'function') {
cb = function (err) {
if (err) throw err;
};
}
var calledBack = false;
var waitingClose = 0;
function onEnd(err) {
if (!calledBack && (err || --waitingClose <= 0)) {
calledBack = true;
cb(err);
}
}
while (this._allConnections.length !== 0) {
waitingClose++;
this._purgeConnection(this._allConnections[0], onEnd);
}
if (waitingClose === 0) {
process.nextTick(onEnd);
}
};
Pool.prototype.query = function (sql, values, cb) {
var query = Connection.createQuery(sql, values, cb);
if (!(typeof sql === 'object' && 'typeCast' in sql)) {
query.typeCast = this.config.connectionConfig.typeCast;
}
if (this.config.connectionConfig.trace) {
// Long stack trace support
query._callSite = new Error();
}
this.getConnection(function (err, conn) {
if (err) {
query.on('error', function () {});
query.end(err);
return;
}
// Release connection based off event
query.once('end', function() {
conn.release();
});
conn.query(query);
});
return query;
};
Pool.prototype._enqueueCallback = function _enqueueCallback(callback) {
if (this.config.queueLimit && this._connectionQueue.length >= this.config.queueLimit) {
process.nextTick(function () {
var err = new Error('Queue limit reached.');
err.code = 'POOL_ENQUEUELIMIT';
callback(err);
});
return;
}
// Bind to domain, as dequeue will likely occur in a different domain
var cb = process.domain
? process.domain.bind(callback)
: callback;
this._connectionQueue.push(cb);
this.emit('enqueue');
};
Pool.prototype._needsChangeUser = function _needsChangeUser(connection) {
var connConfig = connection.config;
var poolConfig = this.config.connectionConfig;
// check if changeUser values are different
return connConfig.user !== poolConfig.user
|| connConfig.database !== poolConfig.database
|| connConfig.password !== poolConfig.password
|| connConfig.charsetNumber !== poolConfig.charsetNumber;
};
Pool.prototype._purgeConnection = function _purgeConnection(connection, callback) {
var cb = callback || function () {};
if (connection.state === 'disconnected') {
connection.destroy();
}
this._removeConnection(connection);
if (connection.state !== 'disconnected' && !connection._protocol._quitSequence) {
connection._realEnd(cb);
return;
}
process.nextTick(cb);
};
Pool.prototype._removeConnection = function(connection) {
connection._pool = null;
// Remove connection from all connections
spliceConnection(this._allConnections, connection);
// Remove connection from free connections
spliceConnection(this._freeConnections, connection);
this.releaseConnection(connection);
};
Pool.prototype.escape = function(value) {
return mysql.escape(value, this.config.connectionConfig.stringifyObjects, this.config.connectionConfig.timezone);
};
Pool.prototype.escapeId = function escapeId(value) {
return mysql.escapeId(value, false);
};
function spliceConnection(array, connection) {
var index;
if ((index = array.indexOf(connection)) !== -1) {
// Remove connection from all connections
array.splice(index, 1);
}
}
var Pool = require('./Pool');
var PoolConfig = require('./PoolConfig');
var PoolNamespace = require('./PoolNamespace');
var PoolSelector = require('./PoolSelector');
var Util = require('util');
var EventEmitter = require('events').EventEmitter;
module.exports = PoolCluster;
/**
* PoolCluster
* @constructor
* @param {object} [config] The pool cluster configuration
* @public
*/
function PoolCluster(config) {
EventEmitter.call(this);
config = config || {};
this._canRetry = typeof config.canRetry === 'undefined' ? true : config.canRetry;
this._defaultSelector = config.defaultSelector || 'RR';
this._removeNodeErrorCount = config.removeNodeErrorCount || 5;
this._restoreNodeTimeout = config.restoreNodeTimeout || 0;
this._closed = false;
this._findCaches = Object.create(null);
this._lastId = 0;
this._namespaces = Object.create(null);
this._nodes = Object.create(null);
}
Util.inherits(PoolCluster, EventEmitter);
PoolCluster.prototype.add = function add(id, config) {
if (this._closed) {
throw new Error('PoolCluster is closed.');
}
var nodeId = typeof id === 'object'
? 'CLUSTER::' + (++this._lastId)
: String(id);
if (this._nodes[nodeId] !== undefined) {
throw new Error('Node ID "' + nodeId + '" is already defined in PoolCluster.');
}
var poolConfig = typeof id !== 'object'
? new PoolConfig(config)
: new PoolConfig(id);
this._nodes[nodeId] = {
id : nodeId,
errorCount : 0,
pool : new Pool({config: poolConfig}),
_offlineUntil : 0
};
this._clearFindCaches();
};
PoolCluster.prototype.end = function end(callback) {
var cb = callback !== undefined
? callback
: _cb;
if (typeof cb !== 'function') {
throw TypeError('callback argument must be a function');
}
if (this._closed) {
process.nextTick(cb);
return;
}
this._closed = true;
var calledBack = false;
var nodeIds = Object.keys(this._nodes);
var waitingClose = 0;
function onEnd(err) {
if (!calledBack && (err || --waitingClose <= 0)) {
calledBack = true;
cb(err);
}
}
for (var i = 0; i < nodeIds.length; i++) {
var nodeId = nodeIds[i];
var node = this._nodes[nodeId];
waitingClose++;
node.pool.end(onEnd);
}
if (waitingClose === 0) {
process.nextTick(onEnd);
}
};
PoolCluster.prototype.of = function(pattern, selector) {
pattern = pattern || '*';
selector = selector || this._defaultSelector;
selector = selector.toUpperCase();
if (typeof PoolSelector[selector] === 'undefined') {
selector = this._defaultSelector;
}
var key = pattern + selector;
if (typeof this._namespaces[key] === 'undefined') {
this._namespaces[key] = new PoolNamespace(this, pattern, selector);
}
return this._namespaces[key];
};
PoolCluster.prototype.remove = function remove(pattern) {
var foundNodeIds = this._findNodeIds(pattern, true);
for (var i = 0; i < foundNodeIds.length; i++) {
var node = this._getNode(foundNodeIds[i]);
if (node) {
this._removeNode(node);
}
}
};
PoolCluster.prototype.getConnection = function(pattern, selector, cb) {
var namespace;
if (typeof pattern === 'function') {
cb = pattern;
namespace = this.of();
} else {
if (typeof selector === 'function') {
cb = selector;
selector = this._defaultSelector;
}
namespace = this.of(pattern, selector);
}
namespace.getConnection(cb);
};
PoolCluster.prototype._clearFindCaches = function _clearFindCaches() {
this._findCaches = Object.create(null);
};
PoolCluster.prototype._decreaseErrorCount = function _decreaseErrorCount(node) {
var errorCount = node.errorCount;
if (errorCount > this._removeNodeErrorCount) {
errorCount = this._removeNodeErrorCount;
}
if (errorCount < 1) {
errorCount = 1;
}
node.errorCount = errorCount - 1;
if (node._offlineUntil) {
node._offlineUntil = 0;
this.emit('online', node.id);
}
};
PoolCluster.prototype._findNodeIds = function _findNodeIds(pattern, includeOffline) {
var currentTime = 0;
var foundNodeIds = this._findCaches[pattern];
if (foundNodeIds === undefined) {
var expression = patternRegExp(pattern);
var nodeIds = Object.keys(this._nodes);
foundNodeIds = nodeIds.filter(function (id) {
return id.match(expression);
});
this._findCaches[pattern] = foundNodeIds;
}
if (includeOffline) {
return foundNodeIds;
}
return foundNodeIds.filter(function (nodeId) {
var node = this._getNode(nodeId);
if (!node._offlineUntil) {
return true;
}
if (!currentTime) {
currentTime = getMonotonicMilliseconds();
}
return node._offlineUntil <= currentTime;
}, this);
};
PoolCluster.prototype._getNode = function _getNode(id) {
return this._nodes[id] || null;
};
PoolCluster.prototype._increaseErrorCount = function _increaseErrorCount(node) {
var errorCount = ++node.errorCount;
if (this._removeNodeErrorCount > errorCount) {
return;
}
if (this._restoreNodeTimeout > 0) {
node._offlineUntil = getMonotonicMilliseconds() + this._restoreNodeTimeout;
this.emit('offline', node.id);
return;
}
this._removeNode(node);
this.emit('remove', node.id);
};
PoolCluster.prototype._getConnection = function(node, cb) {
var self = this;
node.pool.getConnection(function (err, connection) {
if (err) {
self._increaseErrorCount(node);
cb(err);
return;
} else {
self._decreaseErrorCount(node);
}
connection._clusterId = node.id;
cb(null, connection);
});
};
PoolCluster.prototype._removeNode = function _removeNode(node) {
delete this._nodes[node.id];
this._clearFindCaches();
node.pool.end(_noop);
};
function getMonotonicMilliseconds() {
var ms;
if (typeof process.hrtime === 'function') {
ms = process.hrtime();
ms = ms[0] * 1e3 + ms[1] * 1e-6;
} else {
ms = process.uptime() * 1000;
}
return Math.floor(ms);
}
function isRegExp(val) {
return typeof val === 'object'
&& Object.prototype.toString.call(val) === '[object RegExp]';
}
function patternRegExp(pattern) {
if (isRegExp(pattern)) {
return pattern;
}
var source = pattern
.replace(/([.+?^=!:${}()|\[\]\/\\])/g, '\\$1')
.replace(/\*/g, '.*');
return new RegExp('^' + source + '$');
}
function _cb(err) {
if (err) {
throw err;
}
}
function _noop() {}
var ConnectionConfig = require('./ConnectionConfig');
module.exports = PoolConfig;
function PoolConfig(options) {
if (typeof options === 'string') {
options = ConnectionConfig.parseUrl(options);
}
this.acquireTimeout = (options.acquireTimeout === undefined)
? 10 * 1000
: Number(options.acquireTimeout);
this.connectionConfig = new ConnectionConfig(options);
this.waitForConnections = (options.waitForConnections === undefined)
? true
: Boolean(options.waitForConnections);
this.connectionLimit = (options.connectionLimit === undefined)
? 10
: Number(options.connectionLimit);
this.queueLimit = (options.queueLimit === undefined)
? 0
: Number(options.queueLimit);
}
PoolConfig.prototype.newConnectionConfig = function newConnectionConfig() {
var connectionConfig = new ConnectionConfig(this.connectionConfig);
connectionConfig.clientFlags = this.connectionConfig.clientFlags;
connectionConfig.maxPacketSize = this.connectionConfig.maxPacketSize;
return connectionConfig;
};
var inherits = require('util').inherits;
var Connection = require('./Connection');
var Events = require('events');
module.exports = PoolConnection;
inherits(PoolConnection, Connection);
function PoolConnection(pool, options) {
Connection.call(this, options);
this._pool = pool;
// Bind connection to pool domain
if (Events.usingDomains) {
this.domain = pool.domain;
}
// When a fatal error occurs the connection's protocol ends, which will cause
// the connection to end as well, thus we only need to watch for the end event
// and we will be notified of disconnects.
this.on('end', this._removeFromPool);
this.on('error', function (err) {
if (err.fatal) {
this._removeFromPool();
}
});
}
PoolConnection.prototype.release = function release() {
var pool = this._pool;
if (!pool || pool._closed) {
return undefined;
}
return pool.releaseConnection(this);
};
// TODO: Remove this when we are removing PoolConnection#end
PoolConnection.prototype._realEnd = Connection.prototype.end;
PoolConnection.prototype.end = function () {
console.warn(
'Calling conn.end() to release a pooled connection is ' +
'deprecated. In next version calling conn.end() will be ' +
'restored to default conn.end() behavior. Use ' +
'conn.release() instead.'
);
this.release();
};
PoolConnection.prototype.destroy = function () {
Connection.prototype.destroy.apply(this, arguments);
this._removeFromPool(this);
};
PoolConnection.prototype._removeFromPool = function _removeFromPool() {
if (!this._pool || this._pool._closed) {
return;
}
var pool = this._pool;
this._pool = null;
pool._purgeConnection(this);
};
var Connection = require('./Connection');
var PoolSelector = require('./PoolSelector');
module.exports = PoolNamespace;
/**
* PoolNamespace
* @constructor
* @param {PoolCluster} cluster The parent cluster for the namespace
* @param {string} pattern The selection pattern to use
* @param {string} selector The selector name to use
* @public
*/
function PoolNamespace(cluster, pattern, selector) {
this._cluster = cluster;
this._pattern = pattern;
this._selector = new PoolSelector[selector]();
}
PoolNamespace.prototype.getConnection = function(cb) {
var clusterNode = this._getClusterNode();
var cluster = this._cluster;
var namespace = this;
if (clusterNode === null) {
var err = null;
if (this._cluster._findNodeIds(this._pattern, true).length !== 0) {
err = new Error('Pool does not have online node.');
err.code = 'POOL_NONEONLINE';
} else {
err = new Error('Pool does not exist.');
err.code = 'POOL_NOEXIST';
}
cb(err);
return;
}
cluster._getConnection(clusterNode, function(err, connection) {
var retry = err && cluster._canRetry
&& cluster._findNodeIds(namespace._pattern).length !== 0;
if (retry) {
namespace.getConnection(cb);
return;
}
if (err) {
cb(err);
return;
}
cb(null, connection);
});
};
PoolNamespace.prototype.query = function (sql, values, cb) {
var cluster = this._cluster;
var clusterNode = this._getClusterNode();
var query = Connection.createQuery(sql, values, cb);
var namespace = this;
if (clusterNode === null) {
var err = null;
if (this._cluster._findNodeIds(this._pattern, true).length !== 0) {
err = new Error('Pool does not have online node.');
err.code = 'POOL_NONEONLINE';
} else {
err = new Error('Pool does not exist.');
err.code = 'POOL_NOEXIST';
}
process.nextTick(function () {
query.on('error', function () {});
query.end(err);
});
return query;
}
if (!(typeof sql === 'object' && 'typeCast' in sql)) {
query.typeCast = clusterNode.pool.config.connectionConfig.typeCast;
}
if (clusterNode.pool.config.connectionConfig.trace) {
// Long stack trace support
query._callSite = new Error();
}
cluster._getConnection(clusterNode, function (err, conn) {
var retry = err && cluster._canRetry
&& cluster._findNodeIds(namespace._pattern).length !== 0;
if (retry) {
namespace.query(query);
return;
}
if (err) {
query.on('error', function () {});
query.end(err);
return;
}
// Release connection based off event
query.once('end', function() {
conn.release();
});
conn.query(query);
});
return query;
};
PoolNamespace.prototype._getClusterNode = function _getClusterNode() {
var foundNodeIds = this._cluster._findNodeIds(this._pattern);
var nodeId;
switch (foundNodeIds.length) {
case 0:
nodeId = null;
break;
case 1:
nodeId = foundNodeIds[0];
break;
default:
nodeId = this._selector(foundNodeIds);
break;
}
return nodeId !== null
? this._cluster._getNode(nodeId)
: null;
};
/**
* PoolSelector
*/
var PoolSelector = module.exports = {};
PoolSelector.RR = function PoolSelectorRoundRobin() {
var index = 0;
return function(clusterIds) {
if (index >= clusterIds.length) {
index = 0;
}
var clusterId = clusterIds[index++];
return clusterId;
};
};
PoolSelector.RANDOM = function PoolSelectorRandom() {
return function(clusterIds) {
return clusterIds[Math.floor(Math.random() * clusterIds.length)];
};
};
PoolSelector.ORDER = function PoolSelectorOrder() {
return function(clusterIds) {
return clusterIds[0];
};
};
var Buffer = require('safe-buffer').Buffer;
var Crypto = require('crypto');
var Auth = exports;
function auth(name, data, options) {
options = options || {};
switch (name) {
case 'mysql_native_password':
return Auth.token(options.password, data.slice(0, 20));
default:
return undefined;
}
}
Auth.auth = auth;
function sha1(msg) {
var hash = Crypto.createHash('sha1');
hash.update(msg, 'binary');
return hash.digest('binary');
}
Auth.sha1 = sha1;
function xor(a, b) {
a = Buffer.from(a, 'binary');
b = Buffer.from(b, 'binary');
var result = Buffer.allocUnsafe(a.length);
for (var i = 0; i < a.length; i++) {
result[i] = (a[i] ^ b[i]);
}
return result;
}
Auth.xor = xor;
Auth.token = function(password, scramble) {
if (!password) {
return Buffer.alloc(0);
}
// password must be in binary format, not utf8
var stage1 = sha1((Buffer.from(password, 'utf8')).toString('binary'));
var stage2 = sha1(stage1);
var stage3 = sha1(scramble.toString('binary') + stage2);
return xor(stage3, stage1);
};
// This is a port of sql/password.c:hash_password which needs to be used for
// pre-4.1 passwords.
Auth.hashPassword = function(password) {
var nr = [0x5030, 0x5735];
var add = 7;
var nr2 = [0x1234, 0x5671];
var result = Buffer.alloc(8);
if (typeof password === 'string'){
password = Buffer.from(password);
}
for (var i = 0; i < password.length; i++) {
var c = password[i];
if (c === 32 || c === 9) {
// skip space in password
continue;
}
// nr^= (((nr & 63)+add)*c)+ (nr << 8);
// nr = xor(nr, add(mul(add(and(nr, 63), add), c), shl(nr, 8)))
nr = this.xor32(nr, this.add32(this.mul32(this.add32(this.and32(nr, [0, 63]), [0, add]), [0, c]), this.shl32(nr, 8)));
// nr2+=(nr2 << 8) ^ nr;
// nr2 = add(nr2, xor(shl(nr2, 8), nr))
nr2 = this.add32(nr2, this.xor32(this.shl32(nr2, 8), nr));
// add+=tmp;
add += c;
}
this.int31Write(result, nr, 0);
this.int31Write(result, nr2, 4);
return result;
};
Auth.randomInit = function(seed1, seed2) {
return {
max_value : 0x3FFFFFFF,
max_value_dbl : 0x3FFFFFFF,
seed1 : seed1 % 0x3FFFFFFF,
seed2 : seed2 % 0x3FFFFFFF
};
};
Auth.myRnd = function(r){
r.seed1 = (r.seed1 * 3 + r.seed2) % r.max_value;
r.seed2 = (r.seed1 + r.seed2 + 33) % r.max_value;
return r.seed1 / r.max_value_dbl;
};
Auth.scramble323 = function(message, password) {
if (!password) {
return Buffer.alloc(0);
}
var to = Buffer.allocUnsafe(8);
var hashPass = this.hashPassword(password);
var hashMessage = this.hashPassword(message.slice(0, 8));
var seed1 = this.int32Read(hashPass, 0) ^ this.int32Read(hashMessage, 0);
var seed2 = this.int32Read(hashPass, 4) ^ this.int32Read(hashMessage, 4);
var r = this.randomInit(seed1, seed2);
for (var i = 0; i < 8; i++){
to[i] = Math.floor(this.myRnd(r) * 31) + 64;
}
var extra = (Math.floor(this.myRnd(r) * 31));
for (var i = 0; i < 8; i++){
to[i] ^= extra;
}
return to;
};
Auth.xor32 = function(a, b){
return [a[0] ^ b[0], a[1] ^ b[1]];
};
Auth.add32 = function(a, b){
var w1 = a[1] + b[1];
var w2 = a[0] + b[0] + ((w1 & 0xFFFF0000) >> 16);
return [w2 & 0xFFFF, w1 & 0xFFFF];
};
Auth.mul32 = function(a, b){
// based on this example of multiplying 32b ints using 16b
// http://www.dsprelated.com/showmessage/89790/1.php
var w1 = a[1] * b[1];
var w2 = (((a[1] * b[1]) >> 16) & 0xFFFF) + ((a[0] * b[1]) & 0xFFFF) + (a[1] * b[0] & 0xFFFF);
return [w2 & 0xFFFF, w1 & 0xFFFF];
};
Auth.and32 = function(a, b){
return [a[0] & b[0], a[1] & b[1]];
};
Auth.shl32 = function(a, b){
// assume b is 16 or less
var w1 = a[1] << b;
var w2 = (a[0] << b) | ((w1 & 0xFFFF0000) >> 16);
return [w2 & 0xFFFF, w1 & 0xFFFF];
};
Auth.int31Write = function(buffer, number, offset) {
buffer[offset] = (number[0] >> 8) & 0x7F;
buffer[offset + 1] = (number[0]) & 0xFF;
buffer[offset + 2] = (number[1] >> 8) & 0xFF;
buffer[offset + 3] = (number[1]) & 0xFF;
};
Auth.int32Read = function(buffer, offset){
return (buffer[offset] << 24)
+ (buffer[offset + 1] << 16)
+ (buffer[offset + 2] << 8)
+ (buffer[offset + 3]);
};
module.exports = BufferList;
function BufferList() {
this.bufs = [];
this.size = 0;
}
BufferList.prototype.shift = function shift() {
var buf = this.bufs.shift();
if (buf) {
this.size -= buf.length;
}
return buf;
};
BufferList.prototype.push = function push(buf) {
if (!buf || !buf.length) {
return;
}
this.bufs.push(buf);
this.size += buf.length;
};
module.exports = PacketHeader;
function PacketHeader(length, number) {
this.length = length;
this.number = number;
}
var BIT_16 = Math.pow(2, 16);
var BIT_24 = Math.pow(2, 24);
var BUFFER_ALLOC_SIZE = Math.pow(2, 8);
// The maximum precision JS Numbers can hold precisely
// Don't panic: Good enough to represent byte values up to 8192 TB
var IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53);
var MAX_PACKET_LENGTH = Math.pow(2, 24) - 1;
var Buffer = require('safe-buffer').Buffer;
module.exports = PacketWriter;
function PacketWriter() {
this._buffer = null;
this._offset = 0;
}
PacketWriter.prototype.toBuffer = function toBuffer(parser) {
if (!this._buffer) {
this._buffer = Buffer.alloc(0);
this._offset = 0;
}
var buffer = this._buffer;
var length = this._offset;
var packets = Math.floor(length / MAX_PACKET_LENGTH) + 1;
this._buffer = Buffer.allocUnsafe(length + packets * 4);
this._offset = 0;
for (var packet = 0; packet < packets; packet++) {
var isLast = (packet + 1 === packets);
var packetLength = (isLast)
? length % MAX_PACKET_LENGTH
: MAX_PACKET_LENGTH;
var packetNumber = parser.incrementPacketNumber();
this.writeUnsignedNumber(3, packetLength);
this.writeUnsignedNumber(1, packetNumber);
var start = packet * MAX_PACKET_LENGTH;
var end = start + packetLength;
this.writeBuffer(buffer.slice(start, end));
}
return this._buffer;
};
PacketWriter.prototype.writeUnsignedNumber = function(bytes, value) {
this._allocate(bytes);
for (var i = 0; i < bytes; i++) {
this._buffer[this._offset++] = (value >> (i * 8)) & 0xff;
}
};
PacketWriter.prototype.writeFiller = function(bytes) {
this._allocate(bytes);
for (var i = 0; i < bytes; i++) {
this._buffer[this._offset++] = 0x00;
}
};
PacketWriter.prototype.writeNullTerminatedString = function(value, encoding) {
// Typecast undefined into '' and numbers into strings
value = value || '';
value = value + '';
var bytes = Buffer.byteLength(value, encoding || 'utf-8') + 1;
this._allocate(bytes);
this._buffer.write(value, this._offset, encoding);
this._buffer[this._offset + bytes - 1] = 0x00;
this._offset += bytes;
};
PacketWriter.prototype.writeString = function(value) {
// Typecast undefined into '' and numbers into strings
value = value || '';
value = value + '';
var bytes = Buffer.byteLength(value, 'utf-8');
this._allocate(bytes);
this._buffer.write(value, this._offset, 'utf-8');
this._offset += bytes;
};
PacketWriter.prototype.writeBuffer = function(value) {
var bytes = value.length;
this._allocate(bytes);
value.copy(this._buffer, this._offset);
this._offset += bytes;
};
PacketWriter.prototype.writeLengthCodedNumber = function(value) {
if (value === null) {
this._allocate(1);
this._buffer[this._offset++] = 251;
return;
}
if (value <= 250) {
this._allocate(1);
this._buffer[this._offset++] = value;
return;
}
if (value > IEEE_754_BINARY_64_PRECISION) {
throw new Error(
'writeLengthCodedNumber: JS precision range exceeded, your ' +
'number is > 53 bit: "' + value + '"'
);
}
if (value < BIT_16) {
this._allocate(3);
this._buffer[this._offset++] = 252;
} else if (value < BIT_24) {
this._allocate(4);
this._buffer[this._offset++] = 253;
} else {
this._allocate(9);
this._buffer[this._offset++] = 254;
}
// 16 Bit
this._buffer[this._offset++] = value & 0xff;
this._buffer[this._offset++] = (value >> 8) & 0xff;
if (value < BIT_16) {
return;
}
// 24 Bit
this._buffer[this._offset++] = (value >> 16) & 0xff;
if (value < BIT_24) {
return;
}
this._buffer[this._offset++] = (value >> 24) & 0xff;
// Hack: Get the most significant 32 bit (JS bitwise operators are 32 bit)
value = value.toString(2);
value = value.substr(0, value.length - 32);
value = parseInt(value, 2);
this._buffer[this._offset++] = value & 0xff;
this._buffer[this._offset++] = (value >> 8) & 0xff;
this._buffer[this._offset++] = (value >> 16) & 0xff;
// Set last byte to 0, as we can only support 53 bits in JS (see above)
this._buffer[this._offset++] = 0;
};
PacketWriter.prototype.writeLengthCodedBuffer = function(value) {
var bytes = value.length;
this.writeLengthCodedNumber(bytes);
this.writeBuffer(value);
};
PacketWriter.prototype.writeNullTerminatedBuffer = function(value) {
this.writeBuffer(value);
this.writeFiller(1); // 0x00 terminator
};
PacketWriter.prototype.writeLengthCodedString = function(value) {
if (value === null) {
this.writeLengthCodedNumber(null);
return;
}
value = (value === undefined)
? ''
: String(value);
var bytes = Buffer.byteLength(value, 'utf-8');
this.writeLengthCodedNumber(bytes);
if (!bytes) {
return;
}
this._allocate(bytes);
this._buffer.write(value, this._offset, 'utf-8');
this._offset += bytes;
};
PacketWriter.prototype._allocate = function _allocate(bytes) {
if (!this._buffer) {
this._buffer = Buffer.alloc(Math.max(BUFFER_ALLOC_SIZE, bytes));
this._offset = 0;
return;
}
var bytesRemaining = this._buffer.length - this._offset;
if (bytesRemaining >= bytes) {
return;
}
var newSize = this._buffer.length + Math.max(BUFFER_ALLOC_SIZE, bytes);
var oldBuffer = this._buffer;
this._buffer = Buffer.alloc(newSize);
oldBuffer.copy(this._buffer);
};
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
module.exports = ResultSet;
function ResultSet(resultSetHeaderPacket) {
this.resultSetHeaderPacket = resultSetHeaderPacket;
this.fieldPackets = [];
this.eofPackets = [];
this.rows = [];
}
module.exports = require('sqlstring');
var Timers = require('timers');
module.exports = Timer;
function Timer(object) {
this._object = object;
this._timeout = null;
}
Timer.prototype.active = function active() {
if (this._timeout) {
if (this._timeout.refresh) {
this._timeout.refresh();
} else {
Timers.active(this._timeout);
}
}
};
Timer.prototype.start = function start(msecs) {
this.stop();
this._timeout = Timers.setTimeout(this._onTimeout.bind(this), msecs);
};
Timer.prototype.stop = function stop() {
if (this._timeout) {
Timers.clearTimeout(this._timeout);
this._timeout = null;
}
};
Timer.prototype._onTimeout = function _onTimeout() {
return this._object._onTimeout();
};
This diff is collapsed. Click to expand it.
// Manually extracted from mysql-5.5.23/include/mysql_com.h
exports.CLIENT_LONG_PASSWORD = 1; /* new more secure passwords */
exports.CLIENT_FOUND_ROWS = 2; /* Found instead of affected rows */
exports.CLIENT_LONG_FLAG = 4; /* Get all column flags */
exports.CLIENT_CONNECT_WITH_DB = 8; /* One can specify db on connect */
exports.CLIENT_NO_SCHEMA = 16; /* Don't allow database.table.column */
exports.CLIENT_COMPRESS = 32; /* Can use compression protocol */
exports.CLIENT_ODBC = 64; /* Odbc client */
exports.CLIENT_LOCAL_FILES = 128; /* Can use LOAD DATA LOCAL */
exports.CLIENT_IGNORE_SPACE = 256; /* Ignore spaces before '(' */
exports.CLIENT_PROTOCOL_41 = 512; /* New 4.1 protocol */
exports.CLIENT_INTERACTIVE = 1024; /* This is an interactive client */
exports.CLIENT_SSL = 2048; /* Switch to SSL after handshake */
exports.CLIENT_IGNORE_SIGPIPE = 4096; /* IGNORE sigpipes */
exports.CLIENT_TRANSACTIONS = 8192; /* Client knows about transactions */
exports.CLIENT_RESERVED = 16384; /* Old flag for 4.1 protocol */
exports.CLIENT_SECURE_CONNECTION = 32768; /* New 4.1 authentication */
exports.CLIENT_MULTI_STATEMENTS = 65536; /* Enable/disable multi-stmt support */
exports.CLIENT_MULTI_RESULTS = 131072; /* Enable/disable multi-results */
exports.CLIENT_PS_MULTI_RESULTS = 262144; /* Multi-results in PS-protocol */
exports.CLIENT_PLUGIN_AUTH = 524288; /* Client supports plugin authentication */
exports.CLIENT_SSL_VERIFY_SERVER_CERT = 1073741824;
exports.CLIENT_REMEMBER_OPTIONS = 2147483648;
This diff could not be displayed because it is too large.
// Manually extracted from mysql-5.5.23/include/mysql_com.h
exports.NOT_NULL_FLAG = 1; /* Field can't be NULL */
exports.PRI_KEY_FLAG = 2; /* Field is part of a primary key */
exports.UNIQUE_KEY_FLAG = 4; /* Field is part of a unique key */
exports.MULTIPLE_KEY_FLAG = 8; /* Field is part of a key */
exports.BLOB_FLAG = 16; /* Field is a blob */
exports.UNSIGNED_FLAG = 32; /* Field is unsigned */
exports.ZEROFILL_FLAG = 64; /* Field is zerofill */
exports.BINARY_FLAG = 128; /* Field is binary */
/* The following are only sent to new clients */
exports.ENUM_FLAG = 256; /* field is an enum */
exports.AUTO_INCREMENT_FLAG = 512; /* field is a autoincrement field */
exports.TIMESTAMP_FLAG = 1024; /* Field is a timestamp */
exports.SET_FLAG = 2048; /* field is a set */
exports.NO_DEFAULT_VALUE_FLAG = 4096; /* Field doesn't have default value */
exports.ON_UPDATE_NOW_FLAG = 8192; /* Field is set to NOW on UPDATE */
exports.NUM_FLAG = 32768; /* Field is num (for clients) */
// Manually extracted from mysql-5.5.23/include/mysql_com.h
/**
Is raised when a multi-statement transaction
has been started, either explicitly, by means
of BEGIN or COMMIT AND CHAIN, or
implicitly, by the first transactional
statement, when autocommit=off.
*/
exports.SERVER_STATUS_IN_TRANS = 1;
exports.SERVER_STATUS_AUTOCOMMIT = 2; /* Server in auto_commit mode */
exports.SERVER_MORE_RESULTS_EXISTS = 8; /* Multi query - next query exists */
exports.SERVER_QUERY_NO_GOOD_INDEX_USED = 16;
exports.SERVER_QUERY_NO_INDEX_USED = 32;
/**
The server was able to fulfill the clients request and opened a
read-only non-scrollable cursor for a query. This flag comes
in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands.
*/
exports.SERVER_STATUS_CURSOR_EXISTS = 64;
/**
This flag is sent when a read-only cursor is exhausted, in reply to
COM_STMT_FETCH command.
*/
exports.SERVER_STATUS_LAST_ROW_SENT = 128;
exports.SERVER_STATUS_DB_DROPPED = 256; /* A database was dropped */
exports.SERVER_STATUS_NO_BACKSLASH_ESCAPES = 512;
/**
Sent to the client if after a prepared statement reprepare
we discovered that the new statement returns a different
number of result set columns.
*/
exports.SERVER_STATUS_METADATA_CHANGED = 1024;
exports.SERVER_QUERY_WAS_SLOW = 2048;
/**
To mark ResultSet containing output parameter values.
*/
exports.SERVER_PS_OUT_PARAMS = 4096;
This diff is collapsed. Click to expand it.
/**
* MySQL type constants
*
* Extracted from version 5.7.29
*
* !! Generated by generate-type-constants.js, do not modify by hand !!
*/
exports.DECIMAL = 0;
exports.TINY = 1;
exports.SHORT = 2;
exports.LONG = 3;
exports.FLOAT = 4;
exports.DOUBLE = 5;
exports.NULL = 6;
exports.TIMESTAMP = 7;
exports.LONGLONG = 8;
exports.INT24 = 9;
exports.DATE = 10;
exports.TIME = 11;
exports.DATETIME = 12;
exports.YEAR = 13;
exports.NEWDATE = 14;
exports.VARCHAR = 15;
exports.BIT = 16;
exports.TIMESTAMP2 = 17;
exports.DATETIME2 = 18;
exports.TIME2 = 19;
exports.JSON = 245;
exports.NEWDECIMAL = 246;
exports.ENUM = 247;
exports.SET = 248;
exports.TINY_BLOB = 249;
exports.MEDIUM_BLOB = 250;
exports.LONG_BLOB = 251;
exports.BLOB = 252;
exports.VAR_STRING = 253;
exports.STRING = 254;
exports.GEOMETRY = 255;
// Lookup-by-number table
exports[0] = 'DECIMAL';
exports[1] = 'TINY';
exports[2] = 'SHORT';
exports[3] = 'LONG';
exports[4] = 'FLOAT';
exports[5] = 'DOUBLE';
exports[6] = 'NULL';
exports[7] = 'TIMESTAMP';
exports[8] = 'LONGLONG';
exports[9] = 'INT24';
exports[10] = 'DATE';
exports[11] = 'TIME';
exports[12] = 'DATETIME';
exports[13] = 'YEAR';
exports[14] = 'NEWDATE';
exports[15] = 'VARCHAR';
exports[16] = 'BIT';
exports[17] = 'TIMESTAMP2';
exports[18] = 'DATETIME2';
exports[19] = 'TIME2';
exports[245] = 'JSON';
exports[246] = 'NEWDECIMAL';
exports[247] = 'ENUM';
exports[248] = 'SET';
exports[249] = 'TINY_BLOB';
exports[250] = 'MEDIUM_BLOB';
exports[251] = 'LONG_BLOB';
exports[252] = 'BLOB';
exports[253] = 'VAR_STRING';
exports[254] = 'STRING';
exports[255] = 'GEOMETRY';
module.exports = AuthSwitchRequestPacket;
function AuthSwitchRequestPacket(options) {
options = options || {};
this.status = 0xfe;
this.authMethodName = options.authMethodName;
this.authMethodData = options.authMethodData;
}
AuthSwitchRequestPacket.prototype.parse = function parse(parser) {
this.status = parser.parseUnsignedNumber(1);
this.authMethodName = parser.parseNullTerminatedString();
this.authMethodData = parser.parsePacketTerminatedBuffer();
};
AuthSwitchRequestPacket.prototype.write = function write(writer) {
writer.writeUnsignedNumber(1, this.status);
writer.writeNullTerminatedString(this.authMethodName);
writer.writeBuffer(this.authMethodData);
};
module.exports = AuthSwitchResponsePacket;
function AuthSwitchResponsePacket(options) {
options = options || {};
this.data = options.data;
}
AuthSwitchResponsePacket.prototype.parse = function parse(parser) {
this.data = parser.parsePacketTerminatedBuffer();
};
AuthSwitchResponsePacket.prototype.write = function write(writer) {
writer.writeBuffer(this.data);
};
var Buffer = require('safe-buffer').Buffer;
module.exports = ClientAuthenticationPacket;
function ClientAuthenticationPacket(options) {
options = options || {};
this.clientFlags = options.clientFlags;
this.maxPacketSize = options.maxPacketSize;
this.charsetNumber = options.charsetNumber;
this.filler = undefined;
this.user = options.user;
this.scrambleBuff = options.scrambleBuff;
this.database = options.database;
this.protocol41 = options.protocol41;
}
ClientAuthenticationPacket.prototype.parse = function(parser) {
if (this.protocol41) {
this.clientFlags = parser.parseUnsignedNumber(4);
this.maxPacketSize = parser.parseUnsignedNumber(4);
this.charsetNumber = parser.parseUnsignedNumber(1);
this.filler = parser.parseFiller(23);
this.user = parser.parseNullTerminatedString();
this.scrambleBuff = parser.parseLengthCodedBuffer();
this.database = parser.parseNullTerminatedString();
} else {
this.clientFlags = parser.parseUnsignedNumber(2);
this.maxPacketSize = parser.parseUnsignedNumber(3);
this.user = parser.parseNullTerminatedString();
this.scrambleBuff = parser.parseBuffer(8);
this.database = parser.parseLengthCodedBuffer();
}
};
ClientAuthenticationPacket.prototype.write = function(writer) {
if (this.protocol41) {
writer.writeUnsignedNumber(4, this.clientFlags);
writer.writeUnsignedNumber(4, this.maxPacketSize);
writer.writeUnsignedNumber(1, this.charsetNumber);
writer.writeFiller(23);
writer.writeNullTerminatedString(this.user);
writer.writeLengthCodedBuffer(this.scrambleBuff);
writer.writeNullTerminatedString(this.database);
} else {
writer.writeUnsignedNumber(2, this.clientFlags);
writer.writeUnsignedNumber(3, this.maxPacketSize);
writer.writeNullTerminatedString(this.user);
writer.writeBuffer(this.scrambleBuff);
if (this.database && this.database.length) {
writer.writeFiller(1);
writer.writeBuffer(Buffer.from(this.database));
}
}
};
module.exports = ComChangeUserPacket;
function ComChangeUserPacket(options) {
options = options || {};
this.command = 0x11;
this.user = options.user;
this.scrambleBuff = options.scrambleBuff;
this.database = options.database;
this.charsetNumber = options.charsetNumber;
}
ComChangeUserPacket.prototype.parse = function(parser) {
this.command = parser.parseUnsignedNumber(1);
this.user = parser.parseNullTerminatedString();
this.scrambleBuff = parser.parseLengthCodedBuffer();
this.database = parser.parseNullTerminatedString();
this.charsetNumber = parser.parseUnsignedNumber(1);
};
ComChangeUserPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, this.command);
writer.writeNullTerminatedString(this.user);
writer.writeLengthCodedBuffer(this.scrambleBuff);
writer.writeNullTerminatedString(this.database);
writer.writeUnsignedNumber(2, this.charsetNumber);
};
module.exports = ComPingPacket;
function ComPingPacket() {
this.command = 0x0e;
}
ComPingPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, this.command);
};
ComPingPacket.prototype.parse = function(parser) {
this.command = parser.parseUnsignedNumber(1);
};
module.exports = ComQueryPacket;
function ComQueryPacket(sql) {
this.command = 0x03;
this.sql = sql;
}
ComQueryPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, this.command);
writer.writeString(this.sql);
};
ComQueryPacket.prototype.parse = function(parser) {
this.command = parser.parseUnsignedNumber(1);
this.sql = parser.parsePacketTerminatedString();
};
module.exports = ComQuitPacket;
function ComQuitPacket() {
this.command = 0x01;
}
ComQuitPacket.prototype.parse = function parse(parser) {
this.command = parser.parseUnsignedNumber(1);
};
ComQuitPacket.prototype.write = function write(writer) {
writer.writeUnsignedNumber(1, this.command);
};
module.exports = ComStatisticsPacket;
function ComStatisticsPacket() {
this.command = 0x09;
}
ComStatisticsPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, this.command);
};
ComStatisticsPacket.prototype.parse = function(parser) {
this.command = parser.parseUnsignedNumber(1);
};
module.exports = EmptyPacket;
function EmptyPacket() {
}
EmptyPacket.prototype.parse = function parse() {
};
EmptyPacket.prototype.write = function write() {
};
module.exports = EofPacket;
function EofPacket(options) {
options = options || {};
this.fieldCount = undefined;
this.warningCount = options.warningCount;
this.serverStatus = options.serverStatus;
this.protocol41 = options.protocol41;
}
EofPacket.prototype.parse = function(parser) {
this.fieldCount = parser.parseUnsignedNumber(1);
if (this.protocol41) {
this.warningCount = parser.parseUnsignedNumber(2);
this.serverStatus = parser.parseUnsignedNumber(2);
}
};
EofPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, 0xfe);
if (this.protocol41) {
writer.writeUnsignedNumber(2, this.warningCount);
writer.writeUnsignedNumber(2, this.serverStatus);
}
};
module.exports = ErrorPacket;
function ErrorPacket(options) {
options = options || {};
this.fieldCount = options.fieldCount;
this.errno = options.errno;
this.sqlStateMarker = options.sqlStateMarker;
this.sqlState = options.sqlState;
this.message = options.message;
}
ErrorPacket.prototype.parse = function(parser) {
this.fieldCount = parser.parseUnsignedNumber(1);
this.errno = parser.parseUnsignedNumber(2);
// sqlStateMarker ('#' = 0x23) indicates error packet format
if (parser.peak() === 0x23) {
this.sqlStateMarker = parser.parseString(1);
this.sqlState = parser.parseString(5);
}
this.message = parser.parsePacketTerminatedString();
};
ErrorPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, 0xff);
writer.writeUnsignedNumber(2, this.errno);
if (this.sqlStateMarker) {
writer.writeString(this.sqlStateMarker);
writer.writeString(this.sqlState);
}
writer.writeString(this.message);
};
var Types = require('../constants/types');
module.exports = Field;
function Field(options) {
options = options || {};
this.parser = options.parser;
this.packet = options.packet;
this.db = options.packet.db;
this.table = options.packet.table;
this.name = options.packet.name;
this.type = Types[options.packet.type];
this.length = options.packet.length;
}
Field.prototype.string = function () {
return this.parser.parseLengthCodedString();
};
Field.prototype.buffer = function () {
return this.parser.parseLengthCodedBuffer();
};
Field.prototype.geometry = function () {
return this.parser.parseGeometryValue();
};
module.exports = FieldPacket;
function FieldPacket(options) {
options = options || {};
this.catalog = options.catalog;
this.db = options.db;
this.table = options.table;
this.orgTable = options.orgTable;
this.name = options.name;
this.orgName = options.orgName;
this.charsetNr = options.charsetNr;
this.length = options.length;
this.type = options.type;
this.flags = options.flags;
this.decimals = options.decimals;
this.default = options.default;
this.zeroFill = options.zeroFill;
this.protocol41 = options.protocol41;
}
FieldPacket.prototype.parse = function(parser) {
if (this.protocol41) {
this.catalog = parser.parseLengthCodedString();
this.db = parser.parseLengthCodedString();
this.table = parser.parseLengthCodedString();
this.orgTable = parser.parseLengthCodedString();
this.name = parser.parseLengthCodedString();
this.orgName = parser.parseLengthCodedString();
if (parser.parseLengthCodedNumber() !== 0x0c) {
var err = new TypeError('Received invalid field length');
err.code = 'PARSER_INVALID_FIELD_LENGTH';
throw err;
}
this.charsetNr = parser.parseUnsignedNumber(2);
this.length = parser.parseUnsignedNumber(4);
this.type = parser.parseUnsignedNumber(1);
this.flags = parser.parseUnsignedNumber(2);
this.decimals = parser.parseUnsignedNumber(1);
var filler = parser.parseBuffer(2);
if (filler[0] !== 0x0 || filler[1] !== 0x0) {
var err = new TypeError('Received invalid filler');
err.code = 'PARSER_INVALID_FILLER';
throw err;
}
// parsed flags
this.zeroFill = (this.flags & 0x0040 ? true : false);
if (parser.reachedPacketEnd()) {
return;
}
this.default = parser.parseLengthCodedString();
} else {
this.table = parser.parseLengthCodedString();
this.name = parser.parseLengthCodedString();
this.length = parser.parseUnsignedNumber(parser.parseUnsignedNumber(1));
this.type = parser.parseUnsignedNumber(parser.parseUnsignedNumber(1));
}
};
FieldPacket.prototype.write = function(writer) {
if (this.protocol41) {
writer.writeLengthCodedString(this.catalog);
writer.writeLengthCodedString(this.db);
writer.writeLengthCodedString(this.table);
writer.writeLengthCodedString(this.orgTable);
writer.writeLengthCodedString(this.name);
writer.writeLengthCodedString(this.orgName);
writer.writeLengthCodedNumber(0x0c);
writer.writeUnsignedNumber(2, this.charsetNr || 0);
writer.writeUnsignedNumber(4, this.length || 0);
writer.writeUnsignedNumber(1, this.type || 0);
writer.writeUnsignedNumber(2, this.flags || 0);
writer.writeUnsignedNumber(1, this.decimals || 0);
writer.writeFiller(2);
if (this.default !== undefined) {
writer.writeLengthCodedString(this.default);
}
} else {
writer.writeLengthCodedString(this.table);
writer.writeLengthCodedString(this.name);
writer.writeUnsignedNumber(1, 0x01);
writer.writeUnsignedNumber(1, this.length);
writer.writeUnsignedNumber(1, 0x01);
writer.writeUnsignedNumber(1, this.type);
}
};
var Buffer = require('safe-buffer').Buffer;
var Client = require('../constants/client');
module.exports = HandshakeInitializationPacket;
function HandshakeInitializationPacket(options) {
options = options || {};
this.protocolVersion = options.protocolVersion;
this.serverVersion = options.serverVersion;
this.threadId = options.threadId;
this.scrambleBuff1 = options.scrambleBuff1;
this.filler1 = options.filler1;
this.serverCapabilities1 = options.serverCapabilities1;
this.serverLanguage = options.serverLanguage;
this.serverStatus = options.serverStatus;
this.serverCapabilities2 = options.serverCapabilities2;
this.scrambleLength = options.scrambleLength;
this.filler2 = options.filler2;
this.scrambleBuff2 = options.scrambleBuff2;
this.filler3 = options.filler3;
this.pluginData = options.pluginData;
this.protocol41 = options.protocol41;
if (this.protocol41) {
// force set the bit in serverCapabilities1
this.serverCapabilities1 |= Client.CLIENT_PROTOCOL_41;
}
}
HandshakeInitializationPacket.prototype.parse = function(parser) {
this.protocolVersion = parser.parseUnsignedNumber(1);
this.serverVersion = parser.parseNullTerminatedString();
this.threadId = parser.parseUnsignedNumber(4);
this.scrambleBuff1 = parser.parseBuffer(8);
this.filler1 = parser.parseFiller(1);
this.serverCapabilities1 = parser.parseUnsignedNumber(2);
this.serverLanguage = parser.parseUnsignedNumber(1);
this.serverStatus = parser.parseUnsignedNumber(2);
this.protocol41 = (this.serverCapabilities1 & (1 << 9)) > 0;
if (this.protocol41) {
this.serverCapabilities2 = parser.parseUnsignedNumber(2);
this.scrambleLength = parser.parseUnsignedNumber(1);
this.filler2 = parser.parseFiller(10);
// scrambleBuff2 should be 0x00 terminated, but sphinx does not do this
// so we assume scrambleBuff2 to be 12 byte and treat the next byte as a
// filler byte.
this.scrambleBuff2 = parser.parseBuffer(12);
this.filler3 = parser.parseFiller(1);
} else {
this.filler2 = parser.parseFiller(13);
}
if (parser.reachedPacketEnd()) {
return;
}
// According to the docs this should be 0x00 terminated, but MariaDB does
// not do this, so we assume this string to be packet terminated.
this.pluginData = parser.parsePacketTerminatedString();
// However, if there is a trailing '\0', strip it
var lastChar = this.pluginData.length - 1;
if (this.pluginData[lastChar] === '\0') {
this.pluginData = this.pluginData.substr(0, lastChar);
}
};
HandshakeInitializationPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, this.protocolVersion);
writer.writeNullTerminatedString(this.serverVersion);
writer.writeUnsignedNumber(4, this.threadId);
writer.writeBuffer(this.scrambleBuff1);
writer.writeFiller(1);
writer.writeUnsignedNumber(2, this.serverCapabilities1);
writer.writeUnsignedNumber(1, this.serverLanguage);
writer.writeUnsignedNumber(2, this.serverStatus);
if (this.protocol41) {
writer.writeUnsignedNumber(2, this.serverCapabilities2);
writer.writeUnsignedNumber(1, this.scrambleLength);
writer.writeFiller(10);
}
writer.writeNullTerminatedBuffer(this.scrambleBuff2);
if (this.pluginData !== undefined) {
writer.writeNullTerminatedString(this.pluginData);
}
};
HandshakeInitializationPacket.prototype.scrambleBuff = function() {
var buffer = null;
if (typeof this.scrambleBuff2 === 'undefined') {
buffer = Buffer.from(this.scrambleBuff1);
} else {
buffer = Buffer.allocUnsafe(this.scrambleBuff1.length + this.scrambleBuff2.length);
this.scrambleBuff1.copy(buffer, 0);
this.scrambleBuff2.copy(buffer, this.scrambleBuff1.length);
}
return buffer;
};
module.exports = LocalDataFilePacket;
/**
* Create a new LocalDataFilePacket
* @constructor
* @param {Buffer} data The data contents of the packet
* @public
*/
function LocalDataFilePacket(data) {
this.data = data;
}
LocalDataFilePacket.prototype.write = function(writer) {
writer.writeBuffer(this.data);
};
module.exports = LocalInfileRequestPacket;
function LocalInfileRequestPacket(options) {
options = options || {};
this.filename = options.filename;
}
LocalInfileRequestPacket.prototype.parse = function parse(parser) {
if (parser.parseLengthCodedNumber() !== null) {
var err = new TypeError('Received invalid field length');
err.code = 'PARSER_INVALID_FIELD_LENGTH';
throw err;
}
this.filename = parser.parsePacketTerminatedString();
};
LocalInfileRequestPacket.prototype.write = function write(writer) {
writer.writeLengthCodedNumber(null);
writer.writeString(this.filename);
};
// Language-neutral expression to match ER_UPDATE_INFO
var ER_UPDATE_INFO_REGEXP = /^[^:0-9]+: [0-9]+[^:0-9]+: ([0-9]+)[^:0-9]+: [0-9]+[^:0-9]*$/;
module.exports = OkPacket;
function OkPacket(options) {
options = options || {};
this.fieldCount = undefined;
this.affectedRows = undefined;
this.insertId = undefined;
this.serverStatus = undefined;
this.warningCount = undefined;
this.message = undefined;
this.protocol41 = options.protocol41;
}
OkPacket.prototype.parse = function(parser) {
this.fieldCount = parser.parseUnsignedNumber(1);
this.affectedRows = parser.parseLengthCodedNumber();
this.insertId = parser.parseLengthCodedNumber();
if (this.protocol41) {
this.serverStatus = parser.parseUnsignedNumber(2);
this.warningCount = parser.parseUnsignedNumber(2);
}
this.message = parser.parsePacketTerminatedString();
this.changedRows = 0;
var m = ER_UPDATE_INFO_REGEXP.exec(this.message);
if (m !== null) {
this.changedRows = parseInt(m[1], 10);
}
};
OkPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, 0x00);
writer.writeLengthCodedNumber(this.affectedRows || 0);
writer.writeLengthCodedNumber(this.insertId || 0);
if (this.protocol41) {
writer.writeUnsignedNumber(2, this.serverStatus || 0);
writer.writeUnsignedNumber(2, this.warningCount || 0);
}
writer.writeString(this.message);
};
module.exports = OldPasswordPacket;
function OldPasswordPacket(options) {
options = options || {};
this.scrambleBuff = options.scrambleBuff;
}
OldPasswordPacket.prototype.parse = function(parser) {
this.scrambleBuff = parser.parsePacketTerminatedBuffer();
};
OldPasswordPacket.prototype.write = function(writer) {
writer.writeBuffer(this.scrambleBuff);
};
module.exports = ResultSetHeaderPacket;
function ResultSetHeaderPacket(options) {
options = options || {};
this.fieldCount = options.fieldCount;
}
ResultSetHeaderPacket.prototype.parse = function(parser) {
this.fieldCount = parser.parseLengthCodedNumber();
};
ResultSetHeaderPacket.prototype.write = function(writer) {
writer.writeLengthCodedNumber(this.fieldCount);
};
var Types = require('../constants/types');
var Charsets = require('../constants/charsets');
var Field = require('./Field');
var IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53);
module.exports = RowDataPacket;
function RowDataPacket() {
}
Object.defineProperty(RowDataPacket.prototype, 'parse', {
configurable : true,
enumerable : false,
value : parse
});
Object.defineProperty(RowDataPacket.prototype, '_typeCast', {
configurable : true,
enumerable : false,
value : typeCast
});
function parse(parser, fieldPackets, typeCast, nestTables, connection) {
var self = this;
var next = function () {
return self._typeCast(fieldPacket, parser, connection.config.timezone, connection.config.supportBigNumbers, connection.config.bigNumberStrings, connection.config.dateStrings);
};
for (var i = 0; i < fieldPackets.length; i++) {
var fieldPacket = fieldPackets[i];
var value;
if (typeof typeCast === 'function') {
value = typeCast.apply(connection, [ new Field({ packet: fieldPacket, parser: parser }), next ]);
} else {
value = (typeCast)
? this._typeCast(fieldPacket, parser, connection.config.timezone, connection.config.supportBigNumbers, connection.config.bigNumberStrings, connection.config.dateStrings)
: ( (fieldPacket.charsetNr === Charsets.BINARY)
? parser.parseLengthCodedBuffer()
: parser.parseLengthCodedString() );
}
if (typeof nestTables === 'string' && nestTables.length) {
this[fieldPacket.table + nestTables + fieldPacket.name] = value;
} else if (nestTables) {
this[fieldPacket.table] = this[fieldPacket.table] || {};
this[fieldPacket.table][fieldPacket.name] = value;
} else {
this[fieldPacket.name] = value;
}
}
}
function typeCast(field, parser, timeZone, supportBigNumbers, bigNumberStrings, dateStrings) {
var numberString;
switch (field.type) {
case Types.TIMESTAMP:
case Types.TIMESTAMP2:
case Types.DATE:
case Types.DATETIME:
case Types.DATETIME2:
case Types.NEWDATE:
var dateString = parser.parseLengthCodedString();
if (typeMatch(field.type, dateStrings)) {
return dateString;
}
if (dateString === null) {
return null;
}
var originalString = dateString;
if (field.type === Types.DATE) {
dateString += ' 00:00:00';
}
if (timeZone !== 'local') {
dateString += ' ' + timeZone;
}
var dt = new Date(dateString);
if (isNaN(dt.getTime())) {
return originalString;
}
return dt;
case Types.TINY:
case Types.SHORT:
case Types.LONG:
case Types.INT24:
case Types.YEAR:
case Types.FLOAT:
case Types.DOUBLE:
numberString = parser.parseLengthCodedString();
return (numberString === null || (field.zeroFill && numberString[0] === '0'))
? numberString : Number(numberString);
case Types.NEWDECIMAL:
case Types.LONGLONG:
numberString = parser.parseLengthCodedString();
return (numberString === null || (field.zeroFill && numberString[0] === '0'))
? numberString
: ((supportBigNumbers && (bigNumberStrings || (Number(numberString) >= IEEE_754_BINARY_64_PRECISION) || Number(numberString) <= -IEEE_754_BINARY_64_PRECISION))
? numberString
: Number(numberString));
case Types.BIT:
return parser.parseLengthCodedBuffer();
case Types.STRING:
case Types.VAR_STRING:
case Types.TINY_BLOB:
case Types.MEDIUM_BLOB:
case Types.LONG_BLOB:
case Types.BLOB:
return (field.charsetNr === Charsets.BINARY)
? parser.parseLengthCodedBuffer()
: parser.parseLengthCodedString();
case Types.GEOMETRY:
return parser.parseGeometryValue();
default:
return parser.parseLengthCodedString();
}
}
function typeMatch(type, list) {
if (Array.isArray(list)) {
return list.indexOf(Types[type]) !== -1;
} else {
return Boolean(list);
}
}
// http://dev.mysql.com/doc/internals/en/ssl.html
// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::SSLRequest
var ClientConstants = require('../constants/client');
module.exports = SSLRequestPacket;
function SSLRequestPacket(options) {
options = options || {};
this.clientFlags = options.clientFlags | ClientConstants.CLIENT_SSL;
this.maxPacketSize = options.maxPacketSize;
this.charsetNumber = options.charsetNumber;
}
SSLRequestPacket.prototype.parse = function(parser) {
// TODO: check SSLRequest packet v41 vs pre v41
this.clientFlags = parser.parseUnsignedNumber(4);
this.maxPacketSize = parser.parseUnsignedNumber(4);
this.charsetNumber = parser.parseUnsignedNumber(1);
};
SSLRequestPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(4, this.clientFlags);
writer.writeUnsignedNumber(4, this.maxPacketSize);
writer.writeUnsignedNumber(1, this.charsetNumber);
writer.writeFiller(23);
};
module.exports = StatisticsPacket;
function StatisticsPacket() {
this.message = undefined;
}
StatisticsPacket.prototype.parse = function(parser) {
this.message = parser.parsePacketTerminatedString();
var items = this.message.split(/\s\s/);
for (var i = 0; i < items.length; i++) {
var m = items[i].match(/^(.+)\:\s+(.+)$/);
if (m !== null) {
this[m[1].toLowerCase().replace(/\s/g, '_')] = Number(m[2]);
}
}
};
StatisticsPacket.prototype.write = function(writer) {
writer.writeString(this.message);
};
module.exports = UseOldPasswordPacket;
function UseOldPasswordPacket(options) {
options = options || {};
this.firstByte = options.firstByte || 0xfe;
}
UseOldPasswordPacket.prototype.parse = function(parser) {
this.firstByte = parser.parseUnsignedNumber(1);
};
UseOldPasswordPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, this.firstByte);
};
exports.AuthSwitchRequestPacket = require('./AuthSwitchRequestPacket');
exports.AuthSwitchResponsePacket = require('./AuthSwitchResponsePacket');
exports.ClientAuthenticationPacket = require('./ClientAuthenticationPacket');
exports.ComChangeUserPacket = require('./ComChangeUserPacket');
exports.ComPingPacket = require('./ComPingPacket');
exports.ComQueryPacket = require('./ComQueryPacket');
exports.ComQuitPacket = require('./ComQuitPacket');
exports.ComStatisticsPacket = require('./ComStatisticsPacket');
exports.EmptyPacket = require('./EmptyPacket');
exports.EofPacket = require('./EofPacket');
exports.ErrorPacket = require('./ErrorPacket');
exports.Field = require('./Field');
exports.FieldPacket = require('./FieldPacket');
exports.HandshakeInitializationPacket = require('./HandshakeInitializationPacket');
exports.LocalDataFilePacket = require('./LocalDataFilePacket');
exports.LocalInfileRequestPacket = require('./LocalInfileRequestPacket');
exports.OkPacket = require('./OkPacket');
exports.OldPasswordPacket = require('./OldPasswordPacket');
exports.ResultSetHeaderPacket = require('./ResultSetHeaderPacket');
exports.RowDataPacket = require('./RowDataPacket');
exports.SSLRequestPacket = require('./SSLRequestPacket');
exports.StatisticsPacket = require('./StatisticsPacket');
exports.UseOldPasswordPacket = require('./UseOldPasswordPacket');
var Sequence = require('./Sequence');
var Util = require('util');
var Packets = require('../packets');
var Auth = require('../Auth');
module.exports = ChangeUser;
Util.inherits(ChangeUser, Sequence);
function ChangeUser(options, callback) {
Sequence.call(this, options, callback);
this._user = options.user;
this._password = options.password;
this._database = options.database;
this._charsetNumber = options.charsetNumber;
this._currentConfig = options.currentConfig;
}
ChangeUser.prototype.determinePacket = function determinePacket(firstByte) {
switch (firstByte) {
case 0xfe: return Packets.AuthSwitchRequestPacket;
case 0xff: return Packets.ErrorPacket;
default: return undefined;
}
};
ChangeUser.prototype.start = function(handshakeInitializationPacket) {
var scrambleBuff = handshakeInitializationPacket.scrambleBuff();
scrambleBuff = Auth.token(this._password, scrambleBuff);
var packet = new Packets.ComChangeUserPacket({
user : this._user,
scrambleBuff : scrambleBuff,
database : this._database,
charsetNumber : this._charsetNumber
});
this._currentConfig.user = this._user;
this._currentConfig.password = this._password;
this._currentConfig.database = this._database;
this._currentConfig.charsetNumber = this._charsetNumber;
this.emit('packet', packet);
};
ChangeUser.prototype['AuthSwitchRequestPacket'] = function (packet) {
var name = packet.authMethodName;
var data = Auth.auth(name, packet.authMethodData, {
password: this._password
});
if (data !== undefined) {
this.emit('packet', new Packets.AuthSwitchResponsePacket({
data: data
}));
} else {
var err = new Error('MySQL is requesting the ' + name + ' authentication method, which is not supported.');
err.code = 'UNSUPPORTED_AUTH_METHOD';
err.fatal = true;
this.end(err);
}
};
ChangeUser.prototype['ErrorPacket'] = function(packet) {
var err = this._packetToError(packet);
err.fatal = true;
this.end(err);
};
var Sequence = require('./Sequence');
var Util = require('util');
var Packets = require('../packets');
var Auth = require('../Auth');
var ClientConstants = require('../constants/client');
module.exports = Handshake;
Util.inherits(Handshake, Sequence);
function Handshake(options, callback) {
Sequence.call(this, options, callback);
options = options || {};
this._config = options.config;
this._handshakeInitializationPacket = null;
}
Handshake.prototype.determinePacket = function determinePacket(firstByte, parser) {
if (firstByte === 0xff) {
return Packets.ErrorPacket;
}
if (!this._handshakeInitializationPacket) {
return Packets.HandshakeInitializationPacket;
}
if (firstByte === 0xfe) {
return (parser.packetLength() === 1)
? Packets.UseOldPasswordPacket
: Packets.AuthSwitchRequestPacket;
}
return undefined;
};
Handshake.prototype['AuthSwitchRequestPacket'] = function (packet) {
var name = packet.authMethodName;
var data = Auth.auth(name, packet.authMethodData, {
password: this._config.password
});
if (data !== undefined) {
this.emit('packet', new Packets.AuthSwitchResponsePacket({
data: data
}));
} else {
var err = new Error('MySQL is requesting the ' + name + ' authentication method, which is not supported.');
err.code = 'UNSUPPORTED_AUTH_METHOD';
err.fatal = true;
this.end(err);
}
};
Handshake.prototype['HandshakeInitializationPacket'] = function(packet) {
this._handshakeInitializationPacket = packet;
this._config.protocol41 = packet.protocol41;
var serverSSLSupport = packet.serverCapabilities1 & ClientConstants.CLIENT_SSL;
if (this._config.ssl) {
if (!serverSSLSupport) {
var err = new Error('Server does not support secure connection');
err.code = 'HANDSHAKE_NO_SSL_SUPPORT';
err.fatal = true;
this.end(err);
return;
}
this._config.clientFlags |= ClientConstants.CLIENT_SSL;
this.emit('packet', new Packets.SSLRequestPacket({
clientFlags : this._config.clientFlags,
maxPacketSize : this._config.maxPacketSize,
charsetNumber : this._config.charsetNumber
}));
this.emit('start-tls');
} else {
this._sendCredentials();
}
};
Handshake.prototype._tlsUpgradeCompleteHandler = function() {
this._sendCredentials();
};
Handshake.prototype._sendCredentials = function() {
var packet = this._handshakeInitializationPacket;
this.emit('packet', new Packets.ClientAuthenticationPacket({
clientFlags : this._config.clientFlags,
maxPacketSize : this._config.maxPacketSize,
charsetNumber : this._config.charsetNumber,
user : this._config.user,
database : this._config.database,
protocol41 : packet.protocol41,
scrambleBuff : (packet.protocol41)
? Auth.token(this._config.password, packet.scrambleBuff())
: Auth.scramble323(packet.scrambleBuff(), this._config.password)
}));
};
Handshake.prototype['UseOldPasswordPacket'] = function() {
if (!this._config.insecureAuth) {
var err = new Error(
'MySQL server is requesting the old and insecure pre-4.1 auth mechanism. ' +
'Upgrade the user password or use the {insecureAuth: true} option.'
);
err.code = 'HANDSHAKE_INSECURE_AUTH';
err.fatal = true;
this.end(err);
return;
}
this.emit('packet', new Packets.OldPasswordPacket({
scrambleBuff: Auth.scramble323(this._handshakeInitializationPacket.scrambleBuff(), this._config.password)
}));
};
Handshake.prototype['ErrorPacket'] = function(packet) {
var err = this._packetToError(packet, true);
err.fatal = true;
this.end(err);
};
var Sequence = require('./Sequence');
var Util = require('util');
var Packets = require('../packets');
module.exports = Ping;
Util.inherits(Ping, Sequence);
function Ping(options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = {};
}
Sequence.call(this, options, callback);
}
Ping.prototype.start = function() {
this.emit('packet', new Packets.ComPingPacket());
};
var ClientConstants = require('../constants/client');
var fs = require('fs');
var Packets = require('../packets');
var ResultSet = require('../ResultSet');
var Sequence = require('./Sequence');
var ServerStatus = require('../constants/server_status');
var Readable = require('readable-stream');
var Util = require('util');
module.exports = Query;
Util.inherits(Query, Sequence);
function Query(options, callback) {
Sequence.call(this, options, callback);
this.sql = options.sql;
this.values = options.values;
this.typeCast = (options.typeCast === undefined)
? true
: options.typeCast;
this.nestTables = options.nestTables || false;
this._resultSet = null;
this._results = [];
this._fields = [];
this._index = 0;
this._loadError = null;
}
Query.prototype.start = function() {
this.emit('packet', new Packets.ComQueryPacket(this.sql));
};
Query.prototype.determinePacket = function determinePacket(byte, parser) {
var resultSet = this._resultSet;
if (!resultSet) {
switch (byte) {
case 0x00: return Packets.OkPacket;
case 0xfb: return Packets.LocalInfileRequestPacket;
case 0xff: return Packets.ErrorPacket;
default: return Packets.ResultSetHeaderPacket;
}
}
if (resultSet.eofPackets.length === 0) {
return (resultSet.fieldPackets.length < resultSet.resultSetHeaderPacket.fieldCount)
? Packets.FieldPacket
: Packets.EofPacket;
}
if (byte === 0xff) {
return Packets.ErrorPacket;
}
if (byte === 0xfe && parser.packetLength() < 9) {
return Packets.EofPacket;
}
return Packets.RowDataPacket;
};
Query.prototype['OkPacket'] = function(packet) {
// try...finally for exception safety
try {
if (!this._callback) {
this.emit('result', packet, this._index);
} else {
this._results.push(packet);
this._fields.push(undefined);
}
} finally {
this._index++;
this._resultSet = null;
this._handleFinalResultPacket(packet);
}
};
Query.prototype['ErrorPacket'] = function(packet) {
var err = this._packetToError(packet);
var results = (this._results.length > 0)
? this._results
: undefined;
var fields = (this._fields.length > 0)
? this._fields
: undefined;
err.index = this._index;
err.sql = this.sql;
this.end(err, results, fields);
};
Query.prototype['LocalInfileRequestPacket'] = function(packet) {
if (this._connection.config.clientFlags & ClientConstants.CLIENT_LOCAL_FILES) {
this._sendLocalDataFile(packet.filename);
} else {
this._loadError = new Error('Load local files command is disabled');
this._loadError.code = 'LOCAL_FILES_DISABLED';
this._loadError.fatal = false;
this.emit('packet', new Packets.EmptyPacket());
}
};
Query.prototype['ResultSetHeaderPacket'] = function(packet) {
this._resultSet = new ResultSet(packet);
};
Query.prototype['FieldPacket'] = function(packet) {
this._resultSet.fieldPackets.push(packet);
};
Query.prototype['EofPacket'] = function(packet) {
this._resultSet.eofPackets.push(packet);
if (this._resultSet.eofPackets.length === 1 && !this._callback) {
this.emit('fields', this._resultSet.fieldPackets, this._index);
}
if (this._resultSet.eofPackets.length !== 2) {
return;
}
if (this._callback) {
this._results.push(this._resultSet.rows);
this._fields.push(this._resultSet.fieldPackets);
}
this._index++;
this._resultSet = null;
this._handleFinalResultPacket(packet);
};
Query.prototype._handleFinalResultPacket = function(packet) {
if (packet.serverStatus & ServerStatus.SERVER_MORE_RESULTS_EXISTS) {
return;
}
var results = (this._results.length > 1)
? this._results
: this._results[0];
var fields = (this._fields.length > 1)
? this._fields
: this._fields[0];
this.end(this._loadError, results, fields);
};
Query.prototype['RowDataPacket'] = function(packet, parser, connection) {
packet.parse(parser, this._resultSet.fieldPackets, this.typeCast, this.nestTables, connection);
if (this._callback) {
this._resultSet.rows.push(packet);
} else {
this.emit('result', packet, this._index);
}
};
Query.prototype._sendLocalDataFile = function(path) {
var self = this;
var localStream = fs.createReadStream(path, {
flag : 'r',
encoding : null,
autoClose : true
});
this.on('pause', function () {
localStream.pause();
});
this.on('resume', function () {
localStream.resume();
});
localStream.on('data', function (data) {
self.emit('packet', new Packets.LocalDataFilePacket(data));
});
localStream.on('error', function (err) {
self._loadError = err;
localStream.emit('end');
});
localStream.on('end', function () {
self.emit('packet', new Packets.EmptyPacket());
});
};
Query.prototype.stream = function(options) {
var self = this;
options = options || {};
options.objectMode = true;
var stream = new Readable(options);
stream._read = function() {
self._connection && self._connection.resume();
};
stream.once('end', function() {
process.nextTick(function () {
stream.emit('close');
});
});
this.on('result', function(row, i) {
if (!stream.push(row)) self._connection.pause();
stream.emit('result', row, i); // replicate old emitter
});
this.on('error', function(err) {
stream.emit('error', err); // Pass on any errors
});
this.on('end', function() {
stream.push(null); // pushing null, indicating EOF
});
this.on('fields', function(fields, i) {
stream.emit('fields', fields, i); // replicate old emitter
});
return stream;
};
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.