diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 4cb7acc..7323d4f 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -5,25 +5,21 @@ on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ node-version: [14, 16]
steps:
- - uses: actions/checkout@v1
- - name: Setup Node.js
- uses: actions/setup-node@v1
+ - uses: actions/checkout@v2
+ - uses: actions/setup-node@v2
with:
- node-version: 12.x
- - name: npm install
- run: npm install
- env:
- CI: true
- - name: lint
- run: npm run lint
- env:
- CI: true
+ node-version: ${{ matrix.node-version }}
+ - run: npm install
+ - run: npm run lint
unit:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v1
+ - uses: actions/checkout@v2
- name: mocha
run: docker-compose run --rm mocha
- name: docker-compose logs
diff --git a/README.md b/README.md
index 0b05115..5759a12 100644
--- a/README.md
+++ b/README.md
@@ -4,36 +4,84 @@
## Contents
-- [Demo](#demo)
+- [Demo](https://blueimp.github.io/JavaScript-Load-Image/)
- [Description](#description)
- [Setup](#setup)
- [Usage](#usage)
-- [Image loading](#image-loading)
-- [Image scaling](#image-scaling)
+ - [Image loading](#image-loading)
+ - [Image scaling](#image-scaling)
- [Requirements](#requirements)
+- [Browser support](#browser-support)
- [API](#api)
+ - [Callback](#callback)
+ - [Function signature](#function-signature)
+ - [Cancel image loading](#cancel-image-loading)
+ - [Callback arguments](#callback-arguments)
+ - [Error handling](#error-handling)
+ - [Promise](#promise)
- [Options](#options)
-- [Meta data parsing](#meta-data-parsing)
-- [Exif parser](#exif-parser)
-- [IPTC parser](#iptc-parser)
+ - [maxWidth](#maxwidth)
+ - [maxHeight](#maxheight)
+ - [minWidth](#minwidth)
+ - [minHeight](#minheight)
+ - [sourceWidth](#sourcewidth)
+ - [sourceHeight](#sourceheight)
+ - [top](#top)
+ - [right](#right)
+ - [bottom](#bottom)
+ - [left](#left)
+ - [contain](#contain)
+ - [cover](#cover)
+ - [aspectRatio](#aspectratio)
+ - [pixelRatio](#pixelratio)
+ - [downsamplingRatio](#downsamplingratio)
+ - [imageSmoothingEnabled](#imagesmoothingenabled)
+ - [imageSmoothingQuality](#imagesmoothingquality)
+ - [crop](#crop)
+ - [orientation](#orientation)
+ - [meta](#meta)
+ - [canvas](#canvas)
+ - [crossOrigin](#crossorigin)
+ - [noRevoke](#norevoke)
+- [Metadata parsing](#metadata-parsing)
+ - [Image head](#image-head)
+ - [Exif parser](#exif-parser)
+ - [Exif Thumbnail](#exif-thumbnail)
+ - [Exif IFD](#exif-ifd)
+ - [GPSInfo IFD](#gpsinfo-ifd)
+ - [Interoperability IFD](#interoperability-ifd)
+ - [Exif parser options](#exif-parser-options)
+ - [Exif writer](#exif-writer)
+ - [IPTC parser](#iptc-parser)
+ - [IPTC parser options](#iptc-parser-options)
- [License](#license)
- [Credits](#credits)
-## Demo
-
-[JavaScript Load Image Demo](https://blueimp.github.io/JavaScript-Load-Image/)
-
## Description
-JavaScript Load Image is a library to load images provided as File or Blob
-objects or via URL. It returns an optionally scaled and/or cropped HTML img or
-canvas element. It also provides methods to parse image meta data to extract
-IPTC and Exif tags as well as embedded thumbnail images and to restore the
-complete image header after resizing.
+JavaScript Load Image is a library to load images provided as `File` or `Blob`
+objects or via `URL`. It returns an optionally **scaled**, **cropped** or
+**rotated** HTML `img` or `canvas` element.
+
+It also provides methods to parse image metadata to extract
+[IPTC](https://iptc.org/standards/photo-metadata/) and
+[Exif](https://en.wikipedia.org/wiki/Exif) tags as well as embedded thumbnail
+images, to overwrite the Exif Orientation value and to restore the complete
+image header after resizing.
## Setup
-Include the (combined and minified) JavaScript Load Image script in your HTML
+Install via [NPM](https://www.npmjs.com/package/blueimp-load-image):
+
+```sh
+npm install blueimp-load-image
+```
+
+This will install the JavaScript files inside
+`./node_modules/blueimp-load-image/js/` relative to your current directory, from
+where you can copy them into a folder that is served by your web server.
+
+Next include the combined and minified JavaScript Load Image script in your HTML
markup:
```html
@@ -43,17 +91,31 @@ markup:
Or alternatively, choose which components you want to include:
```html
+
+
+
+
+
+
+
+
+
+
+
+
+
+
```
@@ -61,189 +123,308 @@ Or alternatively, choose which components you want to include:
### Image loading
-In your application code, use the **loadImage()** function like this:
+In your application code, use the `loadImage()` function with
+[callback](#callback) style:
```js
-document.getElementById("file-input").onchange = function(e) {
+document.getElementById('file-input').onchange = function () {
loadImage(
- e.target.files[0],
- function(img) {
- document.body.appendChild(img);
+ this.files[0],
+ function (img) {
+ document.body.appendChild(img)
},
{ maxWidth: 600 } // Options
- );
-};
+ )
+}
+```
+
+Or use the [Promise](#promise) based API like this ([requires](#requirements) a
+polyfill for older browsers):
+
+```js
+document.getElementById('file-input').onchange = function () {
+ loadImage(this.files[0], { maxWidth: 600 }).then(function (data) {
+ document.body.appendChild(data.image)
+ })
+}
+```
+
+With
+[async/await](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await)
+(requires a modern browser or a code transpiler like
+[Babel](https://babeljs.io/) or [TypeScript](https://www.typescriptlang.org/)):
+
+```js
+document.getElementById('file-input').onchange = async function () {
+ let data = await loadImage(this.files[0], { maxWidth: 600 })
+ document.body.appendChild(data.image)
+}
```
### Image scaling
-It is also possible to use the image scaling functionality with an existing
-image:
+It is also possible to use the image scaling functionality directly with an
+existing image:
```js
var scaledImage = loadImage.scale(
img, // img or canvas element
{ maxWidth: 600 }
-);
+)
```
## Requirements
-The JavaScript Load Image library has zero dependencies.
-
-However, JavaScript Load Image is a very suitable complement to the
-[Canvas to Blob](https://github.com/blueimp/JavaScript-Canvas-to-Blob) library.
+The JavaScript Load Image library has zero dependencies, but benefits from the
+following two
+[polyfills](https://developer.mozilla.org/en-US/docs/Glossary/Polyfill):
+
+- [blueimp-canvas-to-blob](https://github.com/blueimp/JavaScript-Canvas-to-Blob)
+ for browsers without native
+ [HTMLCanvasElement.toBlob](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
+ support, to create `Blob` objects out of `canvas` elements.
+- [promise-polyfill](https://github.com/taylorhakes/promise-polyfill) to be able
+ to use the
+ [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+ based `loadImage` API in Browsers without native `Promise` support.
+
+## Browser support
+
+Browsers which implement the following APIs support all options:
+
+- Loading images from File and Blob objects:
+ - [URL.createObjectURL](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL)
+ or
+ [FileReader.readAsDataURL](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL)
+- Parsing meta data:
+ - [FileReader.readAsArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsArrayBuffer)
+ - [Blob.slice](https://developer.mozilla.org/en-US/docs/Web/API/Blob/slice)
+ - [DataView](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+ (no [BigInt](https://developer.mozilla.org/en-US/docs/Glossary/BigInt)
+ support required)
+- Parsing meta data from images loaded via URL:
+ - [fetch Response.blob](https://developer.mozilla.org/en-US/docs/Web/API/Body/blob)
+ or
+ [XMLHttpRequest.responseType blob](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType#blob)
+- Promise based API:
+ - [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+
+This includes (but is not limited to) the following browsers:
+
+- Chrome 32+
+- Firefox 29+
+- Safari 8+
+- Mobile Chrome 42+ (Android)
+- Mobile Firefox 50+ (Android)
+- Mobile Safari 8+ (iOS)
+- Edge 74+
+- Edge Legacy 12+
+- Internet Explorer 10+ `*`
+
+`*` Internet Explorer [requires](#requirements) a polyfill for the `Promise`
+based API.
+
+Loading an image from a URL and applying transformations (scaling, cropping and
+rotating - except `orientation:true`, which requires reading meta data) is
+supported by all browsers which implement the
+[HTMLCanvasElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement)
+interface.
+
+Loading an image from a URL and scaling it in size is supported by all browsers
+which implement the
+[img](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) element and
+has been tested successfully with browser engines as old as Internet Explorer 5
+(via
+[IE11's emulation mode]()).
+
+The `loadImage()` function applies options using
+[progressive enhancement](https://en.wikipedia.org/wiki/Progressive_enhancement)
+and falls back to a configuration that is supported by the browser, e.g. if the
+`canvas` element is not supported, an equivalent `img` element is returned.
## API
-The **loadImage()** function accepts a
-[File](https://developer.mozilla.org/en/DOM/File) or
-[Blob](https://developer.mozilla.org/en/DOM/Blob) object or a simple image URL
-(e.g. `'https://example.org/image.png'`) as first argument.
-
-If a [File](https://developer.mozilla.org/en/DOM/File) or
-[Blob](https://developer.mozilla.org/en/DOM/Blob) is passed as parameter, it
-returns a HTML **img** element if the browser supports the
-[URL](https://developer.mozilla.org/en/DOM/window.URL) API or a
-[FileReader](https://developer.mozilla.org/en/DOM/FileReader) object if
-supported, or **false**.
-It always returns a HTML
-[img](https://developer.mozilla.org/en/docs/HTML/Element/Img) element when
-passing an image URL:
+### Callback
+
+#### Function signature
+
+The `loadImage()` function accepts a
+[File](https://developer.mozilla.org/en-US/docs/Web/API/File) or
+[Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) object or an image
+URL as first argument.
+
+If a [File](https://developer.mozilla.org/en-US/docs/Web/API/File) or
+[Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) is passed as
+parameter, it returns an HTML `img` element if the browser supports the
+[URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) API, alternatively a
+[FileReader](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) object
+if the `FileReader` API is supported, or `false`.
+
+It always returns an HTML
+[img](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Img) element
+when passing an image URL:
```js
-document.getElementById("file-input").onchange = function(e) {
- var loadingImage = loadImage(
- e.target.files[0],
- function(img) {
- document.body.appendChild(img);
- },
- { maxWidth: 600 }
- );
- if (!loadingImage) {
- // Alternative code ...
+var loadingImage = loadImage(
+ 'https://example.org/image.png',
+ function (img) {
+ document.body.appendChild(img)
+ },
+ { maxWidth: 600 }
+)
+```
+
+#### Cancel image loading
+
+Some browsers (e.g. Chrome) will cancel the image loading process if the `src`
+property of an `img` element is changed.
+To avoid unnecessary requests, we can use the
+[data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs)
+of a 1x1 pixel transparent GIF image as `src` target to cancel the original
+image download.
+
+To disable callback handling, we can also unset the image event handlers and for
+maximum browser compatibility, cancel the file reading process if the returned
+object is a
+[FileReader](https://developer.mozilla.org/en-US/docs/Web/API/FileReader)
+instance:
+
+```js
+var loadingImage = loadImage(
+ 'https://example.org/image.png',
+ function (img) {
+ document.body.appendChild(img)
+ },
+ { maxWidth: 600 }
+)
+
+if (loadingImage) {
+ // Unset event handling for the loading image:
+ loadingImage.onload = loadingImage.onerror = null
+
+ // Cancel image loading process:
+ if (loadingImage.abort) {
+ // FileReader instance, stop the file reading process:
+ loadingImage.abort()
+ } else {
+ // HTMLImageElement element, cancel the original image request by changing
+ // the target source to the data URL of a 1x1 pixel transparent image GIF:
+ loadingImage.src =
+ 'data:image/gif;base64,' +
+ 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
}
-};
+}
```
-The **img** element or
-[FileReader](https://developer.mozilla.org/en/DOM/FileReader) object returned by
-the **loadImage()** function allows to abort the loading process by setting the
-**onload** and **onerror** event handlers to null:
+**Please note:**
+The `img` element (or `FileReader` instance) for the loading image is only
+returned when using the callback style API and not available with the
+[Promise](#promise) based API.
+
+#### Callback arguments
+
+For the callback style API, the second argument to `loadImage()` must be a
+`callback` function, which is called when the image has been loaded or an error
+occurred while loading the image.
+
+The callback function is passed two arguments:
+
+1. An HTML [img](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img)
+ element or
+ [canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API)
+ element, or an
+ [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event) object of
+ type `error`.
+2. An object with the original image dimensions as properties and potentially
+ additional [metadata](#metadata-parsing).
```js
-document.getElementById("file-input").onchange = function(e) {
- var loadingImage = loadImage(
- e.target.files[0],
- function(img) {
- document.body.appendChild(img);
- },
- { maxWidth: 600 }
- );
- loadingImage.onload = loadingImage.onerror = null;
-};
+loadImage(
+ fileOrBlobOrUrl,
+ function (img, data) {
+ document.body.appendChild(img)
+ console.log('Original image width: ', data.originalWidth)
+ console.log('Original image height: ', data.originalHeight)
+ },
+ { maxWidth: 600, meta: true }
+)
```
-The second argument must be a **callback** function, which is called when the
-image has been loaded or an error occurred while loading the image. The callback
-function is passed two arguments.
-The first is either an HTML **img** element, a
-[canvas](https://developer.mozilla.org/en/HTML/Canvas) element, or an
-[Event](https://developer.mozilla.org/en/DOM/event) object of type **error**.
-The second is on object with the original image dimensions as properties and
-potentially additional [meta data](#meta-data-parsing):
+**Please note:**
+The original image dimensions reflect the natural width and height of the loaded
+image before applying any transformation.
+For consistent values across browsers, [metadata](#metadata-parsing) parsing has
+to be enabled via `meta:true`, so `loadImage` can detect automatic image
+orientation and normalize the dimensions.
+
+#### Error handling
+
+Example code implementing error handling:
```js
-var imageUrl = "https://example.org/image.png";
loadImage(
- imageUrl,
- function(img, data) {
- if (img.type === "error") {
- console.error("Error loading image " + imageUrl);
+ fileOrBlobOrUrl,
+ function (img, data) {
+ if (img.type === 'error') {
+ console.error('Error loading image file')
} else {
- document.body.appendChild(img);
- console.log("Original image width: ", data.originalWidth);
- console.log("Original image height: ", data.originalHeight);
+ document.body.appendChild(img)
}
},
{ maxWidth: 600 }
-);
+)
+```
+
+### Promise
+
+If the `loadImage()` function is called without a `callback` function as second
+argument and the
+[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+API is available, it returns a `Promise` object:
+
+```js
+loadImage(fileOrBlobOrUrl, { maxWidth: 600, meta: true })
+ .then(function (data) {
+ document.body.appendChild(data.image)
+ console.log('Original image width: ', data.originalWidth)
+ console.log('Original image height: ', data.originalHeight)
+ })
+ .catch(function (err) {
+ // Handling image loading errors
+ console.log(err)
+ })
```
+The `Promise` resolves with an object with the following properties:
+
+- `image`: An HTML
+ [img](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) or
+ [canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) element.
+- `originalWidth`: The original width of the image.
+- `originalHeight`: The original height of the image.
+
+Please also read the note about original image dimensions normalization in the
+[callback arguments](#callback-arguments) section.
+
+If [metadata](#metadata-parsing) has been parsed, additional properties might be
+present on the object.
+
+If image loading fails, the `Promise` rejects with an
+[Event](https://developer.mozilla.org/en-US/docs/Web/API/Event) object of type
+`error`.
+
## Options
-The optional third argument to **loadImage()** is a map of options:
-
-- **maxWidth**: Defines the maximum width of the img/canvas element.
-- **maxHeight**: Defines the maximum height of the img/canvas element.
-- **minWidth**: Defines the minimum width of the img/canvas element.
-- **minHeight**: Defines the minimum height of the img/canvas element.
-- **sourceWidth**: The width of the sub-rectangle of the source image to draw
- into the destination canvas.
- Defaults to the source image width and requires `canvas: true`.
-- **sourceHeight**: The height of the sub-rectangle of the source image to draw
- into the destination canvas.
- Defaults to the source image height and requires `canvas: true`.
-- **top**: The top margin of the sub-rectangle of the source image.
- Defaults to `0` and requires `canvas: true`.
-- **right**: The right margin of the sub-rectangle of the source image.
- Defaults to `0` and requires `canvas: true`.
-- **bottom**: The bottom margin of the sub-rectangle of the source image.
- Defaults to `0` and requires `canvas: true`.
-- **left**: The left margin of the sub-rectangle of the source image.
- Defaults to `0` and requires `canvas: true`.
-- **contain**: Scales the image up/down to contain it in the max dimensions if
- set to `true`.
- This emulates the CSS feature
- [background-image: contain](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#contain).
-- **cover**: Scales the image up/down to cover the max dimensions with the image
- dimensions if set to `true`.
- This emulates the CSS feature
- [background-image: cover](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#cover).
-- **aspectRatio**: Crops the image to the given aspect ratio (e.g. `16/9`).
- Setting the `aspectRatio` also enables the `crop` option.
-- **pixelRatio**: Defines the ratio of the canvas pixels to the physical image
- pixels on the screen.
- Should be set to `window.devicePixelRatio` unless the scaled image is not
- rendered on screen.
- Defaults to `1` and requires `canvas: true`.
-- **downsamplingRatio**: Defines the ratio in which the image is downsampled.
- By default, images are downsampled in one step. With a ratio of `0.5`, each
- step scales the image to half the size, before reaching the target dimensions.
- Requires `canvas: true`.
-- **crop**: Crops the image to the maxWidth/maxHeight constraints if set to
- `true`.
- Enabling the `crop` option also enables the `canvas` option.
-- **orientation**: Transform the canvas according to the specified Exif
- orientation, which can be an `integer` in the range of `1` to `8` or the
- boolean value `true`.
- When set to `true`, it will set the orientation value based on the EXIF data
- of the image, which will be parsed automatically if the exif library is
- available.
- Setting the `orientation` also enables the `canvas` option.
- Setting `orientation` to `true` also enables the `meta` option.
-- **meta**: Automatically parses the image meta data if set to `true`.
- The meta data is passed to the callback as part of the second argument.
- If the file is given as URL and the browser supports the
- [fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API), fetches
- the file as Blob to be able to parse the meta data.
-- **canvas**: Returns the image as
- [canvas](https://developer.mozilla.org/en/HTML/Canvas) element if set to
- `true`.
-- **crossOrigin**: Sets the crossOrigin property on the img element for loading
- [CORS enabled images](https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image).
-- **noRevoke**: By default, the
- [created object URL](https://developer.mozilla.org/en/DOM/window.URL.createObjectURL)
- is revoked after the image has been loaded, except when this option is set to
- `true`.
-
-They can be used the following way:
+The optional options argument to `loadImage()` allows to configure the image
+loading.
+
+It can be used the following way with the callback style:
```js
loadImage(
fileOrBlobOrUrl,
- function(img) {
- document.body.appendChild(img);
+ function (img) {
+ document.body.appendChild(img)
},
{
maxWidth: 600,
@@ -252,151 +433,638 @@ loadImage(
minHeight: 50,
canvas: true
}
-);
+)
```
-All settings are optional. By default, the image is returned as HTML **img**
+Or the following way with the `Promise` based API:
+
+```js
+loadImage(fileOrBlobOrUrl, {
+ maxWidth: 600,
+ maxHeight: 300,
+ minWidth: 100,
+ minHeight: 50,
+ canvas: true
+}).then(function (data) {
+ document.body.appendChild(data.image)
+})
+```
+
+All settings are optional. By default, the image is returned as HTML `img`
element without any image size restrictions.
-## Meta data parsing
+### maxWidth
+
+Defines the maximum width of the `img`/`canvas` element.
+
+### maxHeight
+
+Defines the maximum height of the `img`/`canvas` element.
+
+### minWidth
+
+Defines the minimum width of the `img`/`canvas` element.
+
+### minHeight
+
+Defines the minimum height of the `img`/`canvas` element.
+
+### sourceWidth
+
+The width of the sub-rectangle of the source image to draw into the destination
+canvas.
+Defaults to the source image width and requires `canvas: true`.
+
+### sourceHeight
+
+The height of the sub-rectangle of the source image to draw into the destination
+canvas.
+Defaults to the source image height and requires `canvas: true`.
+
+### top
+
+The top margin of the sub-rectangle of the source image.
+Defaults to `0` and requires `canvas: true`.
+
+### right
+
+The right margin of the sub-rectangle of the source image.
+Defaults to `0` and requires `canvas: true`.
+
+### bottom
+
+The bottom margin of the sub-rectangle of the source image.
+Defaults to `0` and requires `canvas: true`.
+
+### left
+
+The left margin of the sub-rectangle of the source image.
+Defaults to `0` and requires `canvas: true`.
+
+### contain
+
+Scales the image up/down to contain it in the max dimensions if set to `true`.
+This emulates the CSS feature
+[background-image: contain](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Backgrounds_and_Borders/Resizing_background_images#contain).
+
+### cover
+
+Scales the image up/down to cover the max dimensions with the image dimensions
+if set to `true`.
+This emulates the CSS feature
+[background-image: cover](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Backgrounds_and_Borders/Resizing_background_images#cover).
+
+### aspectRatio
+
+Crops the image to the given aspect ratio (e.g. `16/9`).
+Setting the `aspectRatio` also enables the `crop` option.
+
+### pixelRatio
+
+Defines the ratio of the canvas pixels to the physical image pixels on the
+screen.
+Should be set to
+[window.devicePixelRatio](https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio)
+unless the scaled image is not rendered on screen.
+Defaults to `1` and requires `canvas: true`.
+
+### downsamplingRatio
+
+Defines the ratio in which the image is downsampled (scaled down in steps).
+By default, images are downsampled in one step.
+With a ratio of `0.5`, each step scales the image to half the size, before
+reaching the target dimensions.
+Requires `canvas: true`.
-If the Load Image Meta extension is included, it is also possible to parse image
-meta data automatically with the `meta` option:
+### imageSmoothingEnabled
+
+If set to `false`,
+[disables image smoothing](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/imageSmoothingEnabled).
+Defaults to `true` and requires `canvas: true`.
+
+### imageSmoothingQuality
+
+Sets the
+[quality of image smoothing](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/imageSmoothingQuality).
+Possible values: `'low'`, `'medium'`, `'high'`
+Defaults to `'low'` and requires `canvas: true`.
+
+### crop
+
+Crops the image to the `maxWidth`/`maxHeight` constraints if set to `true`.
+Enabling the `crop` option also enables the `canvas` option.
+
+### orientation
+
+Transform the canvas according to the specified Exif orientation, which can be
+an `integer` in the range of `1` to `8` or the boolean value `true`.
+
+When set to `true`, it will set the orientation value based on the Exif data of
+the image, which will be parsed automatically if the Exif extension is
+available.
+
+Exif orientation values to correctly display the letter F:
+
+```
+ 1 2
+ ██████ ██████
+ ██ ██
+ ████ ████
+ ██ ██
+ ██ ██
+
+ 3 4
+ ██ ██
+ ██ ██
+ ████ ████
+ ██ ██
+ ██████ ██████
+
+ 5 6
+██████████ ██
+██ ██ ██ ██
+██ ██████████
+
+ 7 8
+ ██ ██████████
+ ██ ██ ██ ██
+██████████ ██
+```
+
+Setting `orientation` to `true` enables the `canvas` and `meta` options, unless
+the browser supports automatic image orientation (see
+[browser support for image-orientation](https://caniuse.com/#feat=css-image-orientation)).
+
+Setting `orientation` to `1` enables the `canvas` and `meta` options if the
+browser does support automatic image orientation (to allow reset of the
+orientation).
+
+Setting `orientation` to an integer in the range of `2` to `8` always enables
+the `canvas` option and also enables the `meta` option if the browser supports
+automatic image orientation (again to allow reset).
+
+### meta
+
+Automatically parses the image metadata if set to `true`.
+
+If metadata has been found, the data object passed as second argument to the
+callback function has additional properties (see
+[metadata parsing](#metadata-parsing)).
+
+If the file is given as URL and the browser supports the
+[fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) or the
+XHR
+[responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType)
+`blob`, fetches the file as `Blob` to be able to parse the metadata.
+
+### canvas
+
+Returns the image as
+[canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) element if
+set to `true`.
+
+### crossOrigin
+
+Sets the `crossOrigin` property on the `img` element for loading
+[CORS enabled images](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image).
+
+### noRevoke
+
+By default, the
+[created object URL](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL)
+is revoked after the image has been loaded, except when this option is set to
+`true`.
+
+## Metadata parsing
+
+If the Load Image Meta extension is included, it is possible to parse image meta
+data automatically with the `meta` option:
```js
loadImage(
fileOrBlobOrUrl,
- function(img, data) {
- console.log("Original image head: ", data.imageHead);
- console.log("Exif data: ", data.exif); // requires exif extension
- console.log("IPTC data: ", data.iptc); // requires iptc extension
+ function (img, data) {
+ console.log('Original image head: ', data.imageHead)
+ console.log('Exif data: ', data.exif) // requires exif extension
+ console.log('IPTC data: ', data.iptc) // requires iptc extension
},
{ meta: true }
-);
+)
```
-The extension also provides the method **loadImage.parseMetaData**, which can be
-used the following way:
+Or alternatively via `loadImage.parseMetaData`, which can be used with an
+available `File` or `Blob` object as first argument:
```js
loadImage.parseMetaData(
fileOrBlob,
- function(data) {
- if (!data.imageHead) {
- return;
- }
- // Combine data.imageHead with the image body of a resized file
- // to create scaled images with the original image meta data, e.g.:
- var blob = new Blob(
- [
- data.imageHead,
- // Resized images always have a head size of 20 bytes,
- // including the JPEG marker and a minimal JFIF header:
- loadImage.blobSlice.call(resizedImageBlob, 20)
- ],
- { type: resizedImageBlob.type }
- );
+ function (data) {
+ console.log('Original image head: ', data.imageHead)
+ console.log('Exif data: ', data.exif) // requires exif extension
+ console.log('IPTC data: ', data.iptc) // requires iptc extension
},
{
- maxMetaDataSize: 262144,
- disableImageHead: false
+ maxMetaDataSize: 262144
}
-);
+)
```
-**Note:**
-Blob objects of resized images can be created via
-[canvas.toBlob()](https://github.com/blueimp/JavaScript-Canvas-to-Blob).
+Or using the
+[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+based API:
-The Meta data extension also adds additional options used for the
-`parseMetaData` method:
+```js
+loadImage
+ .parseMetaData(fileOrBlob, {
+ maxMetaDataSize: 262144
+ })
+ .then(function (data) {
+ console.log('Original image head: ', data.imageHead)
+ console.log('Exif data: ', data.exif) // requires exif extension
+ console.log('IPTC data: ', data.iptc) // requires iptc extension
+ })
+```
-- **maxMetaDataSize**: Maximum number of bytes of meta data to parse.
-- **disableImageHead**: Disable parsing the original image head.
+The Metadata extension adds additional options used for the `parseMetaData`
+method:
+
+- `maxMetaDataSize`: Maximum number of bytes of metadata to parse.
+- `disableImageHead`: Disable parsing the original image head.
+- `disableMetaDataParsers`: Disable parsing metadata (image head only)
+
+### Image head
+
+Resized JPEG images can be combined with their original image head via
+`loadImage.replaceHead`, which requires the resized image as `Blob` object as
+first argument and an `ArrayBuffer` image head as second argument.
+
+With callback style, the third argument must be a `callback` function, which is
+called with the new `Blob` object:
+
+```js
+loadImage(
+ fileOrBlobOrUrl,
+ function (img, data) {
+ if (data.imageHead) {
+ img.toBlob(function (blob) {
+ loadImage.replaceHead(blob, data.imageHead, function (newBlob) {
+ // do something with the new Blob object
+ })
+ }, 'image/jpeg')
+ }
+ },
+ { meta: true, canvas: true, maxWidth: 800 }
+)
+```
+
+Or using the
+[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+based API like this:
+
+```js
+loadImage(fileOrBlobOrUrl, { meta: true, canvas: true, maxWidth: 800 })
+ .then(function (data) {
+ if (!data.imageHead) throw new Error('Could not parse image metadata')
+ return new Promise(function (resolve) {
+ data.image.toBlob(function (blob) {
+ data.blob = blob
+ resolve(data)
+ }, 'image/jpeg')
+ })
+ })
+ .then(function (data) {
+ return loadImage.replaceHead(data.blob, data.imageHead)
+ })
+ .then(function (blob) {
+ // do something with the new Blob object
+ })
+ .catch(function (err) {
+ console.error(err)
+ })
+```
+
+**Please note:**
+`Blob` objects of resized images can be created via
+[HTMLCanvasElement.toBlob](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob).
+[blueimp-canvas-to-blob](https://github.com/blueimp/JavaScript-Canvas-to-Blob)
+provides a polyfill for browsers without native `canvas.toBlob()` support.
### Exif parser
If you include the Load Image Exif Parser extension, the argument passed to the
-callback for **parseMetaData** will contain the additional property **exif** if
-Exif data could be found in the given image.
-The **exif** object stores the parsed Exif tags:
+callback for `parseMetaData` will contain the following additional properties if
+Exif data could be found in the given image:
+
+- `exif`: The parsed Exif tags
+- `exifOffsets`: The parsed Exif tag offsets
+- `exifTiffOffset`: TIFF header offset (used for offset pointers)
+- `exifLittleEndian`: little endian order if true, big endian if false
+
+The `exif` object stores the parsed Exif tags:
```js
-var orientation = data.exif[0x0112];
+var orientation = data.exif[0x0112] // Orientation
```
-It also provides an **exif.get()** method to retrieve the tag value via the
-tag's mapped name:
+The `exif` and `exifOffsets` objects also provide a `get()` method to retrieve
+the tag value/offset via the tag's mapped name:
```js
-var orientation = data.exif.get("Orientation");
+var orientation = data.exif.get('Orientation')
+var orientationOffset = data.exifOffsets.get('Orientation')
```
-By default, the only available mapped names are **Orientation** and
-**Thumbnail**.
+By default, only the following names are mapped:
+
+- `Orientation`
+- `Thumbnail` (see [Exif Thumbnail](#exif-thumbnail))
+- `Exif` (see [Exif IFD](#exif-ifd))
+- `GPSInfo` (see [GPSInfo IFD](#gpsinfo-ifd))
+- `Interoperability` (see [Interoperability IFD](#interoperability-ifd))
+
If you also include the Load Image Exif Map library, additional tag mappings
-become available, as well as two additional methods, **exif.getText()** and
-**exif.getAll()**:
+become available, as well as three additional methods:
+
+- `exif.getText()`
+- `exif.getName()`
+- `exif.getAll()`
```js
-var flashText = data.exif.getText("Flash"); // e.g.: 'Flash fired, auto mode',
+var orientationText = data.exif.getText('Orientation') // e.g. "Rotate 90° CW"
+
+var name = data.exif.getName(0x0112) // "Orientation"
// A map of all parsed tags with their mapped names/text as keys/values:
-var allTags = data.exif.getAll();
+var allTags = data.exif.getAll()
+```
+
+#### Exif Thumbnail
+
+Example code displaying a thumbnail image embedded into the Exif metadata:
+
+```js
+loadImage(
+ fileOrBlobOrUrl,
+ function (img, data) {
+ var exif = data.exif
+ var thumbnail = exif && exif.get('Thumbnail')
+ var blob = thumbnail && thumbnail.get('Blob')
+ if (blob) {
+ loadImage(
+ blob,
+ function (thumbImage) {
+ document.body.appendChild(thumbImage)
+ },
+ { orientation: exif.get('Orientation') }
+ )
+ }
+ },
+ { meta: true }
+)
+```
+
+#### Exif IFD
+
+Example code displaying data from the Exif IFD (Image File Directory) that
+contains Exif specified TIFF tags:
+
+```js
+loadImage(
+ fileOrBlobOrUrl,
+ function (img, data) {
+ var exifIFD = data.exif && data.exif.get('Exif')
+ if (exifIFD) {
+ // Map of all Exif IFD tags with their mapped names/text as keys/values:
+ console.log(exifIFD.getAll())
+ // A specific Exif IFD tag value:
+ console.log(exifIFD.get('UserComment'))
+ }
+ },
+ { meta: true }
+)
+```
+
+#### GPSInfo IFD
+
+Example code displaying data from the Exif IFD (Image File Directory) that
+contains [GPS](https://en.wikipedia.org/wiki/Global_Positioning_System) info:
+
+```js
+loadImage(
+ fileOrBlobOrUrl,
+ function (img, data) {
+ var gpsInfo = data.exif && data.exif.get('GPSInfo')
+ if (gpsInfo) {
+ // Map of all GPSInfo tags with their mapped names/text as keys/values:
+ console.log(gpsInfo.getAll())
+ // A specific GPSInfo tag value:
+ console.log(gpsInfo.get('GPSLatitude'))
+ }
+ },
+ { meta: true }
+)
+```
+
+#### Interoperability IFD
+
+Example code displaying data from the Exif IFD (Image File Directory) that
+contains Interoperability data:
+
+```js
+loadImage(
+ fileOrBlobOrUrl,
+ function (img, data) {
+ var interoperabilityData = data.exif && data.exif.get('Interoperability')
+ if (interoperabilityData) {
+ // The InteroperabilityIndex tag value:
+ console.log(interoperabilityData.get('InteroperabilityIndex'))
+ }
+ },
+ { meta: true }
+)
+```
+
+#### Exif parser options
+
+The Exif parser adds additional options:
+
+- `disableExif`: Disables Exif parsing when `true`.
+- `disableExifOffsets`: Disables storing Exif tag offsets when `true`.
+- `includeExifTags`: A map of Exif tags to include for parsing (includes all but
+ the excluded tags by default).
+- `excludeExifTags`: A map of Exif tags to exclude from parsing (defaults to
+ exclude `Exif` `MakerNote`).
+
+An example parsing only Orientation, Thumbnail and ExifVersion tags:
+
+```js
+loadImage.parseMetaData(
+ fileOrBlob,
+ function (data) {
+ console.log('Exif data: ', data.exif)
+ },
+ {
+ includeExifTags: {
+ 0x0112: true, // Orientation
+ ifd1: {
+ 0x0201: true, // JPEGInterchangeFormat (Thumbnail data offset)
+ 0x0202: true // JPEGInterchangeFormatLength (Thumbnail data length)
+ },
+ 0x8769: {
+ // ExifIFDPointer
+ 0x9000: true // ExifVersion
+ }
+ }
+ }
+)
```
-The Exif parser also adds additional options for the parseMetaData method, to
-disable certain aspects of the parser:
+An example excluding `Exif` `MakerNote` and `GPSInfo`:
+
+```js
+loadImage.parseMetaData(
+ fileOrBlob,
+ function (data) {
+ console.log('Exif data: ', data.exif)
+ },
+ {
+ excludeExifTags: {
+ 0x8769: {
+ // ExifIFDPointer
+ 0x927c: true // MakerNote
+ },
+ 0x8825: true // GPSInfoIFDPointer
+ }
+ }
+)
+```
+
+### Exif writer
+
+The Exif parser extension also includes a minimal writer that allows to override
+the Exif `Orientation` value in the parsed `imageHead` `ArrayBuffer`:
+
+```js
+loadImage(
+ fileOrBlobOrUrl,
+ function (img, data) {
+ if (data.imageHead && data.exif) {
+ // Reset Exif Orientation data:
+ loadImage.writeExifData(data.imageHead, data, 'Orientation', 1)
+ img.toBlob(function (blob) {
+ loadImage.replaceHead(blob, data.imageHead, function (newBlob) {
+ // do something with newBlob
+ })
+ }, 'image/jpeg')
+ }
+ },
+ { meta: true, orientation: true, canvas: true, maxWidth: 800 }
+)
+```
-- **disableExif**: Disables Exif parsing.
-- **disableExifThumbnail**: Disables parsing of the Exif Thumbnail.
-- **disableExifSub**: Disables parsing of the Exif Sub IFD.
-- **disableExifGps**: Disables parsing of the Exif GPS Info IFD.
+**Please note:**
+The Exif writer relies on the Exif tag offsets being available as
+`data.exifOffsets` property, which requires that Exif data has been parsed from
+the image.
+The Exif writer can only change existing values, not add new tags, e.g. it
+cannot add an Exif `Orientation` tag for an image that does not have one.
### IPTC parser
If you include the Load Image IPTC Parser extension, the argument passed to the
-callback for **parseMetaData** will contain the additional property **iptc** if
-IPTC data could be found in the given image.
-The **iptc** object stores the parsed IPTC tags:
+callback for `parseMetaData` will contain the following additional properties if
+IPTC data could be found in the given image:
+
+- `iptc`: The parsed IPTC tags
+- `iptcOffsets`: The parsed IPTC tag offsets
+
+The `iptc` object stores the parsed IPTC tags:
```js
-var objectname = data.iptc[0x5];
+var objectname = data.iptc[5]
```
-It also provides an **iptc.get()** method to retrieve the tag value via the
-tag's mapped name:
+The `iptc` and `iptcOffsets` objects also provide a `get()` method to retrieve
+the tag value/offset via the tag's mapped name:
```js
-var objectname = data.iptc.get("ObjectName");
+var objectname = data.iptc.get('ObjectName')
```
-By default, the only available mapped names are **ObjectName**.
+By default, only the following names are mapped:
+
+- `ObjectName`
+
If you also include the Load Image IPTC Map library, additional tag mappings
-become available, as well as two additional methods, **iptc.getText()** and
-**iptc.getAll()**:
+become available, as well as three additional methods:
+
+- `iptc.getText()`
+- `iptc.getName()`
+- `iptc.getAll()`
```js
-var keywords = data.iptc.getText("Keywords"); // e.g.: ['Weather','Sky']
+var keywords = data.iptc.getText('Keywords') // e.g.: ['Weather','Sky']
+
+var name = data.iptc.getName(5) // ObjectName
// A map of all parsed tags with their mapped names/text as keys/values:
-var allTags = data.iptc.getAll();
+var allTags = data.iptc.getAll()
+```
+
+#### IPTC parser options
+
+The IPTC parser adds additional options:
+
+- `disableIptc`: Disables IPTC parsing when true.
+- `disableIptcOffsets`: Disables storing IPTC tag offsets when `true`.
+- `includeIptcTags`: A map of IPTC tags to include for parsing (includes all but
+ the excluded tags by default).
+- `excludeIptcTags`: A map of IPTC tags to exclude from parsing (defaults to
+ exclude `ObjectPreviewData`).
+
+An example parsing only the `ObjectName` tag:
+
+```js
+loadImage.parseMetaData(
+ fileOrBlob,
+ function (data) {
+ console.log('IPTC data: ', data.iptc)
+ },
+ {
+ includeIptcTags: {
+ 5: true // ObjectName
+ }
+ }
+)
```
-The IPTC parser also adds additional options for the parseMetaData method, to
-disable certain aspects of the parser:
+An example excluding `ApplicationRecordVersion` and `ObjectPreviewData`:
-- **disableIptc**: Disables IPTC parsing.
+```js
+loadImage.parseMetaData(
+ fileOrBlob,
+ function (data) {
+ console.log('IPTC data: ', data.iptc)
+ },
+ {
+ excludeIptcTags: {
+ 0: true, // ApplicationRecordVersion
+ 202: true // ObjectPreviewData
+ }
+ }
+)
+```
## License
-The JavaScript Load Image script is released under the
+The JavaScript Load Image library is released under the
[MIT license](https://opensource.org/licenses/MIT).
## Credits
-- Image meta data handling implementation based on the help and contribution of
+- Original image metadata handling implemented with the help and contribution of
Achim Stöhr.
-- Exif tags mapping based on Jacob Seidelin's
- [exif-js](https://github.com/jseidelin/exif-js) library.
-- IPTC parser implementation by [Dave Bevan](https://github.com/bevand10).
+- Original Exif tags mapping based on Jacob Seidelin's
+ [exif-js](https://github.com/exif-js/exif-js) library.
+- Original IPTC parser implementation by
+ [Dave Bevan](https://github.com/bevand10).
diff --git a/bin/sync-vendor-libs.sh b/bin/sync-vendor-libs.sh
new file mode 100755
index 0000000..bff8eb3
--- /dev/null
+++ b/bin/sync-vendor-libs.sh
@@ -0,0 +1,8 @@
+#!/bin/sh
+cd "$(dirname "$0")/.."
+cp node_modules/blueimp-canvas-to-blob/js/canvas-to-blob.js js/vendor/
+cp node_modules/jquery/dist/jquery.js js/vendor/
+cp node_modules/promise-polyfill/dist/polyfill.js js/vendor/promise-polyfill.js
+cp node_modules/chai/chai.js test/vendor/
+cp node_modules/mocha/mocha.js test/vendor/
+cp node_modules/mocha/mocha.css test/vendor/
diff --git a/css/demo.css b/css/demo.css
index 2b2a8d5..97e4ec5 100644
--- a/css/demo.css
+++ b/css/demo.css
@@ -10,31 +10,25 @@
*/
body {
- max-width: 750px;
+ max-width: 990px;
margin: 0 auto;
padding: 1em;
- font-family: 'Lucida Grande', 'Lucida Sans Unicode', Arial, sans-serif;
- font-size: 1em;
- line-height: 1.4em;
- background: #222;
- color: #fff;
+ font-family: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue',
+ Arial, sans-serif;
-webkit-text-size-adjust: 100%;
- -ms-text-size-adjust: 100%;
+ line-height: 1.4;
+ background: #212121;
+ color: #dedede;
}
a {
- color: orange;
+ color: #61afef;
text-decoration: none;
}
-img {
- border: 0;
- vertical-align: middle;
+a:visited {
+ color: #56b6c2;
}
-h1 {
- line-height: 1em;
-}
-h2,
-h3 {
- margin-top: 2em;
+a:hover {
+ color: #98c379;
}
table {
width: 100%;
@@ -42,29 +36,194 @@ table {
table-layout: fixed;
border-collapse: collapse;
}
-tr {
- background: #fff;
- color: #222;
+figure {
+ margin: 0;
+ padding: 0.75em;
+ border-radius: 5px;
+ display: inline-block;
+}
+table,
+figure {
+ margin-bottom: 1.25em;
+}
+tr,
+figure {
+ background: #363636;
}
tr:nth-child(odd) {
- background: #eee;
- color: #222;
+ background: #414141;
+}
+td,
+th {
+ padding: 0.5em 0.75em;
+ text-align: left;
}
-td {
- padding: 10px;
+img,
+canvas {
+ max-width: 100%;
+ border: 0;
+ vertical-align: middle;
}
-#result,
-#thumbnail {
- padding: 20px;
- background: #fff;
- color: #222;
- text-align: center;
+h1,
+h2,
+h3,
+h4,
+h5,
+h6 {
+ margin-top: 1.5em;
+ margin-bottom: 0.5em;
}
-.jcrop-holder {
- margin: 0 auto;
+h1 {
+ margin-top: 0.5em;
+}
+label {
+ display: inline-block;
+ margin-bottom: 0.25em;
+}
+button,
+select,
+input,
+textarea {
+ -webkit-appearance: none;
+ box-sizing: border-box;
+ margin: 0;
+ padding: 0.5em 0.75em;
+ font-family: inherit;
+ font-size: 100%;
+ line-height: 1.4;
+ background: #414141;
+ color: #dedede;
+ border: 1px solid #363636;
+ border-radius: 5px;
+ box-shadow: 0 0 4px rgba(0, 0, 0, 0.07);
+}
+input,
+textarea {
+ width: 100%;
+ box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.07);
+}
+textarea {
+ display: block;
+ overflow: auto;
+}
+button {
+ background: #3c76a7;
+ background: linear-gradient(180deg, #3c76a7, #225c8d);
+ border-color: #225c8d;
+ color: #fff;
+}
+button[type='submit'] {
+ background: #6fa349;
+ background: linear-gradient(180deg, #6fa349, #568a30);
+ border-color: #568a30;
+}
+button[type='reset'] {
+ background: #d79435;
+ background: linear-gradient(180deg, #d79435, #be7b1c);
+ border-color: #be7b1c;
+}
+select {
+ display: block;
+ padding-right: 2.25em;
+ background: #3c76a7;
+ background: url('data:image/svg+xml;charset=utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 5"%3E%3Cpath fill="%23fff" d="M2 0L0 2h4zm0 5L0 3h4z"/%3E%3C/svg%3E')
+ no-repeat right 0.75em center/0.75em,
+ linear-gradient(180deg, #3c76a7, #225c8d);
+ border-color: #225c8d;
+ color: #fff;
+}
+button:active,
+select:active {
+ box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.5);
+}
+select::-ms-expand {
+ display: none;
+}
+option {
+ color: #212121;
+}
+input[type='checkbox'] {
+ -webkit-appearance: checkbox;
+ width: auto;
+ padding: initial;
+ box-shadow: none;
+}
+input[type='file'] {
+ max-width: 100%;
+ padding: 0;
+ background: none;
+ border: 0;
+ border-radius: 0;
+ box-shadow: none;
+}
+
+input[type='file']::-webkit-file-upload-button {
+ -webkit-appearance: none;
+ box-sizing: border-box;
+ padding: 0.5em 0.75em;
+ font-family: inherit;
+ font-size: 100%;
+ line-height: 1.4;
+ background: linear-gradient(180deg, #3c76a7, #225c8d);
+ border: 1px solid #225c8d;
+ color: #fff;
+ border-radius: 5px;
+ box-shadow: 0 0 4px rgba(0, 0, 0, 0.07);
+}
+input[type='file']::-webkit-file-upload-button:active {
+ box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.5);
+}
+input[type='file']::-ms-browse {
+ box-sizing: border-box;
+ padding: 0.5em 0.75em;
+ font-family: inherit;
+ font-size: 100%;
+ line-height: 1.4;
+ background: linear-gradient(180deg, #3c76a7, #225c8d);
+ border: 1px solid #225c8d;
+ color: #fff;
+ border-radius: 5px;
+ box-shadow: 0 0 4px rgba(0, 0, 0, 0.07);
+}
+input[type='file']::-ms-browse:active {
+ box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.5);
+}
+
+@media (prefers-color-scheme: light) {
+ body {
+ background: #ececec;
+ color: #212121;
+ }
+ a {
+ color: #225c8d;
+ }
+ a:visited {
+ color: #378f9a;
+ }
+ a:hover {
+ color: #6fa349;
+ }
+ figure,
+ tr {
+ background: #fff;
+ color: #212121;
+ }
+ tr:nth-child(odd) {
+ background: #f6f6f6;
+ }
+ input,
+ textarea {
+ background: #fff;
+ border-color: #d1d1d1;
+ color: #212121;
+ }
+}
+
+#result {
+ display: block;
}
-@media (min-width: 481px) {
+@media (min-width: 540px) {
#navigation {
list-style: none;
padding: 0;
@@ -72,7 +231,7 @@ td {
#navigation li {
display: inline-block;
}
- #navigation li:not(:first-child):before {
- content: '| ';
+ #navigation li:not(:first-child)::before {
+ content: ' | ';
}
}
diff --git a/docker-compose.yml b/docker-compose.yml
index 74f66fe..6bba835 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -4,7 +4,6 @@ services:
image: nginx:alpine
ports:
- 127.0.0.1:80:80
- - ${SERVER_HOST:-127.0.0.1}:${SERVER_PORT-}:80
volumes:
- .:/usr/share/nginx/html:ro
mocha:
diff --git a/index.html b/index.html
index 3610e16..05d5ac0 100644
--- a/index.html
+++ b/index.html
@@ -20,7 +20,7 @@
JavaScript Load Image
+
JavaScript Load Image Demo
@@ -36,24 +44,31 @@ JavaScript Load Image Demo
>JavaScript Load Image
is a library to load images provided as
- File or
- Blob objects or
- via URL.
- It returns an optionally scaled and/or
- cropped HTML
- img
+ File
+ or
+ Blob
+ objects or via URL.
+ It returns an optionally scaled ,
+ cropped or rotated HTML
+ img
or
- canvas
- element.
- It also provides a method to parse image meta data to extract
+ canvas
+ element.
+
+
-
IPTC meta data
-
+
+
+
+
Image metadata
+
+
diff --git a/js/demo/demo.js b/js/demo/demo.js
index f1db0c8..a95cf55 100644
--- a/js/demo/demo.js
+++ b/js/demo/demo.js
@@ -11,15 +11,20 @@
/* global loadImage, $ */
-$(function() {
+$(function () {
'use strict'
- var result = $('#result')
- var exifNode = $('#exif')
- var iptcNode = $('#iptc')
+ var resultNode = $('#result')
+ var metaNode = $('#meta')
var thumbNode = $('#thumbnail')
var actionsNode = $('#actions')
- var currentFile
+ var orientationNode = $('#orientation')
+ var imageSmoothingNode = $('#image-smoothing')
+ var fileInputNode = $('#file-input')
+ var urlNode = $('#url')
+ var editNode = $('#edit')
+ var cropNode = $('#crop')
+ var cancelNode = $('#cancel')
var coordinates
var jcropAPI
@@ -27,15 +32,22 @@ $(function() {
* Displays tag data
*
* @param {*} node jQuery node
- * @param {object} tags Tags object
+ * @param {object} tags Tags map
+ * @param {string} title Tags title
*/
- function displayTagData(node, tags) {
- var table = node.find('table').empty()
+ function displayTagData(node, tags, title) {
+ var table = $('
')
var row = $('
')
var cell = $('
')
+ var headerCell = $('
')
var prop
+ table.append(row.clone().append(headerCell.clone().text(title)))
for (prop in tags) {
if (Object.prototype.hasOwnProperty.call(tags, prop)) {
+ if (typeof tags[prop] === 'object') {
+ displayTagData(node, tags[prop], prop)
+ continue
+ }
table.append(
row
.clone()
@@ -44,7 +56,7 @@ $(function() {
)
}
}
- node.show()
+ node.append(table).show()
}
/**
@@ -56,11 +68,15 @@ $(function() {
*/
function displayThumbnailImage(node, thumbnail, options) {
if (thumbnail) {
- thumbNode.empty()
+ var link = $('
')
+ .attr('href', loadImage.createObjectURL(thumbnail))
+ .attr('download', 'thumbnail.jpg')
+ .appendTo(node)
loadImage(
thumbnail,
- function(img) {
- node.append(img).show()
+ function (img) {
+ link.append(img)
+ node.show()
},
options
)
@@ -68,57 +84,79 @@ $(function() {
}
/**
- * Displays meta data
+ * Displays metadata
*
- * @param {object} [data] Meta data object
+ * @param {object} [data] Metadata object
*/
function displayMetaData(data) {
if (!data) return
+ metaNode.data(data)
var exif = data.exif
var iptc = data.iptc
if (exif) {
- displayThumbnailImage(thumbNode, exif.get('Thumbnail'), {
- orientation: exif.get('Orientation')
- })
- displayTagData(exifNode, exif.getAll())
+ var thumbnail = exif.get('Thumbnail')
+ if (thumbnail) {
+ displayThumbnailImage(thumbNode, thumbnail.get('Blob'), {
+ orientation: exif.get('Orientation')
+ })
+ }
+ displayTagData(metaNode, exif.getAll(), 'TIFF')
}
if (iptc) {
- displayTagData(iptcNode, iptc.getAll())
+ displayTagData(metaNode, iptc.getAll(), 'IPTC')
}
}
+ /**
+ * Removes meta data from the page
+ */
+ function removeMetaData() {
+ metaNode.hide().removeData().find('table').remove()
+ thumbNode.hide().empty()
+ }
+
/**
* Updates the results view
*
* @param {*} img Image or canvas element
- * @param {object} [data] Meta data object
+ * @param {object} [data] Metadata object
+ * @param {boolean} [keepMetaData] Keep meta data if true
*/
- function updateResults(img, data) {
- var fileName = currentFile.name
- var href = currentFile.url || img.src
- var dataURLStart
- var content
- if (!(img.src || img instanceof HTMLCanvasElement)) {
- content = $('
Loading image file failed ')
- } else {
- if (!href) {
- href = img.toDataURL(currentFile.type)
- // Check if file type is supported for the dataURL export:
- dataURLStart = 'data:' + currentFile.type
- if (href.slice(0, dataURLStart.length) !== dataURLStart) {
- fileName = fileName.replace(/\.\w+$/, '.png')
- }
+ function updateResults(img, data, keepMetaData) {
+ var isCanvas = window.HTMLCanvasElement && img instanceof HTMLCanvasElement
+ if (!keepMetaData) {
+ removeMetaData()
+ if (data) {
+ displayMetaData(data)
}
- content = $('
')
- .append(img)
- .attr('download', fileName)
- .attr('href', href)
+ if (isCanvas) {
+ actionsNode.show()
+ } else {
+ actionsNode.hide()
+ }
+ }
+ if (!(isCanvas || img.src)) {
+ resultNode
+ .children()
+ .replaceWith($('Loading image file failed '))
+ return
}
- result.children().replaceWith(content)
- if (img.getContext) {
- actionsNode.show()
+ var content = $(' ').append(img)
+ resultNode.children().replaceWith(content)
+ if (data.imageHead) {
+ if (data.exif) {
+ // Reset Exif Orientation data:
+ loadImage.writeExifData(data.imageHead, data, 'Orientation', 1)
+ }
+ img.toBlob(function (blob) {
+ if (!blob) return
+ loadImage.replaceHead(blob, data.imageHead, function (newBlob) {
+ content
+ .attr('href', loadImage.createObjectURL(newBlob))
+ .attr('download', 'image.jpg')
+ })
+ }, 'image/jpeg')
}
- displayMetaData(data)
}
/**
@@ -128,17 +166,17 @@ $(function() {
*/
function displayImage(file) {
var options = {
- maxWidth: result.width(),
+ maxWidth: resultNode.width(),
canvas: true,
pixelRatio: window.devicePixelRatio,
downsamplingRatio: 0.5,
- orientation: true
+ orientation: Number(orientationNode.val()) || true,
+ imageSmoothingEnabled: imageSmoothingNode.is(':checked'),
+ meta: true
}
- exifNode.hide()
- iptcNode.hide()
- thumbNode.hide()
if (!loadImage(file, updateResults, options)) {
- result
+ removeMetaData()
+ resultNode
.children()
.replaceWith(
$(
@@ -163,7 +201,6 @@ $(function() {
if (!file) {
return
}
- currentFile = file
displayImage(file)
}
@@ -172,71 +209,84 @@ $(function() {
*/
function urlChangeHandler() {
var url = $(this).val()
- if (!url || (currentFile && currentFile.url === url)) return
- currentFile = {
- name: url.replace(/^.*\//g, ''),
- url: url
- }
- displayImage(url)
+ if (url) displayImage(url)
}
- // Hide URL/FileReader API requirement message in capable browsers:
+ // Show the URL/FileReader API requirement message if not supported:
if (
window.createObjectURL ||
window.URL ||
window.webkitURL ||
window.FileReader
) {
- result.children().hide()
+ resultNode.children().hide()
+ } else {
+ resultNode.children().show()
}
$(document)
- .on('dragover', function(e) {
+ .on('dragover', function (e) {
e.preventDefault()
- var originalEvent = event.originalEvent
- if (originalEvent) originalEvent.dataTransfer.dropEffect = 'copy'
+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy'
})
.on('drop', fileChangeHandler)
- $('#file-input').on('change', fileChangeHandler)
+ fileInputNode.on('change', fileChangeHandler)
+
+ urlNode.on('change paste input', urlChangeHandler)
- $('#url').on('change paste input', urlChangeHandler)
+ orientationNode.on('change', function () {
+ var img = resultNode.find('img, canvas')[0]
+ if (img) {
+ updateResults(
+ loadImage.scale(img, {
+ maxWidth: resultNode.width() * (window.devicePixelRatio || 1),
+ pixelRatio: window.devicePixelRatio,
+ orientation: Number(orientationNode.val()) || true,
+ imageSmoothingEnabled: imageSmoothingNode.is(':checked')
+ }),
+ metaNode.data(),
+ true
+ )
+ }
+ })
- $('#edit').on('click', function(event) {
+ editNode.on('click', function (event) {
event.preventDefault()
- var imgNode = result.find('img, canvas')
+ var imgNode = resultNode.find('img, canvas')
var img = imgNode[0]
var pixelRatio = window.devicePixelRatio || 1
+ var margin = img.width / pixelRatio >= 140 ? 40 : 0
imgNode
// eslint-disable-next-line new-cap
.Jcrop(
{
setSelect: [
- 40,
- 40,
- img.width / pixelRatio - 40,
- img.height / pixelRatio - 40
+ margin,
+ margin,
+ img.width / pixelRatio - margin,
+ img.height / pixelRatio - margin
],
- onSelect: function(coords) {
+ onSelect: function (coords) {
coordinates = coords
},
- onRelease: function() {
+ onRelease: function () {
coordinates = null
}
},
- function() {
+ function () {
jcropAPI = this
}
)
.parent()
- .on('click', function(event) {
+ .on('click', function (event) {
event.preventDefault()
})
})
- $('#crop').on('click', function(event) {
+ cropNode.on('click', function (event) {
event.preventDefault()
- var img = result.find('img, canvas')[0]
+ var img = resultNode.find('img, canvas')[0]
var pixelRatio = window.devicePixelRatio || 1
if (img && coordinates) {
updateResults(
@@ -245,18 +295,23 @@ $(function() {
top: coordinates.y * pixelRatio,
sourceWidth: coordinates.w * pixelRatio,
sourceHeight: coordinates.h * pixelRatio,
- minWidth: result.width(),
- maxWidth: result.width(),
+ maxWidth: resultNode.width() * pixelRatio,
+ contain: true,
pixelRatio: pixelRatio,
- downsamplingRatio: 0.5
- })
+ imageSmoothingEnabled: imageSmoothingNode.is(':checked')
+ }),
+ metaNode.data(),
+ true
)
coordinates = null
}
})
- $('#cancel').on('click', function(event) {
+ cancelNode.on('click', function (event) {
event.preventDefault()
- if (jcropAPI) jcropAPI.release()
+ if (jcropAPI) {
+ jcropAPI.release()
+ jcropAPI.disable()
+ }
})
})
diff --git a/js/load-image-exif-map.js b/js/load-image-exif-map.js
index ec23462..d9ce3a8 100644
--- a/js/load-image-exif-map.js
+++ b/js/load-image-exif-map.js
@@ -14,7 +14,7 @@
/* global define, module, require */
-;(function(factory) {
+;(function (factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
@@ -25,18 +25,17 @@
// Browser globals:
factory(window.loadImage)
}
-})(function(loadImage) {
+})(function (loadImage) {
'use strict'
- loadImage.ExifMap.prototype.tags = {
+ var ExifMapProto = loadImage.ExifMap.prototype
+
+ ExifMapProto.tags = {
// =================
// TIFF tags (IFD0):
// =================
0x0100: 'ImageWidth',
0x0101: 'ImageHeight',
- 0x8769: 'ExifIFDPointer',
- 0x8825: 'GPSInfoIFDPointer',
- 0xa005: 'InteroperabilityIFDPointer',
0x0102: 'BitsPerSample',
0x0103: 'Compression',
0x0106: 'PhotometricInterpretation',
@@ -65,116 +64,126 @@
0x0131: 'Software',
0x013b: 'Artist',
0x8298: 'Copyright',
- // ==================
- // Exif Sub IFD tags:
- // ==================
- 0x9000: 'ExifVersion', // EXIF version
- 0xa000: 'FlashpixVersion', // Flashpix format version
- 0xa001: 'ColorSpace', // Color space information tag
- 0xa002: 'PixelXDimension', // Valid width of meaningful image
- 0xa003: 'PixelYDimension', // Valid height of meaningful image
- 0xa500: 'Gamma',
- 0x9101: 'ComponentsConfiguration', // Information about channels
- 0x9102: 'CompressedBitsPerPixel', // Compressed bits per pixel
- 0x927c: 'MakerNote', // Any desired information written by the manufacturer
- 0x9286: 'UserComment', // Comments by user
- 0xa004: 'RelatedSoundFile', // Name of related sound file
- 0x9003: 'DateTimeOriginal', // Date and time when the original image was generated
- 0x9004: 'DateTimeDigitized', // Date and time when the image was stored digitally
- 0x9290: 'SubSecTime', // Fractions of seconds for DateTime
- 0x9291: 'SubSecTimeOriginal', // Fractions of seconds for DateTimeOriginal
- 0x9292: 'SubSecTimeDigitized', // Fractions of seconds for DateTimeDigitized
- 0x829a: 'ExposureTime', // Exposure time (in seconds)
- 0x829d: 'FNumber',
- 0x8822: 'ExposureProgram', // Exposure program
- 0x8824: 'SpectralSensitivity', // Spectral sensitivity
- 0x8827: 'PhotographicSensitivity', // EXIF 2.3, ISOSpeedRatings in EXIF 2.2
- 0x8828: 'OECF', // Optoelectric conversion factor
- 0x8830: 'SensitivityType',
- 0x8831: 'StandardOutputSensitivity',
- 0x8832: 'RecommendedExposureIndex',
- 0x8833: 'ISOSpeed',
- 0x8834: 'ISOSpeedLatitudeyyy',
- 0x8835: 'ISOSpeedLatitudezzz',
- 0x9201: 'ShutterSpeedValue', // Shutter speed
- 0x9202: 'ApertureValue', // Lens aperture
- 0x9203: 'BrightnessValue', // Value of brightness
- 0x9204: 'ExposureBias', // Exposure bias
- 0x9205: 'MaxApertureValue', // Smallest F number of lens
- 0x9206: 'SubjectDistance', // Distance to subject in meters
- 0x9207: 'MeteringMode', // Metering mode
- 0x9208: 'LightSource', // Kind of light source
- 0x9209: 'Flash', // Flash status
- 0x9214: 'SubjectArea', // Location and area of main subject
- 0x920a: 'FocalLength', // Focal length of the lens in mm
- 0xa20b: 'FlashEnergy', // Strobe energy in BCPS
- 0xa20c: 'SpatialFrequencyResponse',
- 0xa20e: 'FocalPlaneXResolution', // Number of pixels in width direction per FPRUnit
- 0xa20f: 'FocalPlaneYResolution', // Number of pixels in height direction per FPRUnit
- 0xa210: 'FocalPlaneResolutionUnit', // Unit for measuring the focal plane resolution
- 0xa214: 'SubjectLocation', // Location of subject in image
- 0xa215: 'ExposureIndex', // Exposure index selected on camera
- 0xa217: 'SensingMethod', // Image sensor type
- 0xa300: 'FileSource', // Image source (3 == DSC)
- 0xa301: 'SceneType', // Scene type (1 == directly photographed)
- 0xa302: 'CFAPattern', // Color filter array geometric pattern
- 0xa401: 'CustomRendered', // Special processing
- 0xa402: 'ExposureMode', // Exposure mode
- 0xa403: 'WhiteBalance', // 1 = auto white balance, 2 = manual
- 0xa404: 'DigitalZoomRatio', // Digital zoom ratio
- 0xa405: 'FocalLengthIn35mmFilm',
- 0xa406: 'SceneCaptureType', // Type of scene
- 0xa407: 'GainControl', // Degree of overall image gain adjustment
- 0xa408: 'Contrast', // Direction of contrast processing applied by camera
- 0xa409: 'Saturation', // Direction of saturation processing applied by camera
- 0xa40a: 'Sharpness', // Direction of sharpness processing applied by camera
- 0xa40b: 'DeviceSettingDescription',
- 0xa40c: 'SubjectDistanceRange', // Distance to subject
- 0xa420: 'ImageUniqueID', // Identifier assigned uniquely to each image
- 0xa430: 'CameraOwnerName',
- 0xa431: 'BodySerialNumber',
- 0xa432: 'LensSpecification',
- 0xa433: 'LensMake',
- 0xa434: 'LensModel',
- 0xa435: 'LensSerialNumber',
- // ==============
- // GPS Info tags:
- // ==============
- 0x0000: 'GPSVersionID',
- 0x0001: 'GPSLatitudeRef',
- 0x0002: 'GPSLatitude',
- 0x0003: 'GPSLongitudeRef',
- 0x0004: 'GPSLongitude',
- 0x0005: 'GPSAltitudeRef',
- 0x0006: 'GPSAltitude',
- 0x0007: 'GPSTimeStamp',
- 0x0008: 'GPSSatellites',
- 0x0009: 'GPSStatus',
- 0x000a: 'GPSMeasureMode',
- 0x000b: 'GPSDOP',
- 0x000c: 'GPSSpeedRef',
- 0x000d: 'GPSSpeed',
- 0x000e: 'GPSTrackRef',
- 0x000f: 'GPSTrack',
- 0x0010: 'GPSImgDirectionRef',
- 0x0011: 'GPSImgDirection',
- 0x0012: 'GPSMapDatum',
- 0x0013: 'GPSDestLatitudeRef',
- 0x0014: 'GPSDestLatitude',
- 0x0015: 'GPSDestLongitudeRef',
- 0x0016: 'GPSDestLongitude',
- 0x0017: 'GPSDestBearingRef',
- 0x0018: 'GPSDestBearing',
- 0x0019: 'GPSDestDistanceRef',
- 0x001a: 'GPSDestDistance',
- 0x001b: 'GPSProcessingMethod',
- 0x001c: 'GPSAreaInformation',
- 0x001d: 'GPSDateStamp',
- 0x001e: 'GPSDifferential',
- 0x001f: 'GPSHPositioningError'
+ 0x8769: {
+ // ExifIFDPointer
+ 0x9000: 'ExifVersion', // EXIF version
+ 0xa000: 'FlashpixVersion', // Flashpix format version
+ 0xa001: 'ColorSpace', // Color space information tag
+ 0xa002: 'PixelXDimension', // Valid width of meaningful image
+ 0xa003: 'PixelYDimension', // Valid height of meaningful image
+ 0xa500: 'Gamma',
+ 0x9101: 'ComponentsConfiguration', // Information about channels
+ 0x9102: 'CompressedBitsPerPixel', // Compressed bits per pixel
+ 0x927c: 'MakerNote', // Any desired information written by the manufacturer
+ 0x9286: 'UserComment', // Comments by user
+ 0xa004: 'RelatedSoundFile', // Name of related sound file
+ 0x9003: 'DateTimeOriginal', // Date and time when the original image was generated
+ 0x9004: 'DateTimeDigitized', // Date and time when the image was stored digitally
+ 0x9010: 'OffsetTime', // Time zone when the image file was last changed
+ 0x9011: 'OffsetTimeOriginal', // Time zone when the image was stored digitally
+ 0x9012: 'OffsetTimeDigitized', // Time zone when the image was stored digitally
+ 0x9290: 'SubSecTime', // Fractions of seconds for DateTime
+ 0x9291: 'SubSecTimeOriginal', // Fractions of seconds for DateTimeOriginal
+ 0x9292: 'SubSecTimeDigitized', // Fractions of seconds for DateTimeDigitized
+ 0x829a: 'ExposureTime', // Exposure time (in seconds)
+ 0x829d: 'FNumber',
+ 0x8822: 'ExposureProgram', // Exposure program
+ 0x8824: 'SpectralSensitivity', // Spectral sensitivity
+ 0x8827: 'PhotographicSensitivity', // EXIF 2.3, ISOSpeedRatings in EXIF 2.2
+ 0x8828: 'OECF', // Optoelectric conversion factor
+ 0x8830: 'SensitivityType',
+ 0x8831: 'StandardOutputSensitivity',
+ 0x8832: 'RecommendedExposureIndex',
+ 0x8833: 'ISOSpeed',
+ 0x8834: 'ISOSpeedLatitudeyyy',
+ 0x8835: 'ISOSpeedLatitudezzz',
+ 0x9201: 'ShutterSpeedValue', // Shutter speed
+ 0x9202: 'ApertureValue', // Lens aperture
+ 0x9203: 'BrightnessValue', // Value of brightness
+ 0x9204: 'ExposureBias', // Exposure bias
+ 0x9205: 'MaxApertureValue', // Smallest F number of lens
+ 0x9206: 'SubjectDistance', // Distance to subject in meters
+ 0x9207: 'MeteringMode', // Metering mode
+ 0x9208: 'LightSource', // Kind of light source
+ 0x9209: 'Flash', // Flash status
+ 0x9214: 'SubjectArea', // Location and area of main subject
+ 0x920a: 'FocalLength', // Focal length of the lens in mm
+ 0xa20b: 'FlashEnergy', // Strobe energy in BCPS
+ 0xa20c: 'SpatialFrequencyResponse',
+ 0xa20e: 'FocalPlaneXResolution', // Number of pixels in width direction per FPRUnit
+ 0xa20f: 'FocalPlaneYResolution', // Number of pixels in height direction per FPRUnit
+ 0xa210: 'FocalPlaneResolutionUnit', // Unit for measuring the focal plane resolution
+ 0xa214: 'SubjectLocation', // Location of subject in image
+ 0xa215: 'ExposureIndex', // Exposure index selected on camera
+ 0xa217: 'SensingMethod', // Image sensor type
+ 0xa300: 'FileSource', // Image source (3 == DSC)
+ 0xa301: 'SceneType', // Scene type (1 == directly photographed)
+ 0xa302: 'CFAPattern', // Color filter array geometric pattern
+ 0xa401: 'CustomRendered', // Special processing
+ 0xa402: 'ExposureMode', // Exposure mode
+ 0xa403: 'WhiteBalance', // 1 = auto white balance, 2 = manual
+ 0xa404: 'DigitalZoomRatio', // Digital zoom ratio
+ 0xa405: 'FocalLengthIn35mmFilm',
+ 0xa406: 'SceneCaptureType', // Type of scene
+ 0xa407: 'GainControl', // Degree of overall image gain adjustment
+ 0xa408: 'Contrast', // Direction of contrast processing applied by camera
+ 0xa409: 'Saturation', // Direction of saturation processing applied by camera
+ 0xa40a: 'Sharpness', // Direction of sharpness processing applied by camera
+ 0xa40b: 'DeviceSettingDescription',
+ 0xa40c: 'SubjectDistanceRange', // Distance to subject
+ 0xa420: 'ImageUniqueID', // Identifier assigned uniquely to each image
+ 0xa430: 'CameraOwnerName',
+ 0xa431: 'BodySerialNumber',
+ 0xa432: 'LensSpecification',
+ 0xa433: 'LensMake',
+ 0xa434: 'LensModel',
+ 0xa435: 'LensSerialNumber'
+ },
+ 0x8825: {
+ // GPSInfoIFDPointer
+ 0x0000: 'GPSVersionID',
+ 0x0001: 'GPSLatitudeRef',
+ 0x0002: 'GPSLatitude',
+ 0x0003: 'GPSLongitudeRef',
+ 0x0004: 'GPSLongitude',
+ 0x0005: 'GPSAltitudeRef',
+ 0x0006: 'GPSAltitude',
+ 0x0007: 'GPSTimeStamp',
+ 0x0008: 'GPSSatellites',
+ 0x0009: 'GPSStatus',
+ 0x000a: 'GPSMeasureMode',
+ 0x000b: 'GPSDOP',
+ 0x000c: 'GPSSpeedRef',
+ 0x000d: 'GPSSpeed',
+ 0x000e: 'GPSTrackRef',
+ 0x000f: 'GPSTrack',
+ 0x0010: 'GPSImgDirectionRef',
+ 0x0011: 'GPSImgDirection',
+ 0x0012: 'GPSMapDatum',
+ 0x0013: 'GPSDestLatitudeRef',
+ 0x0014: 'GPSDestLatitude',
+ 0x0015: 'GPSDestLongitudeRef',
+ 0x0016: 'GPSDestLongitude',
+ 0x0017: 'GPSDestBearingRef',
+ 0x0018: 'GPSDestBearing',
+ 0x0019: 'GPSDestDistanceRef',
+ 0x001a: 'GPSDestDistance',
+ 0x001b: 'GPSProcessingMethod',
+ 0x001c: 'GPSAreaInformation',
+ 0x001d: 'GPSDateStamp',
+ 0x001e: 'GPSDifferential',
+ 0x001f: 'GPSHPositioningError'
+ },
+ 0xa005: {
+ // InteroperabilityIFDPointer
+ 0x0001: 'InteroperabilityIndex'
+ }
}
- loadImage.ExifMap.prototype.stringValues = {
+ // IFD1 directory can contain any IFD0 tags:
+ ExifMapProto.tags.ifd1 = ExifMapProto.tags
+
+ ExifMapProto.stringValues = {
ExposureProgram: {
0: 'Undefined',
1: 'Manual',
@@ -237,11 +246,15 @@
0x0045: 'Flash fired, red-eye reduction mode, return light not detected',
0x0047: 'Flash fired, red-eye reduction mode, return light detected',
0x0049: 'Flash fired, compulsory flash mode, red-eye reduction mode',
- 0x004d: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected',
- 0x004f: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected',
+ 0x004d:
+ 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected',
+ 0x004f:
+ 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected',
0x0059: 'Flash fired, auto mode, red-eye reduction mode',
- 0x005d: 'Flash fired, auto mode, return light not detected, red-eye reduction mode',
- 0x005f: 'Flash fired, auto mode, return light detected, red-eye reduction mode'
+ 0x005d:
+ 'Flash fired, auto mode, return light not detected, red-eye reduction mode',
+ 0x005f:
+ 'Flash fired, auto mode, return light detected, red-eye reduction mode'
},
SensingMethod: {
1: 'Undefined',
@@ -310,20 +323,20 @@
6: 'B'
},
Orientation: {
- 1: 'top-left',
- 2: 'top-right',
- 3: 'bottom-right',
- 4: 'bottom-left',
- 5: 'left-top',
- 6: 'right-top',
- 7: 'right-bottom',
- 8: 'left-bottom'
+ 1: 'Original',
+ 2: 'Horizontal flip',
+ 3: 'Rotate 180° CCW',
+ 4: 'Vertical flip',
+ 5: 'Vertical flip + Rotate 90° CW',
+ 6: 'Rotate 90° CW',
+ 7: 'Horizontal flip + Rotate 90° CW',
+ 8: 'Rotate 90° CCW'
}
}
- loadImage.ExifMap.prototype.getText = function(id) {
- var value = this.get(id)
- switch (id) {
+ ExifMapProto.getText = function (name) {
+ var value = this.get(name)
+ switch (name) {
case 'LightSource':
case 'Flash':
case 'MeteringMode':
@@ -340,7 +353,7 @@
case 'SubjectDistanceRange':
case 'FileSource':
case 'Orientation':
- return this.stringValues[id][value]
+ return this.stringValues[name][value]
case 'ExifVersion':
case 'FlashpixVersion':
if (!value) return
@@ -348,10 +361,10 @@
case 'ComponentsConfiguration':
if (!value) return
return (
- this.stringValues[id][value[0]] +
- this.stringValues[id][value[1]] +
- this.stringValues[id][value[2]] +
- this.stringValues[id][value[3]]
+ this.stringValues[name][value[0]] +
+ this.stringValues[name][value[1]] +
+ this.stringValues[name][value[2]] +
+ this.stringValues[name][value[3]]
)
case 'GPSVersionID':
if (!value) return
@@ -359,30 +372,53 @@
}
return String(value)
}
- ;(function(exifMapPrototype) {
- var tags = exifMapPrototype.tags
- var map = exifMapPrototype.map
- var prop
- // Map the tag names to tags:
- for (prop in tags) {
- if (Object.prototype.hasOwnProperty.call(tags, prop)) {
- map[tags[prop]] = prop
- }
- }
- })(loadImage.ExifMap.prototype)
- loadImage.ExifMap.prototype.getAll = function() {
+ ExifMapProto.getAll = function () {
var map = {}
var prop
- var id
+ var obj
+ var name
for (prop in this) {
if (Object.prototype.hasOwnProperty.call(this, prop)) {
- id = this.tags[prop]
- if (id) {
- map[id] = this.getText(id)
+ obj = this[prop]
+ if (obj && obj.getAll) {
+ map[this.ifds[prop].name] = obj.getAll()
+ } else {
+ name = this.tags[prop]
+ if (name) map[name] = this.getText(name)
}
}
}
return map
}
+
+ ExifMapProto.getName = function (tagCode) {
+ var name = this.tags[tagCode]
+ if (typeof name === 'object') return this.ifds[tagCode].name
+ return name
+ }
+
+ // Extend the map of tag names to tag codes:
+ ;(function () {
+ var tags = ExifMapProto.tags
+ var prop
+ var ifd
+ var subTags
+ // Map the tag names to tags:
+ for (prop in tags) {
+ if (Object.prototype.hasOwnProperty.call(tags, prop)) {
+ ifd = ExifMapProto.ifds[prop]
+ if (ifd) {
+ subTags = tags[prop]
+ for (prop in subTags) {
+ if (Object.prototype.hasOwnProperty.call(subTags, prop)) {
+ ifd.map[subTags[prop]] = Number(prop)
+ }
+ }
+ } else {
+ ExifMapProto.map[tags[prop]] = Number(prop)
+ }
+ }
+ }
+ })()
})
diff --git a/js/load-image-exif.js b/js/load-image-exif.js
index 3e9701f..7428eef 100644
--- a/js/load-image-exif.js
+++ b/js/load-image-exif.js
@@ -9,11 +9,11 @@
* https://opensource.org/licenses/MIT
*/
-/* global define, module, require */
+/* global define, module, require, DataView */
/* eslint-disable no-console */
-;(function(factory) {
+;(function (factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
@@ -24,42 +24,86 @@
// Browser globals:
factory(window.loadImage)
}
-})(function(loadImage) {
+})(function (loadImage) {
'use strict'
- loadImage.ExifMap = function() {
- return this
+ /**
+ * Exif tag map
+ *
+ * @name ExifMap
+ * @class
+ * @param {number|string} tagCode IFD tag code
+ */
+ function ExifMap(tagCode) {
+ if (tagCode) {
+ Object.defineProperty(this, 'map', {
+ value: this.ifds[tagCode].map
+ })
+ Object.defineProperty(this, 'tags', {
+ value: (this.tags && this.tags[tagCode]) || {}
+ })
+ }
+ }
+
+ ExifMap.prototype.map = {
+ Orientation: 0x0112,
+ Thumbnail: 'ifd1',
+ Blob: 0x0201, // Alias for JPEGInterchangeFormat
+ Exif: 0x8769,
+ GPSInfo: 0x8825,
+ Interoperability: 0xa005
}
- loadImage.ExifMap.prototype.map = {
- Orientation: 0x0112
+ ExifMap.prototype.ifds = {
+ ifd1: { name: 'Thumbnail', map: ExifMap.prototype.map },
+ 0x8769: { name: 'Exif', map: {} },
+ 0x8825: { name: 'GPSInfo', map: {} },
+ 0xa005: { name: 'Interoperability', map: {} }
}
- loadImage.ExifMap.prototype.get = function(id) {
+ /**
+ * Retrieves exif tag value
+ *
+ * @param {number|string} id Exif tag code or name
+ * @returns {object} Exif tag value
+ */
+ ExifMap.prototype.get = function (id) {
return this[id] || this[this.map[id]]
}
- loadImage.getExifThumbnail = function(dataView, offset, length) {
- if (!length || offset + length > dataView.byteLength) {
+ /**
+ * Returns the Exif Thumbnail data as Blob.
+ *
+ * @param {DataView} dataView Data view interface
+ * @param {number} offset Thumbnail data offset
+ * @param {number} length Thumbnail data length
+ * @returns {undefined|Blob} Returns the Thumbnail Blob or undefined
+ */
+ function getExifThumbnail(dataView, offset, length) {
+ if (!length) return
+ if (offset + length > dataView.byteLength) {
console.log('Invalid Exif data: Invalid thumbnail data.')
return
}
- return loadImage.createObjectURL(
- new Blob([dataView.buffer.slice(offset, offset + length)])
+ return new Blob(
+ [loadImage.bufferSlice.call(dataView.buffer, offset, offset + length)],
+ {
+ type: 'image/jpeg'
+ }
)
}
- loadImage.exifTagTypes = {
+ var ExifTagTypes = {
// byte, 8-bit unsigned int:
1: {
- getValue: function(dataView, dataOffset) {
+ getValue: function (dataView, dataOffset) {
return dataView.getUint8(dataOffset)
},
size: 1
},
// ascii, 8-bit byte:
2: {
- getValue: function(dataView, dataOffset) {
+ getValue: function (dataView, dataOffset) {
return String.fromCharCode(dataView.getUint8(dataOffset))
},
size: 1,
@@ -67,21 +111,21 @@
},
// short, 16 bit int:
3: {
- getValue: function(dataView, dataOffset, littleEndian) {
+ getValue: function (dataView, dataOffset, littleEndian) {
return dataView.getUint16(dataOffset, littleEndian)
},
size: 2
},
// long, 32 bit int:
4: {
- getValue: function(dataView, dataOffset, littleEndian) {
+ getValue: function (dataView, dataOffset, littleEndian) {
return dataView.getUint32(dataOffset, littleEndian)
},
size: 4
},
// rational = two long values, first is numerator, second is denominator:
5: {
- getValue: function(dataView, dataOffset, littleEndian) {
+ getValue: function (dataView, dataOffset, littleEndian) {
return (
dataView.getUint32(dataOffset, littleEndian) /
dataView.getUint32(dataOffset + 4, littleEndian)
@@ -91,14 +135,14 @@
},
// slong, 32 bit signed int:
9: {
- getValue: function(dataView, dataOffset, littleEndian) {
+ getValue: function (dataView, dataOffset, littleEndian) {
return dataView.getInt32(dataOffset, littleEndian)
},
size: 4
},
// srational, two slongs, first is numerator, second is denominator:
10: {
- getValue: function(dataView, dataOffset, littleEndian) {
+ getValue: function (dataView, dataOffset, littleEndian) {
return (
dataView.getInt32(dataOffset, littleEndian) /
dataView.getInt32(dataOffset + 4, littleEndian)
@@ -108,9 +152,20 @@
}
}
// undefined, 8-bit byte, value depending on field:
- loadImage.exifTagTypes[7] = loadImage.exifTagTypes[1]
+ ExifTagTypes[7] = ExifTagTypes[1]
- loadImage.getExifValue = function(
+ /**
+ * Returns Exif tag value.
+ *
+ * @param {DataView} dataView Data view interface
+ * @param {number} tiffOffset TIFF offset
+ * @param {number} offset Tag offset
+ * @param {number} type Tag type
+ * @param {number} length Tag length
+ * @param {boolean} littleEndian Little endian encoding
+ * @returns {object} Tag value
+ */
+ function getExifValue(
dataView,
tiffOffset,
offset,
@@ -118,7 +173,7 @@
length,
littleEndian
) {
- var tagType = loadImage.exifTagTypes[type]
+ var tagType = ExifTagTypes[type]
var tagSize
var dataOffset
var values
@@ -167,32 +222,45 @@
return values
}
- loadImage.parseExifTag = function(
- dataView,
- tiffOffset,
- offset,
- littleEndian,
- data
- ) {
- var tag = dataView.getUint16(offset, littleEndian)
- data.exif[tag] = loadImage.getExifValue(
- dataView,
- tiffOffset,
- offset,
- dataView.getUint16(offset + 2, littleEndian), // tag type
- dataView.getUint32(offset + 4, littleEndian), // tag length
- littleEndian
+ /**
+ * Determines if the given tag should be included.
+ *
+ * @param {object} includeTags Map of tags to include
+ * @param {object} excludeTags Map of tags to exclude
+ * @param {number|string} tagCode Tag code to check
+ * @returns {boolean} True if the tag should be included
+ */
+ function shouldIncludeTag(includeTags, excludeTags, tagCode) {
+ return (
+ (!includeTags || includeTags[tagCode]) &&
+ (!excludeTags || excludeTags[tagCode] !== true)
)
}
- loadImage.parseExifTags = function(
+ /**
+ * Parses Exif tags.
+ *
+ * @param {DataView} dataView Data view interface
+ * @param {number} tiffOffset TIFF offset
+ * @param {number} dirOffset Directory offset
+ * @param {boolean} littleEndian Little endian encoding
+ * @param {ExifMap} tags Map to store parsed exif tags
+ * @param {ExifMap} tagOffsets Map to store parsed exif tag offsets
+ * @param {object} includeTags Map of tags to include
+ * @param {object} excludeTags Map of tags to exclude
+ * @returns {number} Next directory offset
+ */
+ function parseExifTags(
dataView,
tiffOffset,
dirOffset,
littleEndian,
- data
+ tags,
+ tagOffsets,
+ includeTags,
+ excludeTags
) {
- var tagsNumber, dirEndOffset, i
+ var tagsNumber, dirEndOffset, i, tagOffset, tagNumber, tagValue
if (dirOffset + 6 > dataView.byteLength) {
console.log('Invalid Exif data: Invalid directory offset.')
return
@@ -204,26 +272,80 @@
return
}
for (i = 0; i < tagsNumber; i += 1) {
- this.parseExifTag(
+ tagOffset = dirOffset + 2 + 12 * i
+ tagNumber = dataView.getUint16(tagOffset, littleEndian)
+ if (!shouldIncludeTag(includeTags, excludeTags, tagNumber)) continue
+ tagValue = getExifValue(
dataView,
tiffOffset,
- dirOffset + 2 + 12 * i, // tag offset
- littleEndian,
- data
+ tagOffset,
+ dataView.getUint16(tagOffset + 2, littleEndian), // tag type
+ dataView.getUint32(tagOffset + 4, littleEndian), // tag length
+ littleEndian
)
+ tags[tagNumber] = tagValue
+ if (tagOffsets) {
+ tagOffsets[tagNumber] = tagOffset
+ }
}
// Return the offset to the next directory:
return dataView.getUint32(dirEndOffset, littleEndian)
}
- loadImage.parseExifData = function(dataView, offset, length, data, options) {
+ /**
+ * Parses tags in a given IFD (Image File Directory).
+ *
+ * @param {object} data Data object to store exif tags and offsets
+ * @param {number|string} tagCode IFD tag code
+ * @param {DataView} dataView Data view interface
+ * @param {number} tiffOffset TIFF offset
+ * @param {boolean} littleEndian Little endian encoding
+ * @param {object} includeTags Map of tags to include
+ * @param {object} excludeTags Map of tags to exclude
+ */
+ function parseExifIFD(
+ data,
+ tagCode,
+ dataView,
+ tiffOffset,
+ littleEndian,
+ includeTags,
+ excludeTags
+ ) {
+ var dirOffset = data.exif[tagCode]
+ if (dirOffset) {
+ data.exif[tagCode] = new ExifMap(tagCode)
+ if (data.exifOffsets) {
+ data.exifOffsets[tagCode] = new ExifMap(tagCode)
+ }
+ parseExifTags(
+ dataView,
+ tiffOffset,
+ tiffOffset + dirOffset,
+ littleEndian,
+ data.exif[tagCode],
+ data.exifOffsets && data.exifOffsets[tagCode],
+ includeTags && includeTags[tagCode],
+ excludeTags && excludeTags[tagCode]
+ )
+ }
+ }
+
+ loadImage.parseExifData = function (dataView, offset, length, data, options) {
if (options.disableExif) {
return
}
+ var includeTags = options.includeExifTags
+ var excludeTags = options.excludeExifTags || {
+ 0x8769: {
+ // ExifIFDPointer
+ 0x927c: true // MakerNote
+ }
+ }
var tiffOffset = offset + 10
var littleEndian
var dirOffset
- var thumbnailData
+ var thumbnailIFD
// Check for the ASCII code for "Exif" (0x45786966):
if (dataView.getUint32(offset + 4) !== 0x45786966) {
// No Exif data, might be XMP data instead
@@ -258,65 +380,81 @@
// Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian)
// Create the exif object to store the tags:
- data.exif = new loadImage.ExifMap()
- // Parse the tags of the main image directory and retrieve the
- // offset to the next directory, usually the thumbnail directory:
- dirOffset = loadImage.parseExifTags(
+ data.exif = new ExifMap()
+ if (!options.disableExifOffsets) {
+ data.exifOffsets = new ExifMap()
+ data.exifTiffOffset = tiffOffset
+ data.exifLittleEndian = littleEndian
+ }
+ // Parse the tags of the main image directory (IFD0) and retrieve the
+ // offset to the next directory (IFD1), usually the thumbnail directory:
+ dirOffset = parseExifTags(
dataView,
tiffOffset,
tiffOffset + dirOffset,
littleEndian,
- data
+ data.exif,
+ data.exifOffsets,
+ includeTags,
+ excludeTags
)
- if (dirOffset && !options.disableExifThumbnail) {
- thumbnailData = { exif: {} }
- dirOffset = loadImage.parseExifTags(
- dataView,
- tiffOffset,
- tiffOffset + dirOffset,
- littleEndian,
- thumbnailData
- )
- // Check for JPEG Thumbnail offset:
- if (thumbnailData.exif[0x0201]) {
- data.exif.Thumbnail = loadImage.getExifThumbnail(
- dataView,
- tiffOffset + thumbnailData.exif[0x0201],
- thumbnailData.exif[0x0202] // Thumbnail data length
- )
+ if (dirOffset && shouldIncludeTag(includeTags, excludeTags, 'ifd1')) {
+ data.exif.ifd1 = dirOffset
+ if (data.exifOffsets) {
+ data.exifOffsets.ifd1 = tiffOffset + dirOffset
}
}
- // Check for Exif Sub IFD Pointer:
- if (data.exif[0x8769] && !options.disableExifSub) {
- loadImage.parseExifTags(
+ Object.keys(data.exif.ifds).forEach(function (tagCode) {
+ parseExifIFD(
+ data,
+ tagCode,
dataView,
tiffOffset,
- tiffOffset + data.exif[0x8769], // directory offset
littleEndian,
- data
+ includeTags,
+ excludeTags
)
- }
- // Check for GPS Info IFD Pointer:
- if (data.exif[0x8825] && !options.disableExifGps) {
- loadImage.parseExifTags(
+ })
+ thumbnailIFD = data.exif.ifd1
+ // Check for JPEG Thumbnail offset and data length:
+ if (thumbnailIFD && thumbnailIFD[0x0201]) {
+ thumbnailIFD[0x0201] = getExifThumbnail(
dataView,
- tiffOffset,
- tiffOffset + data.exif[0x8825], // directory offset
- littleEndian,
- data
+ tiffOffset + thumbnailIFD[0x0201],
+ thumbnailIFD[0x0202] // Thumbnail data length
)
}
}
- // Registers the Exif parser for the APP1 JPEG meta data segment:
+ // Registers the Exif parser for the APP1 JPEG metadata segment:
loadImage.metaDataParsers.jpeg[0xffe1].push(loadImage.parseExifData)
+ loadImage.exifWriters = {
+ // Orientation writer:
+ 0x0112: function (buffer, data, value) {
+ var orientationOffset = data.exifOffsets[0x0112]
+ if (!orientationOffset) return buffer
+ var view = new DataView(buffer, orientationOffset + 8, 2)
+ view.setUint16(0, value, data.exifLittleEndian)
+ return buffer
+ }
+ }
+
+ loadImage.writeExifData = function (buffer, data, id, value) {
+ return loadImage.exifWriters[data.exif.map[id]](buffer, data, value)
+ }
+
+ loadImage.ExifMap = ExifMap
+
// Adds the following properties to the parseMetaData callback data:
- // * exif: The exif tags, parsed by the parseExifData method
+ // - exif: The parsed Exif tags
+ // - exifOffsets: The parsed Exif tag offsets
+ // - exifTiffOffset: TIFF header offset (used for offset pointers)
+ // - exifLittleEndian: little endian order if true, big endian if false
// Adds the following options to the parseMetaData method:
- // * disableExif: Disables Exif parsing.
- // * disableExifThumbnail: Disables parsing of the Exif Thumbnail.
- // * disableExifSub: Disables parsing of the Exif Sub IFD.
- // * disableExifGps: Disables parsing of the Exif GPS Info IFD.
+ // - disableExif: Disables Exif parsing when true.
+ // - disableExifOffsets: Disables storing Exif tag offsets when true.
+ // - includeExifTags: A map of Exif tags to include for parsing.
+ // - excludeExifTags: A map of Exif tags to exclude from parsing.
})
diff --git a/js/load-image-fetch.js b/js/load-image-fetch.js
index ab64665..af65797 100644
--- a/js/load-image-fetch.js
+++ b/js/load-image-fetch.js
@@ -9,67 +9,98 @@
* https://opensource.org/licenses/MIT
*/
-/* global define, module, require */
+/* global define, module, require, Promise */
-;(function(factory) {
+;(function (factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
- define(['./load-image', './load-image-meta'], factory)
+ define(['./load-image'], factory)
} else if (typeof module === 'object' && module.exports) {
- factory(require('./load-image'), require('./load-image-meta'))
+ factory(require('./load-image'))
} else {
// Browser globals:
factory(window.loadImage)
}
-})(function(loadImage) {
+})(function (loadImage) {
'use strict'
- if (typeof fetch !== 'undefined' && typeof Request !== 'undefined') {
- loadImage.fetchBlob = function(url, callback, options) {
- if (loadImage.hasMetaOption(options)) {
- fetch(new Request(url, options))
- .then(function(response) {
- return response.blob()
- })
- .then(callback)
- .catch(function(err) {
- console.log(err) // eslint-disable-line no-console
- callback()
- })
- } else {
- callback()
+ var global = loadImage.global
+
+ if (
+ global.fetch &&
+ global.Request &&
+ global.Response &&
+ global.Response.prototype.blob
+ ) {
+ loadImage.fetchBlob = function (url, callback, options) {
+ /**
+ * Fetch response handler.
+ *
+ * @param {Response} response Fetch response
+ * @returns {Blob} Fetched Blob.
+ */
+ function responseHandler(response) {
+ return response.blob()
}
+ if (global.Promise && typeof callback !== 'function') {
+ return fetch(new Request(url, callback)).then(responseHandler)
+ }
+ fetch(new Request(url, options))
+ .then(responseHandler)
+ .then(callback)
+ [
+ // Avoid parsing error in IE<9, where catch is a reserved word.
+ // eslint-disable-next-line dot-notation
+ 'catch'
+ ](function (err) {
+ callback(null, err)
+ })
}
} else if (
- // Check for XHR2 support:
- typeof XMLHttpRequest !== 'undefined' &&
- typeof ProgressEvent !== 'undefined'
+ global.XMLHttpRequest &&
+ // https://xhr.spec.whatwg.org/#the-responsetype-attribute
+ new XMLHttpRequest().responseType === ''
) {
- loadImage.fetchBlob = function(url, callback, options) {
- if (loadImage.hasMetaOption(options)) {
- // eslint-disable-next-line no-param-reassign
- options = options || {}
+ loadImage.fetchBlob = function (url, callback, options) {
+ /**
+ * Promise executor
+ *
+ * @param {Function} resolve Resolution function
+ * @param {Function} reject Rejection function
+ */
+ function executor(resolve, reject) {
+ options = options || {} // eslint-disable-line no-param-reassign
var req = new XMLHttpRequest()
req.open(options.method || 'GET', url)
if (options.headers) {
- Object.keys(options.headers).forEach(function(key) {
+ Object.keys(options.headers).forEach(function (key) {
req.setRequestHeader(key, options.headers[key])
})
}
req.withCredentials = options.credentials === 'include'
req.responseType = 'blob'
- req.onload = function() {
- callback(req.response)
- }
- req.onerror = req.onabort = req.ontimeout = function(e) {
- console.log(e) // eslint-disable-line no-console
- callback()
+ req.onload = function () {
+ resolve(req.response)
}
+ req.onerror =
+ req.onabort =
+ req.ontimeout =
+ function (err) {
+ if (resolve === reject) {
+ // Not using Promises
+ reject(null, err)
+ } else {
+ reject(err)
+ }
+ }
req.send(options.body)
- } else {
- callback()
}
+ if (global.Promise && typeof callback !== 'function') {
+ options = callback // eslint-disable-line no-param-reassign
+ return new Promise(executor)
+ }
+ return executor(callback, callback)
}
}
})
diff --git a/js/load-image-iptc-map.js b/js/load-image-iptc-map.js
index 5ed39de..165d17d 100644
--- a/js/load-image-iptc-map.js
+++ b/js/load-image-iptc-map.js
@@ -6,9 +6,8 @@
* Copyright 2018, Dave Bevan
*
* IPTC tags mapping based on
- * https://github.com/jseidelin/exif-js
* https://iptc.org/standards/photo-metadata
- * http://www.iptc.org/std/IIM/4.1/specification/IIMV4.1.pdf
+ * https://exiftool.org/TagNames/IPTC.html
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
@@ -16,7 +15,7 @@
/* global define, module, require */
-;(function(factory) {
+;(function (factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
@@ -27,103 +26,144 @@
// Browser globals:
factory(window.loadImage)
}
-})(function(loadImage) {
+})(function (loadImage) {
'use strict'
- loadImage.IptcMap.prototype.tags = {
- // ==========
- // IPTC tags:
- // ==========
- 0x03: 'ObjectType',
- 0x04: 'ObjectAttribute',
- 0x05: 'ObjectName',
- 0x07: 'EditStatus',
- 0x08: 'EditorialUpdate',
- 0x0a: 'Urgency',
- 0x0c: 'SubjectRef',
- 0x0f: 'Category',
- 0x14: 'SupplCategory',
- 0x16: 'FixtureID',
- 0x19: 'Keywords',
- 0x1a: 'ContentLocCode',
- 0x1b: 'ContentLocName',
- 0x1e: 'ReleaseDate',
- 0x23: 'ReleaseTime',
- 0x25: 'ExpirationDate',
- 0x26: 'ExpirationTime',
- 0x28: 'SpecialInstructions',
- 0x2a: 'ActionAdvised',
- 0x2d: 'RefService',
- 0x2f: 'RefDate',
- 0x32: 'RefNumber',
- 0x37: 'DateCreated',
- 0x3c: 'TimeCreated',
- 0x3e: 'DigitalCreationDate',
- 0x3f: 'DigitalCreationTime',
- 0x41: 'OriginatingProgram',
- 0x46: 'ProgramVersion',
- 0x4b: 'ObjectCycle',
- 0x50: 'Byline',
- 0x55: 'BylineTitle',
- 0x5a: 'City',
- 0x5c: 'Sublocation',
- 0x5f: 'State',
- 0x64: 'CountryCode',
- 0x65: 'CountryName',
- 0x67: 'OrigTransRef',
- 0x69: 'Headline',
- 0x6e: 'Credit',
- 0x73: 'Source',
- 0x74: 'CopyrightNotice',
- 0x76: 'Contact',
- 0x78: 'Caption',
- 0x7a: 'WriterEditor',
- 0x82: 'ImageType',
- 0x83: 'ImageOrientation',
- 0x87: 'LanguageID'
+ var IptcMapProto = loadImage.IptcMap.prototype
- // We don't record these tags:
- //
- // 0x00: 'RecordVersion',
- // 0x7d: 'RasterizedCaption',
- // 0x96: 'AudioType',
- // 0x97: 'AudioSamplingRate',
- // 0x98: 'AudioSamplingRes',
- // 0x99: 'AudioDuration',
- // 0x9a: 'AudioOutcue',
- // 0xc8: 'PreviewFileFormat',
- // 0xc9: 'PreviewFileFormatVer',
- // 0xca: 'PreviewData'
+ IptcMapProto.tags = {
+ 0: 'ApplicationRecordVersion',
+ 3: 'ObjectTypeReference',
+ 4: 'ObjectAttributeReference',
+ 5: 'ObjectName',
+ 7: 'EditStatus',
+ 8: 'EditorialUpdate',
+ 10: 'Urgency',
+ 12: 'SubjectReference',
+ 15: 'Category',
+ 20: 'SupplementalCategories',
+ 22: 'FixtureIdentifier',
+ 25: 'Keywords',
+ 26: 'ContentLocationCode',
+ 27: 'ContentLocationName',
+ 30: 'ReleaseDate',
+ 35: 'ReleaseTime',
+ 37: 'ExpirationDate',
+ 38: 'ExpirationTime',
+ 40: 'SpecialInstructions',
+ 42: 'ActionAdvised',
+ 45: 'ReferenceService',
+ 47: 'ReferenceDate',
+ 50: 'ReferenceNumber',
+ 55: 'DateCreated',
+ 60: 'TimeCreated',
+ 62: 'DigitalCreationDate',
+ 63: 'DigitalCreationTime',
+ 65: 'OriginatingProgram',
+ 70: 'ProgramVersion',
+ 75: 'ObjectCycle',
+ 80: 'Byline',
+ 85: 'BylineTitle',
+ 90: 'City',
+ 92: 'Sublocation',
+ 95: 'State',
+ 100: 'CountryCode',
+ 101: 'Country',
+ 103: 'OriginalTransmissionReference',
+ 105: 'Headline',
+ 110: 'Credit',
+ 115: 'Source',
+ 116: 'CopyrightNotice',
+ 118: 'Contact',
+ 120: 'Caption',
+ 121: 'LocalCaption',
+ 122: 'Writer',
+ 125: 'RasterizedCaption',
+ 130: 'ImageType',
+ 131: 'ImageOrientation',
+ 135: 'LanguageIdentifier',
+ 150: 'AudioType',
+ 151: 'AudioSamplingRate',
+ 152: 'AudioSamplingResolution',
+ 153: 'AudioDuration',
+ 154: 'AudioOutcue',
+ 184: 'JobID',
+ 185: 'MasterDocumentID',
+ 186: 'ShortDocumentID',
+ 187: 'UniqueDocumentID',
+ 188: 'OwnerID',
+ 200: 'ObjectPreviewFileFormat',
+ 201: 'ObjectPreviewFileVersion',
+ 202: 'ObjectPreviewData',
+ 221: 'Prefs',
+ 225: 'ClassifyState',
+ 228: 'SimilarityIndex',
+ 230: 'DocumentNotes',
+ 231: 'DocumentHistory',
+ 232: 'ExifCameraInfo',
+ 255: 'CatalogSets'
}
- loadImage.IptcMap.prototype.getText = function(id) {
+ IptcMapProto.stringValues = {
+ 10: {
+ 0: '0 (reserved)',
+ 1: '1 (most urgent)',
+ 2: '2',
+ 3: '3',
+ 4: '4',
+ 5: '5 (normal urgency)',
+ 6: '6',
+ 7: '7',
+ 8: '8 (least urgent)',
+ 9: '9 (user-defined priority)'
+ },
+ 75: {
+ a: 'Morning',
+ b: 'Both Morning and Evening',
+ p: 'Evening'
+ },
+ 131: {
+ L: 'Landscape',
+ P: 'Portrait',
+ S: 'Square'
+ }
+ }
+
+ IptcMapProto.getText = function (id) {
var value = this.get(id)
+ var tagCode = this.map[id]
+ var stringValue = this.stringValues[tagCode]
+ if (stringValue) return stringValue[value]
return String(value)
}
- ;(function(iptcMapPrototype) {
- var tags = iptcMapPrototype.tags
- var map = iptcMapPrototype.map || {}
- var prop
- // Map the tag names to tags:
- for (prop in tags) {
- if (Object.prototype.hasOwnProperty.call(tags, prop)) {
- map[tags[prop]] = prop
- }
- }
- })(loadImage.IptcMap.prototype)
- loadImage.IptcMap.prototype.getAll = function() {
+ IptcMapProto.getAll = function () {
var map = {}
var prop
- var id
+ var name
for (prop in this) {
if (Object.prototype.hasOwnProperty.call(this, prop)) {
- id = this.tags[prop]
- if (id) {
- map[id] = this.getText(id)
- }
+ name = this.tags[prop]
+ if (name) map[name] = this.getText(name)
}
}
return map
}
+
+ IptcMapProto.getName = function (tagCode) {
+ return this.tags[tagCode]
+ }
+
+ // Extend the map of tag names to tag codes:
+ ;(function () {
+ var tags = IptcMapProto.tags
+ var map = IptcMapProto.map || {}
+ var prop
+ // Map the tag names to tags:
+ for (prop in tags) {
+ if (Object.prototype.hasOwnProperty.call(tags, prop)) {
+ map[tags[prop]] = Number(prop)
+ }
+ }
+ })()
})
diff --git a/js/load-image-iptc.js b/js/load-image-iptc.js
index be2e764..04eb796 100644
--- a/js/load-image-iptc.js
+++ b/js/load-image-iptc.js
@@ -10,9 +10,9 @@
* https://opensource.org/licenses/MIT
*/
-/* global define, module, require, Buffer */
+/* global define, module, require, DataView */
-;(function(factory) {
+;(function (factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
@@ -23,131 +23,217 @@
// Browser globals:
factory(window.loadImage)
}
-})(function(loadImage) {
+})(function (loadImage) {
'use strict'
- loadImage.IptcMap = function() {
- return this
+ /**
+ * IPTC tag map
+ *
+ * @name IptcMap
+ * @class
+ */
+ function IptcMap() {}
+
+ IptcMap.prototype.map = {
+ ObjectName: 5
}
- loadImage.IptcMap.prototype.map = {
- ObjectName: 0x5
+ IptcMap.prototype.types = {
+ 0: 'Uint16', // ApplicationRecordVersion
+ 200: 'Uint16', // ObjectPreviewFileFormat
+ 201: 'Uint16', // ObjectPreviewFileVersion
+ 202: 'binary' // ObjectPreviewData
}
- loadImage.IptcMap.prototype.get = function(id) {
+ /**
+ * Retrieves IPTC tag value
+ *
+ * @param {number|string} id IPTC tag code or name
+ * @returns {object} IPTC tag value
+ */
+ IptcMap.prototype.get = function (id) {
return this[id] || this[this.map[id]]
}
- loadImage.parseIptcTags = function(
+ /**
+ * Retrieves string for the given DataView and range
+ *
+ * @param {DataView} dataView Data view interface
+ * @param {number} offset Offset start
+ * @param {number} length Offset length
+ * @returns {string} String value
+ */
+ function getStringValue(dataView, offset, length) {
+ var outstr = ''
+ var end = offset + length
+ for (var n = offset; n < end; n += 1) {
+ outstr += String.fromCharCode(dataView.getUint8(n))
+ }
+ return outstr
+ }
+
+ /**
+ * Retrieves tag value for the given DataView and range
+ *
+ * @param {number} tagCode tag code
+ * @param {IptcMap} map IPTC tag map
+ * @param {DataView} dataView Data view interface
+ * @param {number} offset Range start
+ * @param {number} length Range length
+ * @returns {object} Tag value
+ */
+ function getTagValue(tagCode, map, dataView, offset, length) {
+ if (map.types[tagCode] === 'binary') {
+ return new Blob([dataView.buffer.slice(offset, offset + length)])
+ }
+ if (map.types[tagCode] === 'Uint16') {
+ return dataView.getUint16(offset)
+ }
+ return getStringValue(dataView, offset, length)
+ }
+
+ /**
+ * Combines IPTC value with existing ones.
+ *
+ * @param {object} value Existing IPTC field value
+ * @param {object} newValue New IPTC field value
+ * @returns {object} Resulting IPTC field value
+ */
+ function combineTagValues(value, newValue) {
+ if (value === undefined) return newValue
+ if (value instanceof Array) {
+ value.push(newValue)
+ return value
+ }
+ return [value, newValue]
+ }
+
+ /**
+ * Parses IPTC tags.
+ *
+ * @param {DataView} dataView Data view interface
+ * @param {number} segmentOffset Segment offset
+ * @param {number} segmentLength Segment length
+ * @param {object} data Data export object
+ * @param {object} includeTags Map of tags to include
+ * @param {object} excludeTags Map of tags to exclude
+ */
+ function parseIptcTags(
dataView,
- startOffset,
- sectionLength,
- data
+ segmentOffset,
+ segmentLength,
+ data,
+ includeTags,
+ excludeTags
) {
- /**
- * Retrieves string for the given Buffer and range
- *
- * @param {Buffer} buffer IPTC buffer
- * @param {number} start Range start
- * @param {number} length Range length
- * @returns {string} String value
- */
- function getStringFromDB(buffer, start, length) {
- var outstr = ''
- for (var n = start; n < start + length; n++) {
- outstr += String.fromCharCode(buffer.getUint8(n))
- }
- return outstr
- }
- var fieldValue, dataSize, segmentType
- var segmentStartPos = startOffset
- while (segmentStartPos < startOffset + sectionLength) {
- // we currently handle the 2: class of iptc tag
+ var value, tagSize, tagCode
+ var segmentEnd = segmentOffset + segmentLength
+ var offset = segmentOffset
+ while (offset < segmentEnd) {
if (
- dataView.getUint8(segmentStartPos) === 0x1c &&
- dataView.getUint8(segmentStartPos + 1) === 0x02
+ dataView.getUint8(offset) === 0x1c && // tag marker
+ dataView.getUint8(offset + 1) === 0x02 // record number, only handles v2
) {
- segmentType = dataView.getUint8(segmentStartPos + 2)
- // only store data for known tags
- if (segmentType in data.iptc.tags) {
- dataSize = dataView.getInt16(segmentStartPos + 3)
- fieldValue = getStringFromDB(dataView, segmentStartPos + 5, dataSize)
- // Check if we already stored a value with this name
- if (Object.prototype.hasOwnProperty.call(data.iptc, segmentType)) {
- // Value already stored with this name, create multivalue field
- if (data.iptc[segmentType] instanceof Array) {
- data.iptc[segmentType].push(fieldValue)
- } else {
- data.iptc[segmentType] = [data.iptc[segmentType], fieldValue]
- }
- } else {
- data.iptc[segmentType] = fieldValue
+ tagCode = dataView.getUint8(offset + 2)
+ if (
+ (!includeTags || includeTags[tagCode]) &&
+ (!excludeTags || !excludeTags[tagCode])
+ ) {
+ tagSize = dataView.getInt16(offset + 3)
+ value = getTagValue(tagCode, data.iptc, dataView, offset + 5, tagSize)
+ data.iptc[tagCode] = combineTagValues(data.iptc[tagCode], value)
+ if (data.iptcOffsets) {
+ data.iptcOffsets[tagCode] = offset
}
}
}
- segmentStartPos++
+ offset += 1
}
}
- loadImage.parseIptcData = function(dataView, offset, length, data, options) {
+ /**
+ * Tests if field segment starts at offset.
+ *
+ * @param {DataView} dataView Data view interface
+ * @param {number} offset Segment offset
+ * @returns {boolean} True if '8BIM
' exists at offset
+ */
+ function isSegmentStart(dataView, offset) {
+ return (
+ dataView.getUint32(offset) === 0x3842494d && // Photoshop segment start
+ dataView.getUint16(offset + 4) === 0x0404 // IPTC segment start
+ )
+ }
+
+ /**
+ * Returns header length.
+ *
+ * @param {DataView} dataView Data view interface
+ * @param {number} offset Segment offset
+ * @returns {number} Header length
+ */
+ function getHeaderLength(dataView, offset) {
+ var length = dataView.getUint8(offset + 7)
+ if (length % 2 !== 0) length += 1
+ // Check for pre photoshop 6 format
+ if (length === 0) {
+ // Always 4
+ length = 4
+ }
+ return length
+ }
+
+ loadImage.parseIptcData = function (dataView, offset, length, data, options) {
if (options.disableIptc) {
return
}
var markerLength = offset + length
- // Found '8BIM' ?
- var isFieldSegmentStart = function(dataView, offset) {
- return (
- dataView.getUint32(offset) === 0x3842494d &&
- dataView.getUint16(offset + 4) === 0x0404
- )
- }
- // Hunt forward, looking for the correct IPTC block signature:
- // Reference: https://metacpan.org/pod/distribution/Image-MetaData-JPEG/lib/Image/MetaData/JPEG/Structures.pod#Structure-of-a-Photoshop-style-APP13-segment
- // From https://github.com/exif-js/exif-js/blob/master/exif.js ~ line 474 on
while (offset + 8 < markerLength) {
- if (isFieldSegmentStart(dataView, offset)) {
- var nameHeaderLength = dataView.getUint8(offset + 7)
- if (nameHeaderLength % 2 !== 0) nameHeaderLength += 1
- // Check for pre photoshop 6 format
- if (nameHeaderLength === 0) {
- // Always 4
- nameHeaderLength = 4
- }
- var startOffset = offset + 8 + nameHeaderLength
- if (startOffset > markerLength) {
+ if (isSegmentStart(dataView, offset)) {
+ var headerLength = getHeaderLength(dataView, offset)
+ var segmentOffset = offset + 8 + headerLength
+ if (segmentOffset > markerLength) {
// eslint-disable-next-line no-console
console.log('Invalid IPTC data: Invalid segment offset.')
break
}
- var sectionLength = dataView.getUint16(offset + 6 + nameHeaderLength)
- if (offset + sectionLength > markerLength) {
+ var segmentLength = dataView.getUint16(offset + 6 + headerLength)
+ if (offset + segmentLength > markerLength) {
// eslint-disable-next-line no-console
console.log('Invalid IPTC data: Invalid segment size.')
break
}
// Create the iptc object to store the tags:
- data.iptc = new loadImage.IptcMap()
- // Parse the tags
- return loadImage.parseIptcTags(
+ data.iptc = new IptcMap()
+ if (!options.disableIptcOffsets) {
+ data.iptcOffsets = new IptcMap()
+ }
+ parseIptcTags(
dataView,
- startOffset,
- sectionLength,
- data
+ segmentOffset,
+ segmentLength,
+ data,
+ options.includeIptcTags,
+ options.excludeIptcTags || { 202: true } // ObjectPreviewData
)
+ return
}
// eslint-disable-next-line no-param-reassign
- offset++
+ offset += 1
}
- // eslint-disable-next-line no-console
- console.log('No IPTC data at this offset - could be XMP')
}
- // Registers this IPTC parser for the APP13 JPEG meta data segment:
+ // Registers this IPTC parser for the APP13 JPEG metadata segment:
loadImage.metaDataParsers.jpeg[0xffed].push(loadImage.parseIptcData)
+ loadImage.IptcMap = IptcMap
+
// Adds the following properties to the parseMetaData callback data:
- // * iptc: The iptc tags, parsed by the parseIptcData method
+ // - iptc: The iptc tags, parsed by the parseIptcData method
// Adds the following options to the parseMetaData method:
- // * disableIptc: Disables IPTC parsing.
+ // - disableIptc: Disables IPTC parsing when true.
+ // - disableIptcOffsets: Disables storing IPTC tag offsets when true.
+ // - includeIptcTags: A map of IPTC tags to include for parsing.
+ // - excludeIptcTags: A map of IPTC tags to exclude from parsing.
})
diff --git a/js/load-image-meta.js b/js/load-image-meta.js
index c110036..357b9b3 100644
--- a/js/load-image-meta.js
+++ b/js/load-image-meta.js
@@ -5,7 +5,7 @@
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
- * Image meta data handling implementation
+ * Image metadata handling implementation
* based on the help and contribution of
* Achim Stöhr.
*
@@ -13,9 +13,9 @@
* https://opensource.org/licenses/MIT
*/
-/* global define, module, require, DataView, Uint8Array */
+/* global define, module, require, Promise, DataView, Uint8Array, ArrayBuffer */
-;(function(factory) {
+;(function (factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
@@ -26,82 +26,102 @@
// Browser globals:
factory(window.loadImage)
}
-})(function(loadImage) {
+})(function (loadImage) {
'use strict'
- var hasblobSlice =
- typeof Blob !== 'undefined' &&
+ var global = loadImage.global
+ var originalTransform = loadImage.transform
+
+ var blobSlice =
+ global.Blob &&
(Blob.prototype.slice ||
Blob.prototype.webkitSlice ||
Blob.prototype.mozSlice)
- loadImage.blobSlice =
- hasblobSlice &&
- function() {
- var slice = this.slice || this.webkitSlice || this.mozSlice
- return slice.apply(this, arguments)
+ var bufferSlice =
+ (global.ArrayBuffer && ArrayBuffer.prototype.slice) ||
+ function (begin, end) {
+ // Polyfill for IE10, which does not support ArrayBuffer.slice
+ // eslint-disable-next-line no-param-reassign
+ end = end || this.byteLength - begin
+ var arr1 = new Uint8Array(this, begin, end)
+ var arr2 = new Uint8Array(end)
+ arr2.set(arr1)
+ return arr2.buffer
}
- loadImage.metaDataParsers = {
+ var metaDataParsers = {
jpeg: {
0xffe1: [], // APP1 marker
0xffed: [] // APP13 marker
}
}
- // Parses image meta data and calls the callback with an object argument
- // with the following properties:
- // * imageHead: The complete image head as ArrayBuffer (Uint8Array for IE10)
- // The options argument accepts an object and supports the following
- // properties:
- // * maxMetaDataSize: Defines the maximum number of bytes to parse.
- // * disableImageHead: Disables creating the imageHead property.
- loadImage.parseMetaData = function(file, callback, options, data) {
- // eslint-disable-next-line no-param-reassign
- options = options || {}
- // eslint-disable-next-line no-param-reassign
- data = data || {}
+ /**
+ * Parses image metadata and calls the callback with an object argument
+ * with the following property:
+ * - imageHead: The complete image head as ArrayBuffer
+ * The options argument accepts an object and supports the following
+ * properties:
+ * - maxMetaDataSize: Defines the maximum number of bytes to parse.
+ * - disableImageHead: Disables creating the imageHead property.
+ *
+ * @param {Blob} file Blob object
+ * @param {Function} [callback] Callback function
+ * @param {object} [options] Parsing options
+ * @param {object} [data] Result data object
+ * @returns {Promise|undefined} Returns Promise if no callback given.
+ */
+ function parseMetaData(file, callback, options, data) {
var that = this
- // 256 KiB should contain all EXIF/ICC/IPTC segments:
- var maxMetaDataSize = options.maxMetaDataSize || 262144
- var noMetaData = !(
- typeof DataView !== 'undefined' &&
- file &&
- file.size >= 12 &&
- file.type === 'image/jpeg' &&
- loadImage.blobSlice
- )
- if (
- noMetaData ||
- !loadImage.readFile(
- loadImage.blobSlice.call(file, 0, maxMetaDataSize),
- function(e) {
- if (e.target.error) {
- // FileReader error
- // eslint-disable-next-line no-console
- console.log(e.target.error)
- callback(data)
- return
- }
- // Note on endianness:
- // Since the marker and length bytes in JPEG files are always
- // stored in big endian order, we can leave the endian parameter
- // of the DataView methods undefined, defaulting to big endian.
- var buffer = e.target.result
- var dataView = new DataView(buffer)
- var offset = 2
- var maxOffset = dataView.byteLength - 4
- var headLength = offset
- var markerBytes
- var markerLength
- var parsers
- var i
- // Check for the JPEG marker (0xffd8):
- if (dataView.getUint16(0) === 0xffd8) {
+ /**
+ * Promise executor
+ *
+ * @param {Function} resolve Resolution function
+ * @param {Function} reject Rejection function
+ * @returns {undefined} Undefined
+ */
+ function executor(resolve, reject) {
+ if (
+ !(
+ global.DataView &&
+ blobSlice &&
+ file &&
+ file.size >= 12 &&
+ file.type === 'image/jpeg'
+ )
+ ) {
+ // Nothing to parse
+ return resolve(data)
+ }
+ // 256 KiB should contain all EXIF/ICC/IPTC segments:
+ var maxMetaDataSize = options.maxMetaDataSize || 262144
+ if (
+ !loadImage.readFile(
+ blobSlice.call(file, 0, maxMetaDataSize),
+ function (buffer) {
+ // Note on endianness:
+ // Since the marker and length bytes in JPEG files are always
+ // stored in big endian order, we can leave the endian parameter
+ // of the DataView methods undefined, defaulting to big endian.
+ var dataView = new DataView(buffer)
+ // Check for the JPEG marker (0xffd8):
+ if (dataView.getUint16(0) !== 0xffd8) {
+ return reject(
+ new Error('Invalid JPEG file: Missing JPEG marker.')
+ )
+ }
+ var offset = 2
+ var maxOffset = dataView.byteLength - 4
+ var headLength = offset
+ var markerBytes
+ var markerLength
+ var parsers
+ var i
while (offset < maxOffset) {
markerBytes = dataView.getUint16(offset)
// Search for APPn (0xffeN) and COM (0xfffe) markers,
- // which contain application-specific meta-data like
+ // which contain application-specific metadata like
// Exif, ICC and IPTC data and text comments:
if (
(markerBytes >= 0xffe0 && markerBytes <= 0xffef) ||
@@ -114,11 +134,11 @@
markerLength = dataView.getUint16(offset + 2) + 2
if (offset + markerLength > dataView.byteLength) {
// eslint-disable-next-line no-console
- console.log('Invalid meta data: Invalid segment size.')
+ console.log('Invalid JPEG metadata: Invalid segment size.')
break
}
- parsers = loadImage.metaDataParsers.jpeg[markerBytes]
- if (parsers) {
+ parsers = metaDataParsers.jpeg[markerBytes]
+ if (parsers && !options.disableMetaDataParsers) {
for (i = 0; i < parsers.length; i += 1) {
parsers[i].call(
that,
@@ -134,46 +154,94 @@
headLength = offset
} else {
// Not an APPn or COM marker, probably safe to
- // assume that this is the end of the meta data
+ // assume that this is the end of the metadata
break
}
}
// Meta length must be longer than JPEG marker (2)
// plus APPn marker (2), followed by length bytes (2):
if (!options.disableImageHead && headLength > 6) {
- if (buffer.slice) {
- data.imageHead = buffer.slice(0, headLength)
- } else {
- // Workaround for IE10, which does not yet
- // support ArrayBuffer.slice:
- data.imageHead = new Uint8Array(buffer).subarray(0, headLength)
- }
+ data.imageHead = bufferSlice.call(buffer, 0, headLength)
}
- } else {
- // eslint-disable-next-line no-console
- console.log('Invalid JPEG file: Missing JPEG marker.')
- }
- callback(data)
- },
- 'readAsArrayBuffer'
- )
- ) {
- callback(data)
+ resolve(data)
+ },
+ reject,
+ 'readAsArrayBuffer'
+ )
+ ) {
+ // No support for the FileReader interface, nothing to parse
+ resolve(data)
+ }
+ }
+ options = options || {} // eslint-disable-line no-param-reassign
+ if (global.Promise && typeof callback !== 'function') {
+ options = callback || {} // eslint-disable-line no-param-reassign
+ data = options // eslint-disable-line no-param-reassign
+ return new Promise(executor)
}
+ data = data || {} // eslint-disable-line no-param-reassign
+ return executor(callback, callback)
}
- // Determines if meta data should be loaded automatically:
- loadImage.hasMetaOption = function(options) {
- return options && options.meta
+ /**
+ * Replaces the head of a JPEG Blob
+ *
+ * @param {Blob} blob Blob object
+ * @param {ArrayBuffer} oldHead Old JPEG head
+ * @param {ArrayBuffer} newHead New JPEG head
+ * @returns {Blob} Combined Blob
+ */
+ function replaceJPEGHead(blob, oldHead, newHead) {
+ if (!blob || !oldHead || !newHead) return null
+ return new Blob([newHead, blobSlice.call(blob, oldHead.byteLength)], {
+ type: 'image/jpeg'
+ })
}
- var originalTransform = loadImage.transform
- loadImage.transform = function(img, options, callback, file, data) {
- if (loadImage.hasMetaOption(options)) {
- loadImage.parseMetaData(
+ /**
+ * Replaces the image head of a JPEG blob with the given one.
+ * Returns a Promise or calls the callback with the new Blob.
+ *
+ * @param {Blob} blob Blob object
+ * @param {ArrayBuffer} head New JPEG head
+ * @param {Function} [callback] Callback function
+ * @returns {Promise|undefined} Combined Blob
+ */
+ function replaceHead(blob, head, callback) {
+ var options = { maxMetaDataSize: 1024, disableMetaDataParsers: true }
+ if (!callback && global.Promise) {
+ return parseMetaData(blob, options).then(function (data) {
+ return replaceJPEGHead(blob, data.imageHead, head)
+ })
+ }
+ parseMetaData(
+ blob,
+ function (data) {
+ callback(replaceJPEGHead(blob, data.imageHead, head))
+ },
+ options
+ )
+ }
+
+ loadImage.transform = function (img, options, callback, file, data) {
+ if (loadImage.requiresMetaData(options)) {
+ data = data || {} // eslint-disable-line no-param-reassign
+ parseMetaData(
file,
- function(data) {
- originalTransform.call(loadImage, img, options, callback, file, data)
+ function (result) {
+ if (result !== data) {
+ // eslint-disable-next-line no-console
+ if (global.console) console.log(result)
+ result = data // eslint-disable-line no-param-reassign
+ }
+ originalTransform.call(
+ loadImage,
+ img,
+ options,
+ callback,
+ file,
+ result
+ )
},
options,
data
@@ -182,4 +250,10 @@
originalTransform.apply(loadImage, arguments)
}
}
+
+ loadImage.blobSlice = blobSlice
+ loadImage.bufferSlice = bufferSlice
+ loadImage.replaceHead = replaceHead
+ loadImage.parseMetaData = parseMetaData
+ loadImage.metaDataParsers = metaDataParsers
})
diff --git a/js/load-image-orientation.js b/js/load-image-orientation.js
index 11a5ccf..c3d53c4 100644
--- a/js/load-image-orientation.js
+++ b/js/load-image-orientation.js
@@ -9,9 +9,38 @@
* https://opensource.org/licenses/MIT
*/
+/*
+Exif orientation values to correctly display the letter F:
+
+ 1 2
+ ██████ ██████
+ ██ ██
+ ████ ████
+ ██ ██
+ ██ ██
+
+ 3 4
+ ██ ██
+ ██ ██
+ ████ ████
+ ██ ██
+ ██████ ██████
+
+ 5 6
+██████████ ██
+██ ██ ██ ██
+██ ██████████
+
+ 7 8
+ ██ ██████████
+ ██ ██ ██ ██
+██████████ ██
+
+*/
+
/* global define, module, require */
-;(function(factory) {
+;(function (factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
@@ -26,163 +55,427 @@
// Browser globals:
factory(window.loadImage)
}
-})(function(loadImage) {
+})(function (loadImage) {
'use strict'
- var originalHasCanvasOption = loadImage.hasCanvasOption
- var originalHasMetaOption = loadImage.hasMetaOption
+ var originalTransform = loadImage.transform
+ var originalRequiresCanvas = loadImage.requiresCanvas
+ var originalRequiresMetaData = loadImage.requiresMetaData
var originalTransformCoordinates = loadImage.transformCoordinates
var originalGetTransformedOptions = loadImage.getTransformedOptions
+ ;(function ($) {
+ // Guard for non-browser environments (e.g. server-side rendering):
+ if (!$.global.document) return
+ // black+white 3x2 JPEG, with the following meta information set:
+ // - EXIF Orientation: 6 (Rotated 90° CCW)
+ // Image data layout (B=black, F=white):
+ // BFF
+ // BBB
+ var testImageURL =
+ 'data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAA' +
+ 'AAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA' +
+ 'QEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE' +
+ 'BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/x' +
+ 'ABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAA' +
+ 'AAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQ' +
+ 'voP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXw' +
+ 'H/9k='
+ var img = document.createElement('img')
+ img.onload = function () {
+ // Check if the browser supports automatic image orientation:
+ $.orientation = img.width === 2 && img.height === 3
+ if ($.orientation) {
+ var canvas = $.createCanvas(1, 1, true)
+ var ctx = canvas.getContext('2d')
+ ctx.drawImage(img, 1, 1, 1, 1, 0, 0, 1, 1)
+ // Check if the source image coordinates (sX, sY, sWidth, sHeight) are
+ // correctly applied to the auto-orientated image, which should result
+ // in a white opaque pixel (e.g. in Safari).
+ // Browsers that show a transparent pixel (e.g. Chromium) fail to crop
+ // auto-oriented images correctly and require a workaround, e.g.
+ // drawing the complete source image to an intermediate canvas first.
+ // See https://bugs.chromium.org/p/chromium/issues/detail?id=1074354
+ $.orientationCropBug =
+ ctx.getImageData(0, 0, 1, 1).data.toString() !== '255,255,255,255'
+ }
+ }
+ img.src = testImageURL
+ })(loadImage)
+
+ /**
+ * Determines if the orientation requires a canvas element.
+ *
+ * @param {object} [options] Options object
+ * @param {boolean} [withMetaData] Is metadata required for orientation
+ * @returns {boolean} Returns true if orientation requires canvas/meta
+ */
+ function requiresCanvasOrientation(options, withMetaData) {
+ var orientation = options && options.orientation
+ return (
+ // Exif orientation for browsers without automatic image orientation:
+ (orientation === true && !loadImage.orientation) ||
+ // Orientation reset for browsers with automatic image orientation:
+ (orientation === 1 && loadImage.orientation) ||
+ // Orientation to defined value, requires meta for orientation reset only:
+ ((!withMetaData || loadImage.orientation) &&
+ orientation > 1 &&
+ orientation < 9)
+ )
+ }
+
+ /**
+ * Determines if the image requires an orientation change.
+ *
+ * @param {number} [orientation] Defined orientation value
+ * @param {number} [autoOrientation] Auto-orientation based on Exif data
+ * @returns {boolean} Returns true if an orientation change is required
+ */
+ function requiresOrientationChange(orientation, autoOrientation) {
+ return (
+ orientation !== autoOrientation &&
+ ((orientation === 1 && autoOrientation > 1 && autoOrientation < 9) ||
+ (orientation > 1 && orientation < 9))
+ )
+ }
+
+ /**
+ * Determines orientation combinations that require a rotation by 180°.
+ *
+ * The following is a list of combinations that return true:
+ *
+ * 2 (flip) => 5 (rot90,flip), 7 (rot90,flip), 6 (rot90), 8 (rot90)
+ * 4 (flip) => 5 (rot90,flip), 7 (rot90,flip), 6 (rot90), 8 (rot90)
+ *
+ * 5 (rot90,flip) => 2 (flip), 4 (flip), 6 (rot90), 8 (rot90)
+ * 7 (rot90,flip) => 2 (flip), 4 (flip), 6 (rot90), 8 (rot90)
+ *
+ * 6 (rot90) => 2 (flip), 4 (flip), 5 (rot90,flip), 7 (rot90,flip)
+ * 8 (rot90) => 2 (flip), 4 (flip), 5 (rot90,flip), 7 (rot90,flip)
+ *
+ * @param {number} [orientation] Defined orientation value
+ * @param {number} [autoOrientation] Auto-orientation based on Exif data
+ * @returns {boolean} Returns true if rotation by 180° is required
+ */
+ function requiresRot180(orientation, autoOrientation) {
+ if (autoOrientation > 1 && autoOrientation < 9) {
+ switch (orientation) {
+ case 2:
+ case 4:
+ return autoOrientation > 4
+ case 5:
+ case 7:
+ return autoOrientation % 2 === 0
+ case 6:
+ case 8:
+ return (
+ autoOrientation === 2 ||
+ autoOrientation === 4 ||
+ autoOrientation === 5 ||
+ autoOrientation === 7
+ )
+ }
+ }
+ return false
+ }
+
// Determines if the target image should be a canvas element:
- loadImage.hasCanvasOption = function(options) {
+ loadImage.requiresCanvas = function (options) {
return (
- !!options.orientation || originalHasCanvasOption.call(loadImage, options)
+ requiresCanvasOrientation(options) ||
+ originalRequiresCanvas.call(loadImage, options)
)
}
- // Determines if meta data should be loaded automatically:
- loadImage.hasMetaOption = function(options) {
+ // Determines if metadata should be loaded automatically:
+ loadImage.requiresMetaData = function (options) {
return (
- (options && options.orientation === true) ||
- originalHasMetaOption.call(loadImage, options)
+ requiresCanvasOrientation(options, true) ||
+ originalRequiresMetaData.call(loadImage, options)
)
}
- // Transform image orientation based on
- // the given EXIF orientation option:
- loadImage.transformCoordinates = function(canvas, options) {
- originalTransformCoordinates.call(loadImage, canvas, options)
- var ctx = canvas.getContext('2d')
- var width = canvas.width
- var height = canvas.height
- var styleWidth = canvas.style.width
- var styleHeight = canvas.style.height
+ loadImage.transform = function (img, options, callback, file, data) {
+ originalTransform.call(
+ loadImage,
+ img,
+ options,
+ function (img, data) {
+ if (data) {
+ var autoOrientation =
+ loadImage.orientation && data.exif && data.exif.get('Orientation')
+ if (autoOrientation > 4 && autoOrientation < 9) {
+ // Automatic image orientation switched image dimensions
+ var originalWidth = data.originalWidth
+ var originalHeight = data.originalHeight
+ data.originalWidth = originalHeight
+ data.originalHeight = originalWidth
+ }
+ }
+ callback(img, data)
+ },
+ file,
+ data
+ )
+ }
+
+ // Transforms coordinate and dimension options
+ // based on the given orientation option:
+ loadImage.getTransformedOptions = function (img, opts, data) {
+ var options = originalGetTransformedOptions.call(loadImage, img, opts)
+ var exifOrientation = data.exif && data.exif.get('Orientation')
var orientation = options.orientation
- if (!orientation || orientation > 8) {
- return
+ var autoOrientation = loadImage.orientation && exifOrientation
+ if (orientation === true) orientation = exifOrientation
+ if (!requiresOrientationChange(orientation, autoOrientation)) {
+ return options
}
- if (orientation > 4) {
- canvas.width = height
- canvas.height = width
- canvas.style.width = styleHeight
- canvas.style.height = styleWidth
+ var top = options.top
+ var right = options.right
+ var bottom = options.bottom
+ var left = options.left
+ var newOptions = {}
+ for (var i in options) {
+ if (Object.prototype.hasOwnProperty.call(options, i)) {
+ newOptions[i] = options[i]
+ }
+ }
+ newOptions.orientation = orientation
+ if (
+ (orientation > 4 && !(autoOrientation > 4)) ||
+ (orientation < 5 && autoOrientation > 4)
+ ) {
+ // Image dimensions and target dimensions are switched
+ newOptions.maxWidth = options.maxHeight
+ newOptions.maxHeight = options.maxWidth
+ newOptions.minWidth = options.minHeight
+ newOptions.minHeight = options.minWidth
+ newOptions.sourceWidth = options.sourceHeight
+ newOptions.sourceHeight = options.sourceWidth
+ }
+ if (autoOrientation > 1) {
+ // Browsers which correctly apply source image coordinates to
+ // auto-oriented images
+ switch (autoOrientation) {
+ case 2:
+ // Horizontal flip
+ right = options.left
+ left = options.right
+ break
+ case 3:
+ // 180° Rotate CCW
+ top = options.bottom
+ right = options.left
+ bottom = options.top
+ left = options.right
+ break
+ case 4:
+ // Vertical flip
+ top = options.bottom
+ bottom = options.top
+ break
+ case 5:
+ // Horizontal flip + 90° Rotate CCW
+ top = options.left
+ right = options.bottom
+ bottom = options.right
+ left = options.top
+ break
+ case 6:
+ // 90° Rotate CCW
+ top = options.left
+ right = options.top
+ bottom = options.right
+ left = options.bottom
+ break
+ case 7:
+ // Vertical flip + 90° Rotate CCW
+ top = options.right
+ right = options.top
+ bottom = options.left
+ left = options.bottom
+ break
+ case 8:
+ // 90° Rotate CW
+ top = options.right
+ right = options.bottom
+ bottom = options.left
+ left = options.top
+ break
+ }
+ // Some orientation combinations require additional rotation by 180°:
+ if (requiresRot180(orientation, autoOrientation)) {
+ var tmpTop = top
+ var tmpRight = right
+ top = bottom
+ right = left
+ bottom = tmpTop
+ left = tmpRight
+ }
}
+ newOptions.top = top
+ newOptions.right = right
+ newOptions.bottom = bottom
+ newOptions.left = left
+ // Account for defined browser orientation:
switch (orientation) {
case 2:
- // horizontal flip
- ctx.translate(width, 0)
- ctx.scale(-1, 1)
+ // Horizontal flip
+ newOptions.right = left
+ newOptions.left = right
break
case 3:
- // 180° rotate left
- ctx.translate(width, height)
- ctx.rotate(Math.PI)
+ // 180° Rotate CCW
+ newOptions.top = bottom
+ newOptions.right = left
+ newOptions.bottom = top
+ newOptions.left = right
break
case 4:
- // vertical flip
- ctx.translate(0, height)
- ctx.scale(1, -1)
+ // Vertical flip
+ newOptions.top = bottom
+ newOptions.bottom = top
break
case 5:
- // vertical flip + 90 rotate right
- ctx.rotate(0.5 * Math.PI)
- ctx.scale(1, -1)
+ // Vertical flip + 90° Rotate CW
+ newOptions.top = left
+ newOptions.right = bottom
+ newOptions.bottom = right
+ newOptions.left = top
break
case 6:
- // 90° rotate right
- ctx.rotate(0.5 * Math.PI)
- ctx.translate(0, -height)
+ // 90° Rotate CW
+ newOptions.top = right
+ newOptions.right = bottom
+ newOptions.bottom = left
+ newOptions.left = top
break
case 7:
- // horizontal flip + 90 rotate right
- ctx.rotate(0.5 * Math.PI)
- ctx.translate(width, -height)
- ctx.scale(-1, 1)
+ // Horizontal flip + 90° Rotate CW
+ newOptions.top = right
+ newOptions.right = top
+ newOptions.bottom = left
+ newOptions.left = bottom
break
case 8:
- // 90° rotate left
- ctx.rotate(-0.5 * Math.PI)
- ctx.translate(-width, 0)
+ // 90° Rotate CCW
+ newOptions.top = left
+ newOptions.right = top
+ newOptions.bottom = right
+ newOptions.left = bottom
break
}
+ return newOptions
}
- // Transforms coordinate and dimension options
- // based on the given orientation option:
- loadImage.getTransformedOptions = function(img, opts, data) {
- var options = originalGetTransformedOptions.call(loadImage, img, opts)
+ // Transform image orientation based on the given EXIF orientation option:
+ loadImage.transformCoordinates = function (canvas, options, data) {
+ originalTransformCoordinates.call(loadImage, canvas, options, data)
var orientation = options.orientation
- var newOptions
- var i
- if (orientation === true && data && data.exif) {
- orientation = data.exif.get('Orientation')
+ var autoOrientation =
+ loadImage.orientation && data.exif && data.exif.get('Orientation')
+ if (!requiresOrientationChange(orientation, autoOrientation)) {
+ return
}
- if (!orientation || orientation > 8 || orientation === 1) {
- return options
+ var ctx = canvas.getContext('2d')
+ var width = canvas.width
+ var height = canvas.height
+ var sourceWidth = width
+ var sourceHeight = height
+ if (
+ (orientation > 4 && !(autoOrientation > 4)) ||
+ (orientation < 5 && autoOrientation > 4)
+ ) {
+ // Image dimensions and target dimensions are switched
+ canvas.width = height
+ canvas.height = width
}
- newOptions = {}
- for (i in options) {
- if (Object.prototype.hasOwnProperty.call(options, i)) {
- newOptions[i] = options[i]
- }
+ if (orientation > 4) {
+ // Destination and source dimensions are switched
+ sourceWidth = height
+ sourceHeight = width
}
- newOptions.orientation = orientation
- switch (orientation) {
+ // Reset automatic browser orientation:
+ switch (autoOrientation) {
case 2:
- // horizontal flip
- newOptions.left = options.right
- newOptions.right = options.left
+ // Horizontal flip
+ ctx.translate(sourceWidth, 0)
+ ctx.scale(-1, 1)
break
case 3:
- // 180° rotate left
- newOptions.left = options.right
- newOptions.top = options.bottom
- newOptions.right = options.left
- newOptions.bottom = options.top
+ // 180° Rotate CCW
+ ctx.translate(sourceWidth, sourceHeight)
+ ctx.rotate(Math.PI)
break
case 4:
- // vertical flip
- newOptions.top = options.bottom
- newOptions.bottom = options.top
+ // Vertical flip
+ ctx.translate(0, sourceHeight)
+ ctx.scale(1, -1)
break
case 5:
- // vertical flip + 90 rotate right
- newOptions.left = options.top
- newOptions.top = options.left
- newOptions.right = options.bottom
- newOptions.bottom = options.right
+ // Horizontal flip + 90° Rotate CCW
+ ctx.rotate(-0.5 * Math.PI)
+ ctx.scale(-1, 1)
break
case 6:
- // 90° rotate right
- newOptions.left = options.top
- newOptions.top = options.right
- newOptions.right = options.bottom
- newOptions.bottom = options.left
+ // 90° Rotate CCW
+ ctx.rotate(-0.5 * Math.PI)
+ ctx.translate(-sourceWidth, 0)
break
case 7:
- // horizontal flip + 90 rotate right
- newOptions.left = options.bottom
- newOptions.top = options.right
- newOptions.right = options.top
- newOptions.bottom = options.left
+ // Vertical flip + 90° Rotate CCW
+ ctx.rotate(-0.5 * Math.PI)
+ ctx.translate(-sourceWidth, sourceHeight)
+ ctx.scale(1, -1)
break
case 8:
- // 90° rotate left
- newOptions.left = options.bottom
- newOptions.top = options.left
- newOptions.right = options.top
- newOptions.bottom = options.right
+ // 90° Rotate CW
+ ctx.rotate(0.5 * Math.PI)
+ ctx.translate(0, -sourceHeight)
break
}
- if (newOptions.orientation > 4) {
- newOptions.maxWidth = options.maxHeight
- newOptions.maxHeight = options.maxWidth
- newOptions.minWidth = options.minHeight
- newOptions.minHeight = options.minWidth
- newOptions.sourceWidth = options.sourceHeight
- newOptions.sourceHeight = options.sourceWidth
+ // Some orientation combinations require additional rotation by 180°:
+ if (requiresRot180(orientation, autoOrientation)) {
+ ctx.translate(sourceWidth, sourceHeight)
+ ctx.rotate(Math.PI)
+ }
+ switch (orientation) {
+ case 2:
+ // Horizontal flip
+ ctx.translate(width, 0)
+ ctx.scale(-1, 1)
+ break
+ case 3:
+ // 180° Rotate CCW
+ ctx.translate(width, height)
+ ctx.rotate(Math.PI)
+ break
+ case 4:
+ // Vertical flip
+ ctx.translate(0, height)
+ ctx.scale(1, -1)
+ break
+ case 5:
+ // Vertical flip + 90° Rotate CW
+ ctx.rotate(0.5 * Math.PI)
+ ctx.scale(1, -1)
+ break
+ case 6:
+ // 90° Rotate CW
+ ctx.rotate(0.5 * Math.PI)
+ ctx.translate(0, -height)
+ break
+ case 7:
+ // Horizontal flip + 90° Rotate CW
+ ctx.rotate(0.5 * Math.PI)
+ ctx.translate(width, -height)
+ ctx.scale(-1, 1)
+ break
+ case 8:
+ // 90° Rotate CCW
+ ctx.rotate(-0.5 * Math.PI)
+ ctx.translate(-width, 0)
+ break
}
- return newOptions
}
})
diff --git a/js/load-image-scale.js b/js/load-image-scale.js
index 39be9a5..c5e381e 100644
--- a/js/load-image-scale.js
+++ b/js/load-image-scale.js
@@ -11,7 +11,7 @@
/* global define, module, require */
-;(function(factory) {
+;(function (factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
@@ -22,12 +22,22 @@
// Browser globals:
factory(window.loadImage)
}
-})(function(loadImage) {
+})(function (loadImage) {
'use strict'
var originalTransform = loadImage.transform
- loadImage.transform = function(img, options, callback, file, data) {
+ loadImage.createCanvas = function (width, height, offscreen) {
+ if (offscreen && loadImage.global.OffscreenCanvas) {
+ return new OffscreenCanvas(width, height)
+ }
+ var canvas = document.createElement('canvas')
+ canvas.width = width
+ canvas.height = height
+ return canvas
+ }
+
+ loadImage.transform = function (img, options, callback, file, data) {
originalTransform.call(
loadImage,
loadImage.scale(img, options, data),
@@ -40,13 +50,13 @@
// Transform image coordinates, allows to override e.g.
// the canvas orientation based on the orientation option,
- // gets canvas, options passed as arguments:
- loadImage.transformCoordinates = function() {}
+ // gets canvas, options and data passed as arguments:
+ loadImage.transformCoordinates = function () {}
// Returns transformed options, allows to override e.g.
// maxWidth, maxHeight and crop options based on the aspectRatio.
- // gets img, options passed as arguments:
- loadImage.getTransformedOptions = function(img, options) {
+ // gets img, options, data passed as arguments:
+ loadImage.getTransformedOptions = function (img, options) {
var aspectRatio = options.aspectRatio
var newOptions
var i
@@ -75,51 +85,54 @@
}
// Canvas render method, allows to implement a different rendering algorithm:
- loadImage.renderImageToCanvas = function(
- canvas,
+ loadImage.drawImage = function (
img,
+ canvas,
sourceX,
sourceY,
sourceWidth,
sourceHeight,
- destX,
- destY,
destWidth,
- destHeight
+ destHeight,
+ options
) {
- canvas
- .getContext('2d')
- .drawImage(
- img,
- sourceX,
- sourceY,
- sourceWidth,
- sourceHeight,
- destX,
- destY,
- destWidth,
- destHeight
- )
- return canvas
+ var ctx = canvas.getContext('2d')
+ if (options.imageSmoothingEnabled === false) {
+ ctx.msImageSmoothingEnabled = false
+ ctx.imageSmoothingEnabled = false
+ } else if (options.imageSmoothingQuality) {
+ ctx.imageSmoothingQuality = options.imageSmoothingQuality
+ }
+ ctx.drawImage(
+ img,
+ sourceX,
+ sourceY,
+ sourceWidth,
+ sourceHeight,
+ 0,
+ 0,
+ destWidth,
+ destHeight
+ )
+ return ctx
}
// Determines if the target image should be a canvas element:
- loadImage.hasCanvasOption = function(options) {
+ loadImage.requiresCanvas = function (options) {
return options.canvas || options.crop || !!options.aspectRatio
}
// Scales and/or crops the given image (img or canvas HTML element)
- // using the given options.
- // Returns a canvas object if the browser supports canvas
- // and the hasCanvasOption method returns true or a canvas
- // object is passed as image, else the scaled image:
- loadImage.scale = function(img, options, data) {
+ // using the given options:
+ loadImage.scale = function (img, options, data) {
// eslint-disable-next-line no-param-reassign
options = options || {}
- var canvas = document.createElement('canvas')
+ // eslint-disable-next-line no-param-reassign
+ data = data || {}
var useCanvas =
img.getContext ||
- (loadImage.hasCanvasOption(options) && canvas.getContext)
+ (loadImage.requiresCanvas(options) &&
+ !!loadImage.global.HTMLCanvasElement)
var width = img.naturalWidth || img.width
var height = img.naturalHeight || img.height
var destWidth = width
@@ -135,6 +148,7 @@
var pixelRatio
var downsamplingRatio
var tmp
+ var canvas
/**
* Scales up image dimensions
*/
@@ -219,12 +233,40 @@
}
if (useCanvas) {
pixelRatio = options.pixelRatio
- if (pixelRatio > 1) {
- canvas.style.width = destWidth + 'px'
- canvas.style.height = destHeight + 'px'
+ if (
+ pixelRatio > 1 &&
+ // Check if the image has not yet had the device pixel ratio applied:
+ !(
+ img.style.width &&
+ Math.floor(parseFloat(img.style.width, 10)) ===
+ Math.floor(width / pixelRatio)
+ )
+ ) {
destWidth *= pixelRatio
destHeight *= pixelRatio
- canvas.getContext('2d').scale(pixelRatio, pixelRatio)
+ }
+ // Check if workaround for Chromium orientation crop bug is required:
+ // https://bugs.chromium.org/p/chromium/issues/detail?id=1074354
+ if (
+ loadImage.orientationCropBug &&
+ !img.getContext &&
+ (sourceX || sourceY || sourceWidth !== width || sourceHeight !== height)
+ ) {
+ // Write the complete source image to an intermediate canvas first:
+ tmp = img
+ // eslint-disable-next-line no-param-reassign
+ img = loadImage.createCanvas(width, height, true)
+ loadImage.drawImage(
+ tmp,
+ img,
+ 0,
+ 0,
+ width,
+ height,
+ width,
+ height,
+ options
+ )
}
downsamplingRatio = options.downsamplingRatio
if (
@@ -234,57 +276,49 @@
destHeight < sourceHeight
) {
while (sourceWidth * downsamplingRatio > destWidth) {
- canvas.width = sourceWidth * downsamplingRatio
- canvas.height = sourceHeight * downsamplingRatio
- loadImage.renderImageToCanvas(
- canvas,
+ canvas = loadImage.createCanvas(
+ sourceWidth * downsamplingRatio,
+ sourceHeight * downsamplingRatio,
+ true
+ )
+ loadImage.drawImage(
img,
+ canvas,
sourceX,
sourceY,
sourceWidth,
sourceHeight,
- 0,
- 0,
canvas.width,
- canvas.height
+ canvas.height,
+ options
)
sourceX = 0
sourceY = 0
sourceWidth = canvas.width
sourceHeight = canvas.height
// eslint-disable-next-line no-param-reassign
- img = document.createElement('canvas')
- img.width = sourceWidth
- img.height = sourceHeight
- loadImage.renderImageToCanvas(
- img,
- canvas,
- 0,
- 0,
- sourceWidth,
- sourceHeight,
- 0,
- 0,
- sourceWidth,
- sourceHeight
- )
+ img = canvas
}
}
- canvas.width = destWidth
- canvas.height = destHeight
- loadImage.transformCoordinates(canvas, options)
- return loadImage.renderImageToCanvas(
- canvas,
- img,
- sourceX,
- sourceY,
- sourceWidth,
- sourceHeight,
- 0,
- 0,
- destWidth,
- destHeight
- )
+ canvas = loadImage.createCanvas(destWidth, destHeight)
+ loadImage.transformCoordinates(canvas, options, data)
+ if (pixelRatio > 1) {
+ canvas.style.width = canvas.width / pixelRatio + 'px'
+ }
+ loadImage
+ .drawImage(
+ img,
+ canvas,
+ sourceX,
+ sourceY,
+ sourceWidth,
+ sourceHeight,
+ destWidth,
+ destHeight,
+ options
+ )
+ .setTransform(1, 0, 0, 1, 0, 0) // reset to the identity matrix
+ return canvas
}
img.width = destWidth
img.height = destHeight
diff --git a/js/load-image.all.min.js b/js/load-image.all.min.js
index 8d91291..884ef46 100644
--- a/js/load-image.all.min.js
+++ b/js/load-image.all.min.js
@@ -1,2 +1,2 @@
-!function(o){"use strict";function r(t,i,a){var o,n=document.createElement("img");return n.onerror=function(e){return r.onerror(n,e,t,i,a)},n.onload=function(e){return r.onload(n,e,t,i,a)},"string"==typeof t?(r.fetchBlob(t,function(e){e&&r.isInstanceOf("Blob",e)?o=r.createObjectURL(t=e):(o=t,a&&a.crossOrigin&&(n.crossOrigin=a.crossOrigin)),n.src=o},a),n):r.isInstanceOf("Blob",t)||r.isInstanceOf("File",t)?(o=n._objectURL=r.createObjectURL(t))?(n.src=o,n):r.readFile(t,function(e){var t=e.target;t&&t.result?n.src=t.result:i&&i(e)}):void 0}var t=o.createObjectURL&&o||o.URL&&URL.revokeObjectURL&&URL||o.webkitURL&&webkitURL;function n(e,t){!e._objectURL||t&&t.noRevoke||(r.revokeObjectURL(e._objectURL),delete e._objectURL)}r.fetchBlob=function(e,t){t()},r.isInstanceOf=function(e,t){return Object.prototype.toString.call(t)==="[object "+e+"]"},r.transform=function(e,t,i,a,o){i(e,o)},r.onerror=function(e,t,i,a,o){n(e,o),a&&a.call(e,t)},r.onload=function(e,t,i,a,o){n(e,o),a&&r.transform(e,o,a,i,{originalWidth:e.naturalWidth||e.width,originalHeight:e.naturalHeight||e.height})},r.createObjectURL=function(e){return!!t&&t.createObjectURL(e)},r.revokeObjectURL=function(e){return!!t&&t.revokeObjectURL(e)},r.readFile=function(e,t,i){if(o.FileReader){var a=new FileReader;if(a.onload=a.onerror=t,a[i=i||"readAsDataURL"])return a[i](e),a}return!1},"function"==typeof define&&define.amd?define(function(){return r}):"object"==typeof module&&module.exports?module.exports=r:o.loadImage=r}("undefined"!=typeof window&&window||this),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image"],e):"object"==typeof module&&module.exports?e(require("./load-image")):e(window.loadImage)}(function(I){"use strict";var n=I.transform;I.transform=function(e,t,i,a,o){n.call(I,I.scale(e,t,o),t,i,a,o)},I.transformCoordinates=function(){},I.getTransformedOptions=function(e,t){var i,a,o,n,r=t.aspectRatio;if(!r)return t;for(a in i={},t)Object.prototype.hasOwnProperty.call(t,a)&&(i[a]=t[a]);return i.crop=!0,r<(o=e.naturalWidth||e.width)/(n=e.naturalHeight||e.height)?(i.maxWidth=n*r,i.maxHeight=n):(i.maxWidth=o,i.maxHeight=o/r),i},I.renderImageToCanvas=function(e,t,i,a,o,n,r,s,l,c){return e.getContext("2d").drawImage(t,i,a,o,n,r,s,l,c),e},I.hasCanvasOption=function(e){return e.canvas||e.crop||!!e.aspectRatio},I.scale=function(e,t,i){t=t||{};var a,o,n,r,s,l,c,d,u,f,g,p=document.createElement("canvas"),h=e.getContext||I.hasCanvasOption(t)&&p.getContext,m=e.naturalWidth||e.width,b=e.naturalHeight||e.height,y=m,S=b;function x(){var e=Math.max((n||y)/y,(r||S)/S);1r.byteLength){console.log("Invalid meta data: Invalid segment size.");break}if(a=p.metaDataParsers.jpeg[t])for(o=0;oe.byteLength))return g.createObjectURL(new Blob([e.buffer.slice(t,t+i)]));console.log("Invalid Exif data: Invalid thumbnail data.")},g.exifTagTypes={1:{getValue:function(e,t){return e.getUint8(t)},size:1},2:{getValue:function(e,t){return String.fromCharCode(e.getUint8(t))},size:1,ascii:!0},3:{getValue:function(e,t,i){return e.getUint16(t,i)},size:2},4:{getValue:function(e,t,i){return e.getUint32(t,i)},size:4},5:{getValue:function(e,t,i){return e.getUint32(t,i)/e.getUint32(t+4,i)},size:8},9:{getValue:function(e,t,i){return e.getInt32(t,i)},size:4},10:{getValue:function(e,t,i){return e.getInt32(t,i)/e.getInt32(t+4,i)},size:8}},g.exifTagTypes[7]=g.exifTagTypes[1],g.getExifValue=function(e,t,i,a,o,n){var r,s,l,c,d,u,f=g.exifTagTypes[a];if(f){if(!((s=4<(r=f.size*o)?t+e.getUint32(i+8,n):i+8)+r>e.byteLength)){if(1===o)return f.getValue(e,s,n);for(l=[],c=0;ce.byteLength)console.log("Invalid Exif data: Invalid directory offset.");else{if(!((r=i+2+12*(n=e.getUint16(i,a)))+4>e.byteLength)){for(s=0;se.byteLength)console.log("Invalid Exif data: Invalid segment size.");else if(0===e.getUint16(t+8)){switch(e.getUint16(l)){case 18761:n=!0;break;case 19789:n=!1;break;default:return void console.log("Invalid Exif data: Invalid byte alignment marker.")}42===e.getUint16(l+2,n)?(r=e.getUint32(l+4,n),a.exif=new g.ExifMap,(r=g.parseExifTags(e,l,l+r,n,a))&&!o.disableExifThumbnail&&(s={exif:{}},r=g.parseExifTags(e,l,l+r,n,s),s.exif[513]&&(a.exif.Thumbnail=g.getExifThumbnail(e,l+s.exif[513],s.exif[514]))),a.exif[34665]&&!o.disableExifSub&&g.parseExifTags(e,l,l+a.exif[34665],n,a),a.exif[34853]&&!o.disableExifGps&&g.parseExifTags(e,l,l+a.exif[34853],n,a)):console.log("Invalid Exif data: Missing TIFF marker.")}else console.log("Invalid Exif data: Missing byte alignment offset.")}},g.metaDataParsers.jpeg[65505].push(g.parseExifData)}),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image","./load-image-exif"],e):"object"==typeof module&&module.exports?e(require("./load-image"),require("./load-image-exif")):e(window.loadImage)}(function(e){"use strict";e.ExifMap.prototype.tags={256:"ImageWidth",257:"ImageHeight",34665:"ExifIFDPointer",34853:"GPSInfoIFDPointer",40965:"InteroperabilityIFDPointer",258:"BitsPerSample",259:"Compression",262:"PhotometricInterpretation",274:"Orientation",277:"SamplesPerPixel",284:"PlanarConfiguration",530:"YCbCrSubSampling",531:"YCbCrPositioning",282:"XResolution",283:"YResolution",296:"ResolutionUnit",273:"StripOffsets",278:"RowsPerStrip",279:"StripByteCounts",513:"JPEGInterchangeFormat",514:"JPEGInterchangeFormatLength",301:"TransferFunction",318:"WhitePoint",319:"PrimaryChromaticities",529:"YCbCrCoefficients",532:"ReferenceBlackWhite",306:"DateTime",270:"ImageDescription",271:"Make",272:"Model",305:"Software",315:"Artist",33432:"Copyright",36864:"ExifVersion",40960:"FlashpixVersion",40961:"ColorSpace",40962:"PixelXDimension",40963:"PixelYDimension",42240:"Gamma",37121:"ComponentsConfiguration",37122:"CompressedBitsPerPixel",37500:"MakerNote",37510:"UserComment",40964:"RelatedSoundFile",36867:"DateTimeOriginal",36868:"DateTimeDigitized",37520:"SubSecTime",37521:"SubSecTimeOriginal",37522:"SubSecTimeDigitized",33434:"ExposureTime",33437:"FNumber",34850:"ExposureProgram",34852:"SpectralSensitivity",34855:"PhotographicSensitivity",34856:"OECF",34864:"SensitivityType",34865:"StandardOutputSensitivity",34866:"RecommendedExposureIndex",34867:"ISOSpeed",34868:"ISOSpeedLatitudeyyy",34869:"ISOSpeedLatitudezzz",37377:"ShutterSpeedValue",37378:"ApertureValue",37379:"BrightnessValue",37380:"ExposureBias",37381:"MaxApertureValue",37382:"SubjectDistance",37383:"MeteringMode",37384:"LightSource",37385:"Flash",37396:"SubjectArea",37386:"FocalLength",41483:"FlashEnergy",41484:"SpatialFrequencyResponse",41486:"FocalPlaneXResolution",41487:"FocalPlaneYResolution",41488:"FocalPlaneResolutionUnit",41492:"SubjectLocation",41493:"ExposureIndex",41495:"SensingMethod",41728:"FileSource",41729:"SceneType",41730:"CFAPattern",41985:"CustomRendered",41986:"ExposureMode",41987:"WhiteBalance",41988:"DigitalZoomRatio",41989:"FocalLengthIn35mmFilm",41990:"SceneCaptureType",41991:"GainControl",41992:"Contrast",41993:"Saturation",41994:"Sharpness",41995:"DeviceSettingDescription",41996:"SubjectDistanceRange",42016:"ImageUniqueID",42032:"CameraOwnerName",42033:"BodySerialNumber",42034:"LensSpecification",42035:"LensMake",42036:"LensModel",42037:"LensSerialNumber",0:"GPSVersionID",1:"GPSLatitudeRef",2:"GPSLatitude",3:"GPSLongitudeRef",4:"GPSLongitude",5:"GPSAltitudeRef",6:"GPSAltitude",7:"GPSTimeStamp",8:"GPSSatellites",9:"GPSStatus",10:"GPSMeasureMode",11:"GPSDOP",12:"GPSSpeedRef",13:"GPSSpeed",14:"GPSTrackRef",15:"GPSTrack",16:"GPSImgDirectionRef",17:"GPSImgDirection",18:"GPSMapDatum",19:"GPSDestLatitudeRef",20:"GPSDestLatitude",21:"GPSDestLongitudeRef",22:"GPSDestLongitude",23:"GPSDestBearingRef",24:"GPSDestBearing",25:"GPSDestDistanceRef",26:"GPSDestDistance",27:"GPSProcessingMethod",28:"GPSAreaInformation",29:"GPSDateStamp",30:"GPSDifferential",31:"GPSHPositioningError"},e.ExifMap.prototype.stringValues={ExposureProgram:{0:"Undefined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"},MeteringMode:{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"},LightSource:{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"},Flash:{0:"Flash did not fire",1:"Flash fired",5:"Strobe return light not detected",7:"Strobe return light detected",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"},SensingMethod:{1:"Undefined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"},SceneCaptureType:{0:"Standard",1:"Landscape",2:"Portrait",3:"Night scene"},SceneType:{1:"Directly photographed"},CustomRendered:{0:"Normal process",1:"Custom process"},WhiteBalance:{0:"Auto white balance",1:"Manual white balance"},GainControl:{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"},Contrast:{0:"Normal",1:"Soft",2:"Hard"},Saturation:{0:"Normal",1:"Low saturation",2:"High saturation"},Sharpness:{0:"Normal",1:"Soft",2:"Hard"},SubjectDistanceRange:{0:"Unknown",1:"Macro",2:"Close view",3:"Distant view"},FileSource:{3:"DSC"},ComponentsConfiguration:{0:"",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"},Orientation:{1:"top-left",2:"top-right",3:"bottom-right",4:"bottom-left",5:"left-top",6:"right-top",7:"right-bottom",8:"left-bottom"}},e.ExifMap.prototype.getText=function(e){var t=this.get(e);switch(e){case"LightSource":case"Flash":case"MeteringMode":case"ExposureProgram":case"SensingMethod":case"SceneCaptureType":case"SceneType":case"CustomRendered":case"WhiteBalance":case"GainControl":case"Contrast":case"Saturation":case"Sharpness":case"SubjectDistanceRange":case"FileSource":case"Orientation":return this.stringValues[e][t];case"ExifVersion":case"FlashpixVersion":if(!t)return;return String.fromCharCode(t[0],t[1],t[2],t[3]);case"ComponentsConfiguration":if(!t)return;return this.stringValues[e][t[0]]+this.stringValues[e][t[1]]+this.stringValues[e][t[2]]+this.stringValues[e][t[3]];case"GPSVersionID":if(!t)return;return t[0]+"."+t[1]+"."+t[2]+"."+t[3]}return String(t)},function(e){var t,i=e.tags,a=e.map;for(t in i)Object.prototype.hasOwnProperty.call(i,t)&&(a[i[t]]=t)}(e.ExifMap.prototype),e.ExifMap.prototype.getAll=function(){var e,t,i={};for(e in this)Object.prototype.hasOwnProperty.call(this,e)&&(t=this.tags[e])&&(i[t]=this.getText(t));return i}}),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image","./load-image-meta"],e):"object"==typeof module&&module.exports?e(require("./load-image"),require("./load-image-meta")):e(window.loadImage)}(function(u){"use strict";u.IptcMap=function(){return this},u.IptcMap.prototype.map={ObjectName:5},u.IptcMap.prototype.get=function(e){return this[e]||this[this.map[e]]},u.parseIptcTags=function(e,t,i,a){function o(e,t,i){for(var a="",o=t;ot.byteLength){console.log("Invalid JPEG metadata: Invalid segment size.");break}if((n=h.jpeg[i])&&!u.disableMetaDataParsers)for(r=0;re.byteLength)console.log("Invalid Exif data: Invalid directory offset.");else{if(!((c=i+2+12*(l=e.getUint16(i,a)))+4>e.byteLength)){for(f=0;fe.byteLength)){if(1===n)return u.getValue(e,o,r);for(s=[],l=0;ll.byteLength)console.log("Invalid Exif data: Invalid segment size.");else if(0===l.getUint16(e+8)){switch(l.getUint16(g)){case 18761:f=!0;break;case 19789:f=!1;break;default:return void console.log("Invalid Exif data: Invalid byte alignment marker.")}42===l.getUint16(g+2,f)?(e=l.getUint32(g+4,f),c.exif=new m,i.disableExifOffsets||(c.exifOffsets=new m,c.exifTiffOffset=g,c.exifLittleEndian=f),(e=A(l,g,g+e,f,c.exif,c.exifOffsets,u,d))&&p(u,d,"ifd1")&&(c.exif.ifd1=e,c.exifOffsets&&(c.exifOffsets.ifd1=g+e)),Object.keys(c.exif.ifds).forEach(function(e){var t,i,a,n,r,o,s;i=e,a=l,n=g,r=f,o=u,s=d,(e=(t=c).exif[i])&&(t.exif[i]=new m(i),t.exifOffsets&&(t.exifOffsets[i]=new m(i)),A(a,n,n+e,r,t.exif[i],t.exifOffsets&&t.exifOffsets[i],o&&o[i],s&&s[i]))}),(e=c.exif.ifd1)&&e[513]&&(e[513]=function(e,t,i){if(i){if(!(t+i>e.byteLength))return new Blob([n.bufferSlice.call(e.buffer,t,t+i)],{type:"image/jpeg"});console.log("Invalid Exif data: Invalid thumbnail data.")}}(l,g+e[513],e[514]))):console.log("Invalid Exif data: Missing TIFF marker.")}else console.log("Invalid Exif data: Missing byte alignment offset.")}},n.metaDataParsers.jpeg[65505].push(n.parseExifData),n.exifWriters={274:function(e,t,i){var a=t.exifOffsets[274];return a&&new DataView(e,a+8,2).setUint16(0,i,t.exifLittleEndian),e}},n.writeExifData=function(e,t,i,a){return n.exifWriters[t.exif.map[i]](e,t,a)},n.ExifMap=m}),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image","./load-image-exif"],e):"object"==typeof module&&module.exports?e(require("./load-image"),require("./load-image-exif")):e(window.loadImage)}(function(e){"use strict";var n=e.ExifMap.prototype;n.tags={256:"ImageWidth",257:"ImageHeight",258:"BitsPerSample",259:"Compression",262:"PhotometricInterpretation",274:"Orientation",277:"SamplesPerPixel",284:"PlanarConfiguration",530:"YCbCrSubSampling",531:"YCbCrPositioning",282:"XResolution",283:"YResolution",296:"ResolutionUnit",273:"StripOffsets",278:"RowsPerStrip",279:"StripByteCounts",513:"JPEGInterchangeFormat",514:"JPEGInterchangeFormatLength",301:"TransferFunction",318:"WhitePoint",319:"PrimaryChromaticities",529:"YCbCrCoefficients",532:"ReferenceBlackWhite",306:"DateTime",270:"ImageDescription",271:"Make",272:"Model",305:"Software",315:"Artist",33432:"Copyright",34665:{36864:"ExifVersion",40960:"FlashpixVersion",40961:"ColorSpace",40962:"PixelXDimension",40963:"PixelYDimension",42240:"Gamma",37121:"ComponentsConfiguration",37122:"CompressedBitsPerPixel",37500:"MakerNote",37510:"UserComment",40964:"RelatedSoundFile",36867:"DateTimeOriginal",36868:"DateTimeDigitized",36880:"OffsetTime",36881:"OffsetTimeOriginal",36882:"OffsetTimeDigitized",37520:"SubSecTime",37521:"SubSecTimeOriginal",37522:"SubSecTimeDigitized",33434:"ExposureTime",33437:"FNumber",34850:"ExposureProgram",34852:"SpectralSensitivity",34855:"PhotographicSensitivity",34856:"OECF",34864:"SensitivityType",34865:"StandardOutputSensitivity",34866:"RecommendedExposureIndex",34867:"ISOSpeed",34868:"ISOSpeedLatitudeyyy",34869:"ISOSpeedLatitudezzz",37377:"ShutterSpeedValue",37378:"ApertureValue",37379:"BrightnessValue",37380:"ExposureBias",37381:"MaxApertureValue",37382:"SubjectDistance",37383:"MeteringMode",37384:"LightSource",37385:"Flash",37396:"SubjectArea",37386:"FocalLength",41483:"FlashEnergy",41484:"SpatialFrequencyResponse",41486:"FocalPlaneXResolution",41487:"FocalPlaneYResolution",41488:"FocalPlaneResolutionUnit",41492:"SubjectLocation",41493:"ExposureIndex",41495:"SensingMethod",41728:"FileSource",41729:"SceneType",41730:"CFAPattern",41985:"CustomRendered",41986:"ExposureMode",41987:"WhiteBalance",41988:"DigitalZoomRatio",41989:"FocalLengthIn35mmFilm",41990:"SceneCaptureType",41991:"GainControl",41992:"Contrast",41993:"Saturation",41994:"Sharpness",41995:"DeviceSettingDescription",41996:"SubjectDistanceRange",42016:"ImageUniqueID",42032:"CameraOwnerName",42033:"BodySerialNumber",42034:"LensSpecification",42035:"LensMake",42036:"LensModel",42037:"LensSerialNumber"},34853:{0:"GPSVersionID",1:"GPSLatitudeRef",2:"GPSLatitude",3:"GPSLongitudeRef",4:"GPSLongitude",5:"GPSAltitudeRef",6:"GPSAltitude",7:"GPSTimeStamp",8:"GPSSatellites",9:"GPSStatus",10:"GPSMeasureMode",11:"GPSDOP",12:"GPSSpeedRef",13:"GPSSpeed",14:"GPSTrackRef",15:"GPSTrack",16:"GPSImgDirectionRef",17:"GPSImgDirection",18:"GPSMapDatum",19:"GPSDestLatitudeRef",20:"GPSDestLatitude",21:"GPSDestLongitudeRef",22:"GPSDestLongitude",23:"GPSDestBearingRef",24:"GPSDestBearing",25:"GPSDestDistanceRef",26:"GPSDestDistance",27:"GPSProcessingMethod",28:"GPSAreaInformation",29:"GPSDateStamp",30:"GPSDifferential",31:"GPSHPositioningError"},40965:{1:"InteroperabilityIndex"}},n.tags.ifd1=n.tags,n.stringValues={ExposureProgram:{0:"Undefined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"},MeteringMode:{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"},LightSource:{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"},Flash:{0:"Flash did not fire",1:"Flash fired",5:"Strobe return light not detected",7:"Strobe return light detected",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"},SensingMethod:{1:"Undefined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"},SceneCaptureType:{0:"Standard",1:"Landscape",2:"Portrait",3:"Night scene"},SceneType:{1:"Directly photographed"},CustomRendered:{0:"Normal process",1:"Custom process"},WhiteBalance:{0:"Auto white balance",1:"Manual white balance"},GainControl:{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"},Contrast:{0:"Normal",1:"Soft",2:"Hard"},Saturation:{0:"Normal",1:"Low saturation",2:"High saturation"},Sharpness:{0:"Normal",1:"Soft",2:"Hard"},SubjectDistanceRange:{0:"Unknown",1:"Macro",2:"Close view",3:"Distant view"},FileSource:{3:"DSC"},ComponentsConfiguration:{0:"",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"},Orientation:{1:"Original",2:"Horizontal flip",3:"Rotate 180° CCW",4:"Vertical flip",5:"Vertical flip + Rotate 90° CW",6:"Rotate 90° CW",7:"Horizontal flip + Rotate 90° CW",8:"Rotate 90° CCW"}},n.getText=function(e){var t=this.get(e);switch(e){case"LightSource":case"Flash":case"MeteringMode":case"ExposureProgram":case"SensingMethod":case"SceneCaptureType":case"SceneType":case"CustomRendered":case"WhiteBalance":case"GainControl":case"Contrast":case"Saturation":case"Sharpness":case"SubjectDistanceRange":case"FileSource":case"Orientation":return this.stringValues[e][t];case"ExifVersion":case"FlashpixVersion":return t?String.fromCharCode(t[0],t[1],t[2],t[3]):void 0;case"ComponentsConfiguration":return t?this.stringValues[e][t[0]]+this.stringValues[e][t[1]]+this.stringValues[e][t[2]]+this.stringValues[e][t[3]]:void 0;case"GPSVersionID":return t?t[0]+"."+t[1]+"."+t[2]+"."+t[3]:void 0}return String(t)},n.getAll=function(){var e,t,i={};for(e in this)Object.prototype.hasOwnProperty.call(this,e)&&((t=this[e])&&t.getAll?i[this.ifds[e].name]=t.getAll():(t=this.tags[e])&&(i[t]=this.getText(t)));return i},n.getName=function(e){var t=this.tags[e];return"object"==typeof t?this.ifds[e].name:t},function(){var e,t,i,a=n.tags;for(e in a)if(Object.prototype.hasOwnProperty.call(a,e))if(t=n.ifds[e])for(e in i=a[e])Object.prototype.hasOwnProperty.call(i,e)&&(t.map[i[e]]=Number(e));else n.map[a[e]]=Number(e)}()}),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image","./load-image-meta"],e):"object"==typeof module&&module.exports?e(require("./load-image"),require("./load-image-meta")):e(window.loadImage)}(function(e){"use strict";function l(){}function u(e,t,i,a,n){return"binary"===t.types[e]?new Blob([i.buffer.slice(a,a+n)]):"Uint16"===t.types[e]?i.getUint16(a):function(e,t,i){for(var a="",n=t+i,r=t;r} Object
+ */
+ function loadImage(file, callback, options) {
+ /**
+ * Promise executor
+ *
+ * @param {Function} resolve Resolution function
+ * @param {Function} reject Rejection function
+ * @returns {HTMLImageElement|FileReader} Object
+ */
+ function executor(resolve, reject) {
+ var img = document.createElement('img')
+ var url
+ /**
+ * Callback for the fetchBlob call.
+ *
+ * @param {HTMLImageElement|HTMLCanvasElement} img Error object
+ * @param {object} data Data object
+ * @returns {undefined} Undefined
+ */
+ function resolveWrapper(img, data) {
+ if (resolve === reject) {
+ // Not using Promises
+ if (resolve) resolve(img, data)
+ return
+ } else if (img instanceof Error) {
+ reject(img)
+ return
+ }
+ data = data || {} // eslint-disable-line no-param-reassign
+ data.image = img
+ resolve(data)
+ }
+ /**
+ * Callback for the fetchBlob call.
+ *
+ * @param {Blob} blob Blob object
+ * @param {Error} err Error object
+ */
+ function fetchBlobCallback(blob, err) {
+ if (err && $.console) console.log(err) // eslint-disable-line no-console
+ if (blob && isInstanceOf('Blob', blob)) {
+ file = blob // eslint-disable-line no-param-reassign
+ url = createObjectURL(file)
+ } else {
+ url = file
+ if (options && options.crossOrigin) {
+ img.crossOrigin = options.crossOrigin
+ }
+ }
+ img.src = url
+ }
+ img.onerror = function (event) {
+ revokeHelper(url, options)
+ if (reject) reject.call(img, event)
+ }
+ img.onload = function () {
+ revokeHelper(url, options)
+ var data = {
+ originalWidth: img.naturalWidth || img.width,
+ originalHeight: img.naturalHeight || img.height
+ }
+ try {
+ loadImage.transform(img, options, resolveWrapper, file, data)
+ } catch (error) {
+ if (reject) reject(error)
+ }
+ }
+ if (typeof file === 'string') {
+ if (loadImage.requiresMetaData(options)) {
+ loadImage.fetchBlob(file, fetchBlobCallback, options)
+ } else {
+ fetchBlobCallback()
+ }
+ return img
+ } else if (isInstanceOf('Blob', file) || isInstanceOf('File', file)) {
+ url = createObjectURL(file)
+ if (url) {
+ img.src = url
+ return img
+ }
+ return readFile(
+ file,
+ function (url) {
+ img.src = url
+ },
+ reject
+ )
+ }
}
- }
-
- loadImage.onload = function(img, event, file, callback, options) {
- revokeHelper(img, options)
- if (callback) {
- loadImage.transform(img, options, callback, file, {
- originalWidth: img.naturalWidth || img.width,
- originalHeight: img.naturalHeight || img.height
- })
+ if ($.Promise && typeof callback !== 'function') {
+ options = callback // eslint-disable-line no-param-reassign
+ return new Promise(executor)
}
+ return executor(callback, callback)
}
- loadImage.createObjectURL = function(file) {
- return urlAPI ? urlAPI.createObjectURL(file) : false
+ // Determines if metadata should be loaded automatically.
+ // Requires the load image meta extension to load metadata.
+ loadImage.requiresMetaData = function (options) {
+ return options && options.meta
}
- loadImage.revokeObjectURL = function(url) {
- return urlAPI ? urlAPI.revokeObjectURL(url) : false
+ // If the callback given to this function returns a blob, it is used as image
+ // source instead of the original url and overrides the file argument used in
+ // the onload and onerror event callbacks:
+ loadImage.fetchBlob = function (url, callback) {
+ callback()
}
- // Loads a given File object via FileReader interface,
- // invokes the callback with the event object (load or error).
- // The result can be read via event.target.result:
- loadImage.readFile = function(file, callback, method) {
- if ($.FileReader) {
- var fileReader = new FileReader()
- fileReader.onload = fileReader.onerror = callback
- // eslint-disable-next-line no-param-reassign
- method = method || 'readAsDataURL'
- if (fileReader[method]) {
- fileReader[method](file)
- return fileReader
- }
- }
- return false
+ loadImage.transform = function (img, options, callback, file, data) {
+ callback(img, data)
}
+ loadImage.global = $
+ loadImage.readFile = readFile
+ loadImage.isInstanceOf = isInstanceOf
+ loadImage.createObjectURL = createObjectURL
+ loadImage.revokeObjectURL = revokeObjectURL
+
if (typeof define === 'function' && define.amd) {
- define(function() {
+ define(function () {
return loadImage
})
} else if (typeof module === 'object' && module.exports) {
diff --git a/test/vendor/canvas-to-blob.js b/js/vendor/canvas-to-blob.js
similarity index 77%
rename from test/vendor/canvas-to-blob.js
rename to js/vendor/canvas-to-blob.js
index 801339c..8cd717b 100644
--- a/test/vendor/canvas-to-blob.js
+++ b/js/vendor/canvas-to-blob.js
@@ -14,14 +14,14 @@
/* global define, Uint8Array, ArrayBuffer, module */
-;(function(window) {
+;(function (window) {
'use strict'
var CanvasPrototype =
window.HTMLCanvasElement && window.HTMLCanvasElement.prototype
var hasBlobConstructor =
window.Blob &&
- (function() {
+ (function () {
try {
return Boolean(new Blob())
} catch (e) {
@@ -31,7 +31,7 @@
var hasArrayBufferViewSupport =
hasBlobConstructor &&
window.Uint8Array &&
- (function() {
+ (function () {
try {
return new Blob([new Uint8Array(100)]).size === 100
} catch (e) {
@@ -49,7 +49,7 @@
window.atob &&
window.ArrayBuffer &&
window.Uint8Array &&
- function(dataURI) {
+ function (dataURI) {
var matches,
mediaType,
isBase64,
@@ -95,9 +95,9 @@
}
if (window.HTMLCanvasElement && !CanvasPrototype.toBlob) {
if (CanvasPrototype.mozGetAsFile) {
- CanvasPrototype.toBlob = function(callback, type, quality) {
+ CanvasPrototype.toBlob = function (callback, type, quality) {
var self = this
- setTimeout(function() {
+ setTimeout(function () {
if (quality && CanvasPrototype.toDataURL && dataURLtoBlob) {
callback(dataURLtoBlob(self.toDataURL(type, quality)))
} else {
@@ -106,16 +106,33 @@
})
}
} else if (CanvasPrototype.toDataURL && dataURLtoBlob) {
- CanvasPrototype.toBlob = function(callback, type, quality) {
- var self = this
- setTimeout(function() {
- callback(dataURLtoBlob(self.toDataURL(type, quality)))
- })
+ if (CanvasPrototype.msToBlob) {
+ CanvasPrototype.toBlob = function (callback, type, quality) {
+ var self = this
+ setTimeout(function () {
+ if (
+ ((type && type !== 'image/png') || quality) &&
+ CanvasPrototype.toDataURL &&
+ dataURLtoBlob
+ ) {
+ callback(dataURLtoBlob(self.toDataURL(type, quality)))
+ } else {
+ callback(self.msToBlob(type))
+ }
+ })
+ }
+ } else {
+ CanvasPrototype.toBlob = function (callback, type, quality) {
+ var self = this
+ setTimeout(function () {
+ callback(dataURLtoBlob(self.toDataURL(type, quality)))
+ })
+ }
}
}
}
if (typeof define === 'function' && define.amd) {
- define(function() {
+ define(function () {
return dataURLtoBlob
})
} else if (typeof module === 'object' && module.exports) {
diff --git a/js/vendor/jquery.Jcrop.js b/js/vendor/jquery.Jcrop.js
index 3e32f04..a879391 100755
--- a/js/vendor/jquery.Jcrop.js
+++ b/js/vendor/jquery.Jcrop.js
@@ -1,9 +1,9 @@
/**
- * jquery.Jcrop.js v0.9.12
+ * jquery.Jcrop.js v0.9.15
* jQuery Image Cropping Plugin - released under MIT License
* Author: Kelly Hallman
* http://github.com/tapmodo/Jcrop
- * Copyright (c) 2008-2013 Tapmodo Interactive LLC {{{
+ * Copyright (c) 2008-2018 Tapmodo Interactive LLC {{{
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
@@ -228,10 +228,10 @@
function newSelection(e) //{{{
{
if (options.disabled) {
- return false;
+ return;
}
if (!options.allowSelect) {
- return false;
+ return;
}
btndown = true;
docOffset = getPos($img);
@@ -329,7 +329,7 @@
boundy = $img.height(),
- $div = $('
').width(boundx).height(boundy).addClass(cssClass('holder')).css({
+ $div = $('
').width(boundx).height(boundy).addClass(cssClass('holder')).css({
position: 'relative',
backgroundColor: options.bgColor
}).insertAfter($origimg).append($img);
@@ -338,19 +338,19 @@
$div.addClass(options.addClass);
}
- var $img2 = $('
'),
+ var $img2 = $('
'),
- $img_holder = $('
')
+ $img_holder = $('
')
.width('100%').height('100%').css({
zIndex: 310,
position: 'absolute',
overflow: 'hidden'
}),
- $hdl_holder = $('
')
+ $hdl_holder = $('
')
.width('100%').height('100%').css('zIndex', 320),
- $sel = $('
')
+ $sel = $('
')
.css({
position: 'absolute',
zIndex: 600
@@ -737,7 +737,7 @@
// Shade Module {{{
var Shade = (function() {
var enabled = false,
- holder = $('
').css({
+ holder = $('
').css({
position: 'absolute',
zIndex: 240,
opacity: 0
@@ -779,7 +779,7 @@
});
}
function createShade() {
- return $('
').css({
+ return $('
').css({
position: 'absolute',
backgroundColor: options.shadeColor||options.bgColor
}).appendTo(holder);
@@ -863,7 +863,7 @@
// Private Methods
function insertBorder(type) //{{{
{
- var jq = $('
').css({
+ var jq = $('
').css({
position: 'absolute',
opacity: options.borderOpacity
}).addClass(cssClass(type));
@@ -873,7 +873,7 @@
//}}}
function dragDiv(ord, zi) //{{{
{
- var jq = $('
').mousedown(createDragger(ord)).css({
+ var jq = $('
').mousedown(createDragger(ord)).css({
cursor: ord + '-resize',
position: 'absolute',
zIndex: zi
@@ -1226,7 +1226,7 @@
width: '12px'
}).addClass('jcrop-keymgr'),
- $keywrap = $('
').css({
+ $keywrap = $('
').css({
position: 'absolute',
overflow: 'hidden'
}).append($keymgr);
diff --git a/js/vendor/jquery.js b/js/vendor/jquery.js
index 9b5206b..7fc60fc 100644
--- a/js/vendor/jquery.js
+++ b/js/vendor/jquery.js
@@ -1,22 +1,20 @@
/*!
- * jQuery JavaScript Library v3.3.1
- * https://jquery.com/
+ * jQuery JavaScript Library v1.12.4
+ * http://jquery.com/
*
* Includes Sizzle.js
- * https://sizzlejs.com/
+ * http://sizzlejs.com/
*
- * Copyright JS Foundation and other contributors
+ * Copyright jQuery Foundation and other contributors
* Released under the MIT license
- * https://jquery.org/license
+ * http://jquery.org/license
*
- * Date: 2018-01-20T17:24Z
+ * Date: 2016-05-20T17:17Z
*/
-( function( global, factory ) {
- "use strict";
+(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
-
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
@@ -37,27 +35,24 @@
}
// Pass this if window is not defined yet
-} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
-
-// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
-// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
-// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
-// enough that all such attempts are guarded in a try block.
-"use strict";
+}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
-var arr = [];
+// Support: Firefox 18+
+// Can't be in strict mode, several libs including ASP.NET trace
+// the stack via arguments.caller.callee and Firefox dies if
+// you try to trace through "use strict" call chains. (#13335)
+//"use strict";
+var deletedIds = [];
var document = window.document;
-var getProto = Object.getPrototypeOf;
+var slice = deletedIds.slice;
-var slice = arr.slice;
+var concat = deletedIds.concat;
-var concat = arr.concat;
+var push = deletedIds.push;
-var push = arr.push;
-
-var indexOf = arr.indexOf;
+var indexOf = deletedIds.indexOf;
var class2type = {};
@@ -65,71 +60,12 @@ var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
-var fnToString = hasOwn.toString;
-
-var ObjectFunctionString = fnToString.call( Object );
-
var support = {};
-var isFunction = function isFunction( obj ) {
-
- // Support: Chrome <=57, Firefox <=52
- // In some browsers, typeof returns "function" for HTML elements
- // (i.e., `typeof document.createElement( "object" ) === "function"`).
- // We don't want to classify *any* DOM node as a function.
- return typeof obj === "function" && typeof obj.nodeType !== "number";
- };
-
-
-var isWindow = function isWindow( obj ) {
- return obj != null && obj === obj.window;
- };
-
-
-
-
- var preservedScriptAttributes = {
- type: true,
- src: true,
- noModule: true
- };
-
- function DOMEval( code, doc, node ) {
- doc = doc || document;
-
- var i,
- script = doc.createElement( "script" );
-
- script.text = code;
- if ( node ) {
- for ( i in preservedScriptAttributes ) {
- if ( node[ i ] ) {
- script[ i ] = node[ i ];
- }
- }
- }
- doc.head.appendChild( script ).parentNode.removeChild( script );
- }
-
-
-function toType( obj ) {
- if ( obj == null ) {
- return obj + "";
- }
-
- // Support: Android <=2.3 only (functionish RegExp)
- return typeof obj === "object" || typeof obj === "function" ?
- class2type[ toString.call( obj ) ] || "object" :
- typeof obj;
-}
-/* global Symbol */
-// Defining this global in .eslintrc.json would create a danger of using the global
-// unguarded in another place, it seems safer to define global only for this module
-
var
- version = "3.3.1",
+ version = "1.12.4",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
@@ -139,9 +75,18 @@ var
return new jQuery.fn.init( selector, context );
},
- // Support: Android <=4.0 only
+ // Support: Android<4.1, IE<9
// Make sure we trim BOM and NBSP
- rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
+ rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
+
+ // Matches dashed string for camelizing
+ rmsPrefix = /^-ms-/,
+ rdashAlpha = /-([\da-z])/gi,
+
+ // Used by jQuery.camelCase as callback to replace()
+ fcamelCase = function( all, letter ) {
+ return letter.toUpperCase();
+ };
jQuery.fn = jQuery.prototype = {
@@ -150,6 +95,9 @@ jQuery.fn = jQuery.prototype = {
constructor: jQuery,
+ // Start with an empty selector
+ selector: "",
+
// The default length of a jQuery object is 0
length: 0,
@@ -160,14 +108,13 @@ jQuery.fn = jQuery.prototype = {
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
+ return num != null ?
- // Return all the elements in a clean array
- if ( num == null ) {
- return slice.call( this );
- }
+ // Return just the one element from the set
+ ( num < 0 ? this[ num + this.length ] : this[ num ] ) :
- // Return just the one element from the set
- return num < 0 ? this[ num + this.length ] : this[ num ];
+ // Return all the elements in a clean array
+ slice.call( this );
},
// Take an array of elements and push it onto the stack
@@ -179,6 +126,7 @@ jQuery.fn = jQuery.prototype = {
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
+ ret.context = this.context;
// Return the newly-formed element set
return ret;
@@ -220,12 +168,12 @@ jQuery.fn = jQuery.prototype = {
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
- sort: arr.sort,
- splice: arr.splice
+ sort: deletedIds.sort,
+ splice: deletedIds.splice
};
jQuery.extend = jQuery.fn.extend = function() {
- var options, name, src, copy, copyIsArray, clone,
+ var src, copyIsArray, copy, name, options, clone,
target = arguments[ 0 ] || {},
i = 1,
length = arguments.length,
@@ -235,17 +183,17 @@ jQuery.extend = jQuery.fn.extend = function() {
if ( typeof target === "boolean" ) {
deep = target;
- // Skip the boolean and the target
+ // skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
- if ( typeof target !== "object" && !isFunction( target ) ) {
+ if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
target = {};
}
- // Extend jQuery itself if only one argument is passed
+ // extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
@@ -268,11 +216,11 @@ jQuery.extend = jQuery.fn.extend = function() {
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
- ( copyIsArray = Array.isArray( copy ) ) ) ) {
+ ( copyIsArray = jQuery.isArray( copy ) ) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
- clone = src && Array.isArray( src ) ? src : [];
+ clone = src && jQuery.isArray( src ) ? src : [];
} else {
clone = src && jQuery.isPlainObject( src ) ? src : {};
@@ -307,42 +255,110 @@ jQuery.extend( {
noop: function() {},
+ // See test/unit/core.js for details concerning isFunction.
+ // Since version 1.3, DOM methods and functions like alert
+ // aren't supported. They return false on IE (#2968).
+ isFunction: function( obj ) {
+ return jQuery.type( obj ) === "function";
+ },
+
+ isArray: Array.isArray || function( obj ) {
+ return jQuery.type( obj ) === "array";
+ },
+
+ isWindow: function( obj ) {
+ /* jshint eqeqeq: false */
+ return obj != null && obj == obj.window;
+ },
+
+ isNumeric: function( obj ) {
+
+ // parseFloat NaNs numeric-cast false positives (null|true|false|"")
+ // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
+ // subtraction forces infinities to NaN
+ // adding 1 corrects loss of precision from parseFloat (#15100)
+ var realStringObj = obj && obj.toString();
+ return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0;
+ },
+
+ isEmptyObject: function( obj ) {
+ var name;
+ for ( name in obj ) {
+ return false;
+ }
+ return true;
+ },
+
isPlainObject: function( obj ) {
- var proto, Ctor;
+ var key;
- // Detect obvious negatives
- // Use toString instead of jQuery.type to catch host objects
- if ( !obj || toString.call( obj ) !== "[object Object]" ) {
+ // Must be an Object.
+ // Because of IE, we also have to check the presence of the constructor property.
+ // Make sure that DOM nodes and window objects don't pass through, as well
+ if ( !obj || jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
- proto = getProto( obj );
+ try {
- // Objects with no prototype (e.g., `Object.create( null )`) are plain
- if ( !proto ) {
- return true;
+ // Not own constructor property must be Object
+ if ( obj.constructor &&
+ !hasOwn.call( obj, "constructor" ) &&
+ !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
+ return false;
+ }
+ } catch ( e ) {
+
+ // IE8,9 Will throw exceptions on certain host objects #9897
+ return false;
+ }
+
+ // Support: IE<9
+ // Handle iteration over inherited properties before own properties.
+ if ( !support.ownFirst ) {
+ for ( key in obj ) {
+ return hasOwn.call( obj, key );
+ }
}
- // Objects with prototype are plain iff they were constructed by a global Object function
- Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
- return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
+ // Own properties are enumerated firstly, so to speed up,
+ // if last one is own, then all properties are own.
+ for ( key in obj ) {}
+
+ return key === undefined || hasOwn.call( obj, key );
},
- isEmptyObject: function( obj ) {
+ type: function( obj ) {
+ if ( obj == null ) {
+ return obj + "";
+ }
+ return typeof obj === "object" || typeof obj === "function" ?
+ class2type[ toString.call( obj ) ] || "object" :
+ typeof obj;
+ },
- /* eslint-disable no-unused-vars */
- // See https://github.com/eslint/eslint/issues/6125
- var name;
+ // Workarounds based on findings by Jim Driscoll
+ // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
+ globalEval: function( data ) {
+ if ( data && jQuery.trim( data ) ) {
- for ( name in obj ) {
- return false;
+ // We use execScript on Internet Explorer
+ // We use an anonymous function so that context is window
+ // rather than jQuery in Firefox
+ ( window.execScript || function( data ) {
+ window[ "eval" ].call( window, data ); // jscs:ignore requireDotNotation
+ } )( data );
}
- return true;
},
- // Evaluates a script in a global context
- globalEval: function( code ) {
- DOMEval( code );
+ // Convert dashed to camelCase; used by the css and data modules
+ // Microsoft forgot to hump their vendor prefix (#9572)
+ camelCase: function( string ) {
+ return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
+ },
+
+ nodeName: function( elem, name ) {
+ return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
each: function( obj, callback ) {
@@ -366,7 +382,7 @@ jQuery.extend( {
return obj;
},
- // Support: Android <=4.0 only
+ // Support: Android<4.1, IE<9
trim: function( text ) {
return text == null ?
"" :
@@ -392,18 +408,43 @@ jQuery.extend( {
},
inArray: function( elem, arr, i ) {
- return arr == null ? -1 : indexOf.call( arr, elem, i );
+ var len;
+
+ if ( arr ) {
+ if ( indexOf ) {
+ return indexOf.call( arr, elem, i );
+ }
+
+ len = arr.length;
+ i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
+
+ for ( ; i < len; i++ ) {
+
+ // Skip accessing in sparse arrays
+ if ( i in arr && arr[ i ] === elem ) {
+ return i;
+ }
+ }
+ }
+
+ return -1;
},
- // Support: Android <=4.0 only, PhantomJS 1 only
- // push.apply(_, arraylike) throws on ancient WebKit
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
- for ( ; j < len; j++ ) {
- first[ i++ ] = second[ j ];
+ while ( j < len ) {
+ first[ i++ ] = second[ j++ ];
+ }
+
+ // Support: IE<9
+ // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
+ if ( len !== len ) {
+ while ( second[ j ] !== undefined ) {
+ first[ i++ ] = second[ j++ ];
+ }
}
first.length = i;
@@ -465,14 +506,53 @@ jQuery.extend( {
// A global GUID counter for objects
guid: 1,
+ // Bind a function to a context, optionally partially applying any
+ // arguments.
+ proxy: function( fn, context ) {
+ var args, proxy, tmp;
+
+ if ( typeof context === "string" ) {
+ tmp = fn[ context ];
+ context = fn;
+ fn = tmp;
+ }
+
+ // Quick check to determine if target is callable, in the spec
+ // this throws a TypeError, but we will just return undefined.
+ if ( !jQuery.isFunction( fn ) ) {
+ return undefined;
+ }
+
+ // Simulated bind
+ args = slice.call( arguments, 2 );
+ proxy = function() {
+ return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
+ };
+
+ // Set the guid of unique handler to the same of original handler, so it can be removed
+ proxy.guid = fn.guid = fn.guid || jQuery.guid++;
+
+ return proxy;
+ },
+
+ now: function() {
+ return +( new Date() );
+ },
+
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
} );
+// JSHint would error on this code due to the Symbol not being defined in ES5.
+// Defining this global in .jshintrc would create a danger of using the global
+// unguarded in another place, it seems safer to just disable JSHint for these
+// three lines.
+/* jshint ignore: start */
if ( typeof Symbol === "function" ) {
- jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
+ jQuery.fn[ Symbol.iterator ] = deletedIds[ Symbol.iterator ];
}
+/* jshint ignore: end */
// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
@@ -482,14 +562,14 @@ function( i, name ) {
function isArrayLike( obj ) {
- // Support: real iOS 8.2 only (not reproducible in simulator)
+ // Support: iOS 8.2 (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = !!obj && "length" in obj && obj.length,
- type = toType( obj );
+ type = jQuery.type( obj );
- if ( isFunction( obj ) || isWindow( obj ) ) {
+ if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
@@ -498,14 +578,14 @@ function isArrayLike( obj ) {
}
var Sizzle =
/*!
- * Sizzle CSS Selector Engine v2.3.3
- * https://sizzlejs.com/
+ * Sizzle CSS Selector Engine v2.2.1
+ * http://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
- * Date: 2016-08-08
+ * Date: 2015-10-17
*/
(function( window ) {
@@ -546,6 +626,9 @@ var i,
return 0;
},
+ // General-purpose constants
+ MAX_NEGATIVE = 1 << 31,
+
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
@@ -554,7 +637,7 @@ var i,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf as it's faster than native
- // https://jsperf.com/thor-indexof-vs-for/5
+ // http://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
@@ -574,7 +657,7 @@ var i,
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
- identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",
+ identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
@@ -631,9 +714,9 @@ var i,
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
+ rescape = /'|\\/g,
- // CSS escapes
- // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
+ // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
@@ -649,39 +732,13 @@ var i,
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
},
- // CSS string/identifier serialization
- // https://drafts.csswg.org/cssom/#common-serializing-idioms
- rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
- fcssescape = function( ch, asCodePoint ) {
- if ( asCodePoint ) {
-
- // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
- if ( ch === "\0" ) {
- return "\uFFFD";
- }
-
- // Control characters and (dependent upon position) numbers get escaped as code points
- return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
- }
-
- // Other potentially-special ASCII characters get backslash-escaped
- return "\\" + ch;
- },
-
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
- },
-
- disabledAncestor = addCombinator(
- function( elem ) {
- return elem.disabled === true && ("form" in elem || "label" in elem);
- },
- { dir: "parentNode", next: "legend" }
- );
+ };
// Optimize for push.apply( _, NodeList )
try {
@@ -713,7 +770,7 @@ try {
}
function Sizzle( selector, context, results, seed ) {
- var m, i, elem, nid, match, groups, newSelector,
+ var m, i, elem, nid, nidselect, match, groups, newSelector,
newContext = context && context.ownerDocument,
// nodeType defaults to 9, since context defaults to document
@@ -806,7 +863,7 @@ function Sizzle( selector, context, results, seed ) {
// Capture the context ID, setting it first if necessary
if ( (nid = context.getAttribute( "id" )) ) {
- nid = nid.replace( rcssescape, fcssescape );
+ nid = nid.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", (nid = expando) );
}
@@ -814,8 +871,9 @@ function Sizzle( selector, context, results, seed ) {
// Prefix every selector in the list
groups = tokenize( selector );
i = groups.length;
+ nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']";
while ( i-- ) {
- groups[i] = "#" + nid + " " + toSelector( groups[i] );
+ groups[i] = nidselect + " " + toSelector( groups[i] );
}
newSelector = groups.join( "," );
@@ -876,22 +934,22 @@ function markFunction( fn ) {
/**
* Support testing using an element
- * @param {Function} fn Passed the created element and returns a boolean result
+ * @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
- var el = document.createElement("fieldset");
+ var div = document.createElement("div");
try {
- return !!fn( el );
+ return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
- if ( el.parentNode ) {
- el.parentNode.removeChild( el );
+ if ( div.parentNode ) {
+ div.parentNode.removeChild( div );
}
// release memory in IE
- el = null;
+ div = null;
}
}
@@ -918,7 +976,8 @@ function addHandle( attrs, handler ) {
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
- a.sourceIndex - b.sourceIndex;
+ ( ~b.sourceIndex || MAX_NEGATIVE ) -
+ ( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
@@ -959,62 +1018,6 @@ function createButtonPseudo( type ) {
};
}
-/**
- * Returns a function to use in pseudos for :enabled/:disabled
- * @param {Boolean} disabled true for :disabled; false for :enabled
- */
-function createDisabledPseudo( disabled ) {
-
- // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
- return function( elem ) {
-
- // Only certain elements can match :enabled or :disabled
- // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
- // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
- if ( "form" in elem ) {
-
- // Check for inherited disabledness on relevant non-disabled elements:
- // * listed form-associated elements in a disabled fieldset
- // https://html.spec.whatwg.org/multipage/forms.html#category-listed
- // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
- // * option elements in a disabled optgroup
- // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
- // All such elements have a "form" property.
- if ( elem.parentNode && elem.disabled === false ) {
-
- // Option elements defer to a parent optgroup if present
- if ( "label" in elem ) {
- if ( "label" in elem.parentNode ) {
- return elem.parentNode.disabled === disabled;
- } else {
- return elem.disabled === disabled;
- }
- }
-
- // Support: IE 6 - 11
- // Use the isDisabled shortcut property to check for disabled fieldset ancestors
- return elem.isDisabled === disabled ||
-
- // Where there is no isDisabled, check manually
- /* jshint -W018 */
- elem.isDisabled !== !disabled &&
- disabledAncestor( elem ) === disabled;
- }
-
- return elem.disabled === disabled;
-
- // Try to winnow out elements that can't be disabled before trusting the disabled property.
- // Some victims get caught in our net (label, legend, menu, track), but it shouldn't
- // even exist on them, let alone have a boolean value.
- } else if ( "label" in elem ) {
- return elem.disabled === disabled;
- }
-
- // Remaining elements are neither :enabled nor :disabled
- return false;
- };
-}
-
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
@@ -1067,7 +1070,7 @@ isXML = Sizzle.isXML = function( elem ) {
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
- var hasCompare, subWindow,
+ var hasCompare, parent,
doc = node ? node.ownerDocument || node : preferredDoc;
// Return early if doc is invalid or already selected
@@ -1082,16 +1085,14 @@ setDocument = Sizzle.setDocument = function( node ) {
// Support: IE 9-11, Edge
// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
- if ( preferredDoc !== document &&
- (subWindow = document.defaultView) && subWindow.top !== subWindow ) {
-
- // Support: IE 11, Edge
- if ( subWindow.addEventListener ) {
- subWindow.addEventListener( "unload", unloadHandler, false );
+ if ( (parent = document.defaultView) && parent.top !== parent ) {
+ // Support: IE 11
+ if ( parent.addEventListener ) {
+ parent.addEventListener( "unload", unloadHandler, false );
// Support: IE 9 - 10 only
- } else if ( subWindow.attachEvent ) {
- subWindow.attachEvent( "onunload", unloadHandler );
+ } else if ( parent.attachEvent ) {
+ parent.attachEvent( "onunload", unloadHandler );
}
}
@@ -1101,18 +1102,18 @@ setDocument = Sizzle.setDocument = function( node ) {
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
- support.attributes = assert(function( el ) {
- el.className = "i";
- return !el.getAttribute("className");
+ support.attributes = assert(function( div ) {
+ div.className = "i";
+ return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
- support.getElementsByTagName = assert(function( el ) {
- el.appendChild( document.createComment("") );
- return !el.getElementsByTagName("*").length;
+ support.getElementsByTagName = assert(function( div ) {
+ div.appendChild( document.createComment("") );
+ return !div.getElementsByTagName("*").length;
});
// Support: IE<9
@@ -1120,28 +1121,32 @@ setDocument = Sizzle.setDocument = function( node ) {
// Support: IE<10
// Check if getElementById returns elements by name
- // The broken getElementById methods don't pick up programmatically-set names,
+ // The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
- support.getById = assert(function( el ) {
- docElem.appendChild( el ).id = expando;
+ support.getById = assert(function( div ) {
+ docElem.appendChild( div ).id = expando;
return !document.getElementsByName || !document.getElementsByName( expando ).length;
});
- // ID filter and find
+ // ID find and filter
if ( support.getById ) {
+ Expr.find["ID"] = function( id, context ) {
+ if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
+ var m = context.getElementById( id );
+ return m ? [ m ] : [];
+ }
+ };
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
- Expr.find["ID"] = function( id, context ) {
- if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
- var elem = context.getElementById( id );
- return elem ? [ elem ] : [];
- }
- };
} else {
+ // Support: IE6/7
+ // getElementById is not reliable as a find shortcut
+ delete Expr.find["ID"];
+
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
@@ -1150,36 +1155,6 @@ setDocument = Sizzle.setDocument = function( node ) {
return node && node.value === attrId;
};
};
-
- // Support: IE 6 - 7 only
- // getElementById is not reliable as a find shortcut
- Expr.find["ID"] = function( id, context ) {
- if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
- var node, i, elems,
- elem = context.getElementById( id );
-
- if ( elem ) {
-
- // Verify the id attribute
- node = elem.getAttributeNode("id");
- if ( node && node.value === id ) {
- return [ elem ];
- }
-
- // Fall back on getElementsByName
- elems = context.getElementsByName( id );
- i = 0;
- while ( (elem = elems[i++]) ) {
- node = elem.getAttributeNode("id");
- if ( node && node.value === id ) {
- return [ elem ];
- }
- }
- }
-
- return [];
- }
- };
}
// Tag
@@ -1233,87 +1208,77 @@ setDocument = Sizzle.setDocument = function( node ) {
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
- // See https://bugs.jquery.com/ticket/13378
+ // See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
- assert(function( el ) {
+ assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
- // https://bugs.jquery.com/ticket/12359
- docElem.appendChild( el ).innerHTML = " " +
+ // http://bugs.jquery.com/ticket/12359
+ docElem.appendChild( div ).innerHTML = " " +
"" +
" ";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
- // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
- if ( el.querySelectorAll("[msallowcapture^='']").length ) {
+ // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
+ if ( div.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
- if ( !el.querySelectorAll("[selected]").length ) {
+ if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
- if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
+ if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
rbuggyQSA.push("~=");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
- if ( !el.querySelectorAll(":checked").length ) {
+ if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
- // In-page `selector#id sibling-combinator selector` fails
- if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
+ // In-page `selector#id sibing-combinator selector` fails
+ if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
- assert(function( el ) {
- el.innerHTML = " " +
- " ";
-
+ assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = document.createElement("input");
input.setAttribute( "type", "hidden" );
- el.appendChild( input ).setAttribute( "name", "D" );
+ div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
- if ( el.querySelectorAll("[name=d]").length ) {
+ if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
- if ( el.querySelectorAll(":enabled").length !== 2 ) {
- rbuggyQSA.push( ":enabled", ":disabled" );
- }
-
- // Support: IE9-11+
- // IE's :disabled selector does not pick up the children of disabled fieldsets
- docElem.appendChild( el ).disabled = true;
- if ( el.querySelectorAll(":disabled").length !== 2 ) {
+ if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
- el.querySelectorAll("*,:x");
+ div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
@@ -1324,14 +1289,14 @@ setDocument = Sizzle.setDocument = function( node ) {
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
- assert(function( el ) {
+ assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
- support.disconnectedMatch = matches.call( el, "*" );
+ support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
- matches.call( el, "[s!='']:x" );
+ matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
@@ -1533,10 +1498,6 @@ Sizzle.attr = function( elem, name ) {
null;
};
-Sizzle.escape = function( sel ) {
- return (sel + "").replace( rcssescape, fcssescape );
-};
-
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
@@ -2004,8 +1965,13 @@ Expr = Sizzle.selectors = {
},
// Boolean properties
- "enabled": createDisabledPseudo( false ),
- "disabled": createDisabledPseudo( true ),
+ "enabled": function( elem ) {
+ return elem.disabled === false;
+ },
+
+ "disabled": function( elem ) {
+ return elem.disabled === true;
+ },
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
@@ -2207,9 +2173,7 @@ function toSelector( tokens ) {
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
- skip = combinator.next,
- key = skip || dir,
- checkNonElements = base && key === "parentNode",
+ checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
@@ -2220,7 +2184,6 @@ function addCombinator( matcher, combinator, base ) {
return matcher( elem, context, xml );
}
}
- return false;
} :
// Check against all ancestor/preceding elements
@@ -2246,16 +2209,14 @@ function addCombinator( matcher, combinator, base ) {
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
- if ( skip && skip === elem.nodeName.toLowerCase() ) {
- elem = elem[ dir ] || elem;
- } else if ( (oldCache = uniqueCache[ key ]) &&
+ if ( (oldCache = uniqueCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
- uniqueCache[ key ] = newCache;
+ uniqueCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
@@ -2265,7 +2226,6 @@ function addCombinator( matcher, combinator, base ) {
}
}
}
- return false;
};
}
@@ -2628,7 +2588,8 @@ select = Sizzle.select = function( selector, context, results, seed ) {
// Reduce context if the leading compound selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
- context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) {
+ support.getById && context.nodeType === 9 && documentIsHTML &&
+ Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
@@ -2698,17 +2659,17 @@ setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
-support.sortDetached = assert(function( el ) {
+support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
- return el.compareDocumentPosition( document.createElement("fieldset") ) & 1;
+ return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
-// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
-if ( !assert(function( el ) {
- el.innerHTML = " ";
- return el.firstChild.getAttribute("href") === "#" ;
+// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
+if ( !assert(function( div ) {
+ div.innerHTML = " ";
+ return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
@@ -2719,10 +2680,10 @@ if ( !assert(function( el ) {
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
-if ( !support.attributes || !assert(function( el ) {
- el.innerHTML = " ";
- el.firstChild.setAttribute( "value", "" );
- return el.firstChild.getAttribute( "value" ) === "";
+if ( !support.attributes || !assert(function( div ) {
+ div.innerHTML = " ";
+ div.firstChild.setAttribute( "value", "" );
+ return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
@@ -2733,8 +2694,8 @@ if ( !support.attributes || !assert(function( el ) {
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
-if ( !assert(function( el ) {
- return el.getAttribute("disabled") == null;
+if ( !assert(function( div ) {
+ return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
@@ -2755,15 +2716,11 @@ return Sizzle;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
-
-// Deprecated
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
-jQuery.escapeSelector = Sizzle.escape;
-
@@ -2798,41 +2755,40 @@ var siblings = function( n, elem ) {
var rneedsContext = jQuery.expr.match.needsContext;
+var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ );
-function nodeName( elem, name ) {
-
- return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
-
-};
-var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );
-
+var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
- if ( isFunction( qualifier ) ) {
+ if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
+ /* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
} );
+
}
- // Single element
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
} );
+
}
- // Arraylike of elements (jQuery, arguments, Array)
- if ( typeof qualifier !== "string" ) {
- return jQuery.grep( elements, function( elem ) {
- return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
- } );
+ if ( typeof qualifier === "string" ) {
+ if ( risSimple.test( qualifier ) ) {
+ return jQuery.filter( qualifier, elements, not );
+ }
+
+ qualifier = jQuery.filter( qualifier, elements );
}
- // Filtered directly for both simple and complex selectors
- return jQuery.filter( qualifier, elements, not );
+ return jQuery.grep( elements, function( elem ) {
+ return ( jQuery.inArray( elem, qualifier ) > -1 ) !== not;
+ } );
}
jQuery.filter = function( expr, elems, not ) {
@@ -2842,20 +2798,19 @@ jQuery.filter = function( expr, elems, not ) {
expr = ":not(" + expr + ")";
}
- if ( elems.length === 1 && elem.nodeType === 1 ) {
- return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [];
- }
-
- return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
- return elem.nodeType === 1;
- } ) );
+ return elems.length === 1 && elem.nodeType === 1 ?
+ jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
+ jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
+ return elem.nodeType === 1;
+ } ) );
};
jQuery.fn.extend( {
find: function( selector ) {
- var i, ret,
- len = this.length,
- self = this;
+ var i,
+ ret = [],
+ self = this,
+ len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter( function() {
@@ -2867,13 +2822,14 @@ jQuery.fn.extend( {
} ) );
}
- ret = this.pushStack( [] );
-
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
- return len > 1 ? jQuery.uniqueSort( ret ) : ret;
+ // Needed because $( selector, context ) becomes $( context ).find( selector )
+ ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
+ ret.selector = this.selector ? this.selector + " " + selector : selector;
+ return ret;
},
filter: function( selector ) {
return this.pushStack( winnow( this, selector || [], false ) );
@@ -2905,8 +2861,7 @@ var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
- // Shortcut simple #id case for speed
- rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
+ rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context, root ) {
var match, elem;
@@ -2916,14 +2871,14 @@ var rootjQuery,
return this;
}
- // Method init() accepts an alternate rootjQuery
+ // init accepts an alternate rootjQuery
// so migrate can support jQuery.sub (gh-2101)
root = root || rootjQuery;
// Handle HTML strings
if ( typeof selector === "string" ) {
- if ( selector[ 0 ] === "<" &&
- selector[ selector.length - 1 ] === ">" &&
+ if ( selector.charAt( 0 ) === "<" &&
+ selector.charAt( selector.length - 1 ) === ">" &&
selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
@@ -2940,7 +2895,7 @@ var rootjQuery,
if ( match[ 1 ] ) {
context = context instanceof jQuery ? context[ 0 ] : context;
- // Option to run scripts is true for back-compat
+ // scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[ 1 ],
@@ -2953,7 +2908,7 @@ var rootjQuery,
for ( match in context ) {
// Properties of context are called as methods if possible
- if ( isFunction( this[ match ] ) ) {
+ if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
@@ -2969,12 +2924,23 @@ var rootjQuery,
} else {
elem = document.getElementById( match[ 2 ] );
- if ( elem ) {
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ if ( elem && elem.parentNode ) {
- // Inject the element directly into the jQuery object
- this[ 0 ] = elem;
+ // Handle the case where IE and Opera return items
+ // by name instead of ID
+ if ( elem.id !== match[ 2 ] ) {
+ return rootjQuery.find( selector );
+ }
+
+ // Otherwise, we inject the element directly into the jQuery object
this.length = 1;
+ this[ 0 ] = elem;
}
+
+ this.context = document;
+ this.selector = selector;
return this;
}
@@ -2990,20 +2956,25 @@ var rootjQuery,
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
- this[ 0 ] = selector;
+ this.context = this[ 0 ] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
- } else if ( isFunction( selector ) ) {
- return root.ready !== undefined ?
+ } else if ( jQuery.isFunction( selector ) ) {
+ return typeof root.ready !== "undefined" ?
root.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
+ if ( selector.selector !== undefined ) {
+ this.selector = selector.selector;
+ this.context = selector.context;
+ }
+
return jQuery.makeArray( selector, this );
};
@@ -3016,7 +2987,7 @@ rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
- // Methods guaranteed to produce a unique set when starting from a unique set
+ // methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
@@ -3026,12 +2997,12 @@ var rparentsprev = /^(?:parents|prev(?:Until|All))/,
jQuery.fn.extend( {
has: function( target ) {
- var targets = jQuery( target, this ),
- l = targets.length;
+ var i,
+ targets = jQuery( target, this ),
+ len = targets.length;
return this.filter( function() {
- var i = 0;
- for ( ; i < l; i++ ) {
+ for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[ i ] ) ) {
return true;
}
@@ -3044,24 +3015,23 @@ jQuery.fn.extend( {
i = 0,
l = this.length,
matched = [],
- targets = typeof selectors !== "string" && jQuery( selectors );
+ pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
+ jQuery( selectors, context || this.context ) :
+ 0;
- // Positional selectors never match, since there's no _selection_ context
- if ( !rneedsContext.test( selectors ) ) {
- for ( ; i < l; i++ ) {
- for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
+ for ( ; i < l; i++ ) {
+ for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
- // Always skip document fragments
- if ( cur.nodeType < 11 && ( targets ?
- targets.index( cur ) > -1 :
+ // Always skip document fragments
+ if ( cur.nodeType < 11 && ( pos ?
+ pos.index( cur ) > -1 :
- // Don't pass non-elements to Sizzle
- cur.nodeType === 1 &&
- jQuery.find.matchesSelector( cur, selectors ) ) ) {
+ // Don't pass non-elements to Sizzle
+ cur.nodeType === 1 &&
+ jQuery.find.matchesSelector( cur, selectors ) ) ) {
- matched.push( cur );
- break;
- }
+ matched.push( cur );
+ break;
}
}
}
@@ -3069,7 +3039,8 @@ jQuery.fn.extend( {
return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
},
- // Determine the position of an element within the set
+ // Determine the position of an element within
+ // the matched set of elements
index: function( elem ) {
// No argument, return index in parent
@@ -3077,17 +3048,16 @@ jQuery.fn.extend( {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
- // Index in selector
+ // index in selector
if ( typeof elem === "string" ) {
- return indexOf.call( jQuery( elem ), this[ 0 ] );
+ return jQuery.inArray( this[ 0 ], jQuery( elem ) );
}
// Locate the position of the desired element
- return indexOf.call( this,
+ return jQuery.inArray(
// If it receives a jQuery object, the first element is used
- elem.jquery ? elem[ 0 ] : elem
- );
+ elem.jquery ? elem[ 0 ] : elem, this );
},
add: function( selector, context ) {
@@ -3106,7 +3076,10 @@ jQuery.fn.extend( {
} );
function sibling( cur, dir ) {
- while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
+ do {
+ cur = cur[ dir ];
+ } while ( cur && cur.nodeType !== 1 );
+
return cur;
}
@@ -3146,55 +3119,46 @@ jQuery.each( {
return siblings( elem.firstChild );
},
contents: function( elem ) {
- if ( nodeName( elem, "iframe" ) ) {
- return elem.contentDocument;
- }
-
- // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only
- // Treat the template element as a regular one in browsers that
- // don't support it.
- if ( nodeName( elem, "template" ) ) {
- elem = elem.content || elem;
- }
-
- return jQuery.merge( [], elem.childNodes );
+ return jQuery.nodeName( elem, "iframe" ) ?
+ elem.contentDocument || elem.contentWindow.document :
+ jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
- var matched = jQuery.map( this, fn, until );
+ var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
- matched = jQuery.filter( selector, matched );
+ ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
- jQuery.uniqueSort( matched );
+ ret = jQuery.uniqueSort( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
- matched.reverse();
+ ret = ret.reverse();
}
}
- return this.pushStack( matched );
+ return this.pushStack( ret );
};
} );
-var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g );
+var rnotwhite = ( /\S+/g );
// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
var object = {};
- jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) {
+ jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
} );
return object;
@@ -3255,7 +3219,7 @@ jQuery.Callbacks = function( options ) {
fire = function() {
// Enforce single-firing
- locked = locked || options.once;
+ locked = options.once;
// Execute callbacks for all pending executions,
// respecting firingIndex overrides and runtime changes
@@ -3311,11 +3275,11 @@ jQuery.Callbacks = function( options ) {
( function add( args ) {
jQuery.each( args, function( _, arg ) {
- if ( isFunction( arg ) ) {
+ if ( jQuery.isFunction( arg ) ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
- } else if ( arg && arg.length && toType( arg ) !== "string" ) {
+ } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {
// Inspect recursively
add( arg );
@@ -3378,9 +3342,9 @@ jQuery.Callbacks = function( options ) {
// Also disable .add unless we have memory (since it would have no effect)
// Abort any pending executions
lock: function() {
- locked = queue = [];
- if ( !memory && !firing ) {
- list = memory = "";
+ locked = true;
+ if ( !memory ) {
+ self.disable();
}
return this;
},
@@ -3417,59 +3381,15 @@ jQuery.Callbacks = function( options ) {
};
-function Identity( v ) {
- return v;
-}
-function Thrower( ex ) {
- throw ex;
-}
-
-function adoptValue( value, resolve, reject, noValue ) {
- var method;
-
- try {
-
- // Check for promise aspect first to privilege synchronous behavior
- if ( value && isFunction( ( method = value.promise ) ) ) {
- method.call( value ).done( resolve ).fail( reject );
-
- // Other thenables
- } else if ( value && isFunction( ( method = value.then ) ) ) {
- method.call( value, resolve, reject );
-
- // Other non-thenables
- } else {
-
- // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer:
- // * false: [ value ].slice( 0 ) => resolve( value )
- // * true: [ value ].slice( 1 ) => resolve()
- resolve.apply( undefined, [ value ].slice( noValue ) );
- }
-
- // For Promises/A+, convert exceptions into rejections
- // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
- // Deferred#then to conditionally suppress rejection.
- } catch ( value ) {
-
- // Support: Android 4.0 only
- // Strict mode functions invoked without .call/.apply get global-object context
- reject.apply( undefined, [ value ] );
- }
-}
-
jQuery.extend( {
Deferred: function( func ) {
var tuples = [
- // action, add listener, callbacks,
- // ... .then handlers, argument index, [final state]
- [ "notify", "progress", jQuery.Callbacks( "memory" ),
- jQuery.Callbacks( "memory" ), 2 ],
- [ "resolve", "done", jQuery.Callbacks( "once memory" ),
- jQuery.Callbacks( "once memory" ), 0, "resolved" ],
- [ "reject", "fail", jQuery.Callbacks( "once memory" ),
- jQuery.Callbacks( "once memory" ), 1, "rejected" ]
+ // action, add listener, listener list, final state
+ [ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ],
+ [ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ],
+ [ "notify", "progress", jQuery.Callbacks( "memory" ) ]
],
state = "pending",
promise = {
@@ -3480,33 +3400,23 @@ jQuery.extend( {
deferred.done( arguments ).fail( arguments );
return this;
},
- "catch": function( fn ) {
- return promise.then( null, fn );
- },
-
- // Keep pipe for back-compat
- pipe: function( /* fnDone, fnFail, fnProgress */ ) {
+ then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
-
return jQuery.Deferred( function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
+ var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
- // Map tuples (progress, done, fail) to arguments (done, fail, progress)
- var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];
-
- // deferred.progress(function() { bind to newDefer or newDefer.notify })
- // deferred.done(function() { bind to newDefer or newDefer.resolve })
- // deferred.fail(function() { bind to newDefer or newDefer.reject })
+ // deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[ 1 ] ]( function() {
var returned = fn && fn.apply( this, arguments );
- if ( returned && isFunction( returned.promise ) ) {
+ if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.progress( newDefer.notify )
.done( newDefer.resolve )
.fail( newDefer.reject );
} else {
newDefer[ tuple[ 0 ] + "With" ](
- this,
+ this === promise ? newDefer.promise() : this,
fn ? [ returned ] : arguments
);
}
@@ -3515,231 +3425,42 @@ jQuery.extend( {
fns = null;
} ).promise();
},
- then: function( onFulfilled, onRejected, onProgress ) {
- var maxDepth = 0;
- function resolve( depth, deferred, handler, special ) {
- return function() {
- var that = this,
- args = arguments,
- mightThrow = function() {
- var returned, then;
-
- // Support: Promises/A+ section 2.3.3.3.3
- // https://promisesaplus.com/#point-59
- // Ignore double-resolution attempts
- if ( depth < maxDepth ) {
- return;
- }
- returned = handler.apply( that, args );
+ // Get a promise for this deferred
+ // If obj is provided, the promise aspect is added to the object
+ promise: function( obj ) {
+ return obj != null ? jQuery.extend( obj, promise ) : promise;
+ }
+ },
+ deferred = {};
- // Support: Promises/A+ section 2.3.1
- // https://promisesaplus.com/#point-48
- if ( returned === deferred.promise() ) {
- throw new TypeError( "Thenable self-resolution" );
- }
+ // Keep pipe for back-compat
+ promise.pipe = promise.then;
- // Support: Promises/A+ sections 2.3.3.1, 3.5
- // https://promisesaplus.com/#point-54
- // https://promisesaplus.com/#point-75
- // Retrieve `then` only once
- then = returned &&
-
- // Support: Promises/A+ section 2.3.4
- // https://promisesaplus.com/#point-64
- // Only check objects and functions for thenability
- ( typeof returned === "object" ||
- typeof returned === "function" ) &&
- returned.then;
-
- // Handle a returned thenable
- if ( isFunction( then ) ) {
-
- // Special processors (notify) just wait for resolution
- if ( special ) {
- then.call(
- returned,
- resolve( maxDepth, deferred, Identity, special ),
- resolve( maxDepth, deferred, Thrower, special )
- );
-
- // Normal processors (resolve) also hook into progress
- } else {
-
- // ...and disregard older resolution values
- maxDepth++;
-
- then.call(
- returned,
- resolve( maxDepth, deferred, Identity, special ),
- resolve( maxDepth, deferred, Thrower, special ),
- resolve( maxDepth, deferred, Identity,
- deferred.notifyWith )
- );
- }
+ // Add list-specific methods
+ jQuery.each( tuples, function( i, tuple ) {
+ var list = tuple[ 2 ],
+ stateString = tuple[ 3 ];
- // Handle all other returned values
- } else {
+ // promise[ done | fail | progress ] = list.add
+ promise[ tuple[ 1 ] ] = list.add;
- // Only substitute handlers pass on context
- // and multiple values (non-spec behavior)
- if ( handler !== Identity ) {
- that = undefined;
- args = [ returned ];
- }
+ // Handle state
+ if ( stateString ) {
+ list.add( function() {
- // Process the value(s)
- // Default process is resolve
- ( special || deferred.resolveWith )( that, args );
- }
- },
-
- // Only normal processors (resolve) catch and reject exceptions
- process = special ?
- mightThrow :
- function() {
- try {
- mightThrow();
- } catch ( e ) {
-
- if ( jQuery.Deferred.exceptionHook ) {
- jQuery.Deferred.exceptionHook( e,
- process.stackTrace );
- }
-
- // Support: Promises/A+ section 2.3.3.3.4.1
- // https://promisesaplus.com/#point-61
- // Ignore post-resolution exceptions
- if ( depth + 1 >= maxDepth ) {
-
- // Only substitute handlers pass on context
- // and multiple values (non-spec behavior)
- if ( handler !== Thrower ) {
- that = undefined;
- args = [ e ];
- }
-
- deferred.rejectWith( that, args );
- }
- }
- };
-
- // Support: Promises/A+ section 2.3.3.3.1
- // https://promisesaplus.com/#point-57
- // Re-resolve promises immediately to dodge false rejection from
- // subsequent errors
- if ( depth ) {
- process();
- } else {
+ // state = [ resolved | rejected ]
+ state = stateString;
- // Call an optional hook to record the stack, in case of exception
- // since it's otherwise lost when execution goes async
- if ( jQuery.Deferred.getStackHook ) {
- process.stackTrace = jQuery.Deferred.getStackHook();
- }
- window.setTimeout( process );
- }
- };
- }
+ // [ reject_list | resolve_list ].disable; progress_list.lock
+ }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
+ }
- return jQuery.Deferred( function( newDefer ) {
-
- // progress_handlers.add( ... )
- tuples[ 0 ][ 3 ].add(
- resolve(
- 0,
- newDefer,
- isFunction( onProgress ) ?
- onProgress :
- Identity,
- newDefer.notifyWith
- )
- );
-
- // fulfilled_handlers.add( ... )
- tuples[ 1 ][ 3 ].add(
- resolve(
- 0,
- newDefer,
- isFunction( onFulfilled ) ?
- onFulfilled :
- Identity
- )
- );
-
- // rejected_handlers.add( ... )
- tuples[ 2 ][ 3 ].add(
- resolve(
- 0,
- newDefer,
- isFunction( onRejected ) ?
- onRejected :
- Thrower
- )
- );
- } ).promise();
- },
-
- // Get a promise for this deferred
- // If obj is provided, the promise aspect is added to the object
- promise: function( obj ) {
- return obj != null ? jQuery.extend( obj, promise ) : promise;
- }
- },
- deferred = {};
-
- // Add list-specific methods
- jQuery.each( tuples, function( i, tuple ) {
- var list = tuple[ 2 ],
- stateString = tuple[ 5 ];
-
- // promise.progress = list.add
- // promise.done = list.add
- // promise.fail = list.add
- promise[ tuple[ 1 ] ] = list.add;
-
- // Handle state
- if ( stateString ) {
- list.add(
- function() {
-
- // state = "resolved" (i.e., fulfilled)
- // state = "rejected"
- state = stateString;
- },
-
- // rejected_callbacks.disable
- // fulfilled_callbacks.disable
- tuples[ 3 - i ][ 2 ].disable,
-
- // rejected_handlers.disable
- // fulfilled_handlers.disable
- tuples[ 3 - i ][ 3 ].disable,
-
- // progress_callbacks.lock
- tuples[ 0 ][ 2 ].lock,
-
- // progress_handlers.lock
- tuples[ 0 ][ 3 ].lock
- );
- }
-
- // progress_handlers.fire
- // fulfilled_handlers.fire
- // rejected_handlers.fire
- list.add( tuple[ 3 ].fire );
-
- // deferred.notify = function() { deferred.notifyWith(...) }
- // deferred.resolve = function() { deferred.resolveWith(...) }
- // deferred.reject = function() { deferred.rejectWith(...) }
+ // deferred[ resolve | reject | notify ]
deferred[ tuple[ 0 ] ] = function() {
- deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments );
+ deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
-
- // deferred.notifyWith = list.fireWith
- // deferred.resolveWith = list.fireWith
- // deferred.rejectWith = list.fireWith
deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
} );
@@ -3756,95 +3477,69 @@ jQuery.extend( {
},
// Deferred helper
- when: function( singleValue ) {
- var
-
- // count of uncompleted subordinates
- remaining = arguments.length,
-
- // count of unprocessed arguments
- i = remaining,
-
- // subordinate fulfillment data
- resolveContexts = Array( i ),
+ when: function( subordinate /* , ..., subordinateN */ ) {
+ var i = 0,
resolveValues = slice.call( arguments ),
+ length = resolveValues.length,
- // the master Deferred
- master = jQuery.Deferred(),
+ // the count of uncompleted subordinates
+ remaining = length !== 1 ||
+ ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
- // subordinate callback factory
- updateFunc = function( i ) {
+ // the master Deferred.
+ // If resolveValues consist of only a single Deferred, just use that.
+ deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
+
+ // Update function for both resolve and progress values
+ updateFunc = function( i, contexts, values ) {
return function( value ) {
- resolveContexts[ i ] = this;
- resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
- if ( !( --remaining ) ) {
- master.resolveWith( resolveContexts, resolveValues );
+ contexts[ i ] = this;
+ values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
+ if ( values === progressValues ) {
+ deferred.notifyWith( contexts, values );
+
+ } else if ( !( --remaining ) ) {
+ deferred.resolveWith( contexts, values );
}
};
- };
-
- // Single- and empty arguments are adopted like Promise.resolve
- if ( remaining <= 1 ) {
- adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject,
- !remaining );
+ },
- // Use .then() to unwrap secondary thenables (cf. gh-3000)
- if ( master.state() === "pending" ||
- isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {
+ progressValues, progressContexts, resolveContexts;
- return master.then();
+ // add listeners to Deferred subordinates; treat others as resolved
+ if ( length > 1 ) {
+ progressValues = new Array( length );
+ progressContexts = new Array( length );
+ resolveContexts = new Array( length );
+ for ( ; i < length; i++ ) {
+ if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
+ resolveValues[ i ].promise()
+ .progress( updateFunc( i, progressContexts, progressValues ) )
+ .done( updateFunc( i, resolveContexts, resolveValues ) )
+ .fail( deferred.reject );
+ } else {
+ --remaining;
+ }
}
}
- // Multiple arguments are aggregated like Promise.all array elements
- while ( i-- ) {
- adoptValue( resolveValues[ i ], updateFunc( i ), master.reject );
+ // if we're not waiting on anything, resolve the master
+ if ( !remaining ) {
+ deferred.resolveWith( resolveContexts, resolveValues );
}
- return master.promise();
+ return deferred.promise();
}
} );
-// These usually indicate a programmer mistake during development,
-// warn about them ASAP rather than swallowing them by default.
-var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;
-
-jQuery.Deferred.exceptionHook = function( error, stack ) {
-
- // Support: IE 8 - 9 only
- // Console exists when dev tools are open, which can happen at any time
- if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) {
- window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack );
- }
-};
-
-
-
-
-jQuery.readyException = function( error ) {
- window.setTimeout( function() {
- throw error;
- } );
-};
-
-
-
-
// The deferred used on DOM ready
-var readyList = jQuery.Deferred();
+var readyList;
jQuery.fn.ready = function( fn ) {
- readyList
- .then( fn )
-
- // Wrap jQuery.readyException in a function so that the lookup
- // happens at the time of error handling instead of callback
- // registration.
- .catch( function( error ) {
- jQuery.readyException( error );
- } );
+ // Add the callback
+ jQuery.ready.promise().done( fn );
return this;
};
@@ -3858,6 +3553,15 @@ jQuery.extend( {
// the ready event fires. See #6781
readyWait: 1,
+ // Hold (or release) the ready event
+ holdReady: function( hold ) {
+ if ( hold ) {
+ jQuery.readyWait++;
+ } else {
+ jQuery.ready( true );
+ }
+ },
+
// Handle when the DOM is ready
ready: function( wait ) {
@@ -3876,398 +3580,500 @@ jQuery.extend( {
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
+
+ // Trigger any bound ready events
+ if ( jQuery.fn.triggerHandler ) {
+ jQuery( document ).triggerHandler( "ready" );
+ jQuery( document ).off( "ready" );
+ }
}
} );
-jQuery.ready.then = readyList.then;
+/**
+ * Clean-up method for dom ready events
+ */
+function detach() {
+ if ( document.addEventListener ) {
+ document.removeEventListener( "DOMContentLoaded", completed );
+ window.removeEventListener( "load", completed );
+
+ } else {
+ document.detachEvent( "onreadystatechange", completed );
+ window.detachEvent( "onload", completed );
+ }
+}
-// The ready event handler and self cleanup method
+/**
+ * The ready event handler and self cleanup method
+ */
function completed() {
- document.removeEventListener( "DOMContentLoaded", completed );
- window.removeEventListener( "load", completed );
- jQuery.ready();
+
+ // readyState === "complete" is good enough for us to call the dom ready in oldIE
+ if ( document.addEventListener ||
+ window.event.type === "load" ||
+ document.readyState === "complete" ) {
+
+ detach();
+ jQuery.ready();
+ }
}
-// Catch cases where $(document).ready() is called
-// after the browser event has already occurred.
-// Support: IE <=9 - 10 only
-// Older IE sometimes signals "interactive" too soon
-if ( document.readyState === "complete" ||
- ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
+jQuery.ready.promise = function( obj ) {
+ if ( !readyList ) {
- // Handle it asynchronously to allow scripts the opportunity to delay ready
- window.setTimeout( jQuery.ready );
+ readyList = jQuery.Deferred();
-} else {
+ // Catch cases where $(document).ready() is called
+ // after the browser event has already occurred.
+ // Support: IE6-10
+ // Older IE sometimes signals "interactive" too soon
+ if ( document.readyState === "complete" ||
+ ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
- // Use the handy event callback
- document.addEventListener( "DOMContentLoaded", completed );
+ // Handle it asynchronously to allow scripts the opportunity to delay ready
+ window.setTimeout( jQuery.ready );
- // A fallback to window.onload, that will always work
- window.addEventListener( "load", completed );
-}
+ // Standards-based browsers support DOMContentLoaded
+ } else if ( document.addEventListener ) {
+ // Use the handy event callback
+ document.addEventListener( "DOMContentLoaded", completed );
+ // A fallback to window.onload, that will always work
+ window.addEventListener( "load", completed );
+ // If IE event model is used
+ } else {
-// Multifunctional method to get and set values of a collection
-// The value/s can optionally be executed if it's a function
-var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
- var i = 0,
- len = elems.length,
- bulk = key == null;
+ // Ensure firing before onload, maybe late but safe also for iframes
+ document.attachEvent( "onreadystatechange", completed );
- // Sets many values
- if ( toType( key ) === "object" ) {
- chainable = true;
- for ( i in key ) {
- access( elems, fn, i, key[ i ], true, emptyGet, raw );
- }
+ // A fallback to window.onload, that will always work
+ window.attachEvent( "onload", completed );
- // Sets one value
- } else if ( value !== undefined ) {
- chainable = true;
+ // If IE and not a frame
+ // continually check to see if the document is ready
+ var top = false;
- if ( !isFunction( value ) ) {
- raw = true;
- }
+ try {
+ top = window.frameElement == null && document.documentElement;
+ } catch ( e ) {}
- if ( bulk ) {
+ if ( top && top.doScroll ) {
+ ( function doScrollCheck() {
+ if ( !jQuery.isReady ) {
- // Bulk operations run against the entire set
- if ( raw ) {
- fn.call( elems, value );
- fn = null;
+ try {
- // ...except when executing function values
- } else {
- bulk = fn;
- fn = function( elem, key, value ) {
- return bulk.call( jQuery( elem ), value );
- };
- }
- }
+ // Use the trick by Diego Perini
+ // http://javascript.nwbox.com/IEContentLoaded/
+ top.doScroll( "left" );
+ } catch ( e ) {
+ return window.setTimeout( doScrollCheck, 50 );
+ }
- if ( fn ) {
- for ( ; i < len; i++ ) {
- fn(
- elems[ i ], key, raw ?
- value :
- value.call( elems[ i ], i, fn( elems[ i ], key ) )
- );
+ // detach all dom ready events
+ detach();
+
+ // and execute any waiting functions
+ jQuery.ready();
+ }
+ } )();
}
}
}
-
- if ( chainable ) {
- return elems;
- }
-
- // Gets
- if ( bulk ) {
- return fn.call( elems );
- }
-
- return len ? fn( elems[ 0 ], key ) : emptyGet;
+ return readyList.promise( obj );
};
+// Kick off the DOM ready check even if the user does not
+jQuery.ready.promise();
-// Matches dashed string for camelizing
-var rmsPrefix = /^-ms-/,
- rdashAlpha = /-([a-z])/g;
-// Used by camelCase as callback to replace()
-function fcamelCase( all, letter ) {
- return letter.toUpperCase();
-}
-// Convert dashed to camelCase; used by the css and data modules
-// Support: IE <=9 - 11, Edge 12 - 15
-// Microsoft forgot to hump their vendor prefix (#9572)
-function camelCase( string ) {
- return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
+
+// Support: IE<9
+// Iteration over object's inherited properties before its own
+var i;
+for ( i in jQuery( support ) ) {
+ break;
}
-var acceptData = function( owner ) {
-
- // Accepts only:
- // - Node
- // - Node.ELEMENT_NODE
- // - Node.DOCUMENT_NODE
- // - Object
- // - Any
- return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
-};
+support.ownFirst = i === "0";
+// Note: most support tests are defined in their respective modules.
+// false until the test is run
+support.inlineBlockNeedsLayout = false;
+// Execute ASAP in case we need to set body.style.zoom
+jQuery( function() {
+ // Minified: var a,b,c,d
+ var val, div, body, container;
-function Data() {
- this.expando = jQuery.expando + Data.uid++;
-}
+ body = document.getElementsByTagName( "body" )[ 0 ];
+ if ( !body || !body.style ) {
-Data.uid = 1;
+ // Return for frameset docs that don't have a body
+ return;
+ }
-Data.prototype = {
+ // Setup
+ div = document.createElement( "div" );
+ container = document.createElement( "div" );
+ container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
+ body.appendChild( container ).appendChild( div );
- cache: function( owner ) {
+ if ( typeof div.style.zoom !== "undefined" ) {
- // Check if the owner object already has a cache
- var value = owner[ this.expando ];
+ // Support: IE<8
+ // Check if natively block-level elements act like inline-block
+ // elements when setting their display to 'inline' and giving
+ // them layout
+ div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";
- // If not, create one
- if ( !value ) {
- value = {};
+ support.inlineBlockNeedsLayout = val = div.offsetWidth === 3;
+ if ( val ) {
- // We can accept data for non-element nodes in modern browsers,
- // but we should not, see #8335.
- // Always return an empty object.
- if ( acceptData( owner ) ) {
+ // Prevent IE 6 from affecting layout for positioned elements #11048
+ // Prevent IE from shrinking the body in IE 7 mode #12869
+ // Support: IE<8
+ body.style.zoom = 1;
+ }
+ }
- // If it is a node unlikely to be stringify-ed or looped over
- // use plain assignment
- if ( owner.nodeType ) {
- owner[ this.expando ] = value;
+ body.removeChild( container );
+} );
- // Otherwise secure it in a non-enumerable property
- // configurable must be true to allow the property to be
- // deleted when data is removed
- } else {
- Object.defineProperty( owner, this.expando, {
- value: value,
- configurable: true
- } );
- }
- }
- }
- return value;
- },
- set: function( owner, data, value ) {
- var prop,
- cache = this.cache( owner );
+( function() {
+ var div = document.createElement( "div" );
- // Handle: [ owner, key, value ] args
- // Always use camelCase key (gh-2257)
- if ( typeof data === "string" ) {
- cache[ camelCase( data ) ] = value;
+ // Support: IE<9
+ support.deleteExpando = true;
+ try {
+ delete div.test;
+ } catch ( e ) {
+ support.deleteExpando = false;
+ }
- // Handle: [ owner, { properties } ] args
- } else {
+ // Null elements to avoid leaks in IE.
+ div = null;
+} )();
+var acceptData = function( elem ) {
+ var noData = jQuery.noData[ ( elem.nodeName + " " ).toLowerCase() ],
+ nodeType = +elem.nodeType || 1;
- // Copy the properties one-by-one to the cache object
- for ( prop in data ) {
- cache[ camelCase( prop ) ] = data[ prop ];
- }
- }
- return cache;
- },
- get: function( owner, key ) {
- return key === undefined ?
- this.cache( owner ) :
+ // Do not set data on non-element DOM nodes because it will not be cleared (#8335).
+ return nodeType !== 1 && nodeType !== 9 ?
+ false :
- // Always use camelCase key (gh-2257)
- owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ];
- },
- access: function( owner, key, value ) {
+ // Nodes accept data unless otherwise specified; rejection can be conditional
+ !noData || noData !== true && elem.getAttribute( "classid" ) === noData;
+};
- // In cases where either:
- //
- // 1. No key was specified
- // 2. A string key was specified, but no value provided
- //
- // Take the "read" path and allow the get method to determine
- // which value to return, respectively either:
- //
- // 1. The entire cache object
- // 2. The data stored at the key
- //
- if ( key === undefined ||
- ( ( key && typeof key === "string" ) && value === undefined ) ) {
- return this.get( owner, key );
- }
- // When the key is not a string, or both a key and value
- // are specified, set or extend (existing objects) with either:
- //
- // 1. An object of properties
- // 2. A key and value
- //
- this.set( owner, key, value );
- // Since the "set" path can have two possible entry points
- // return the expected data based on which path was taken[*]
- return value !== undefined ? value : key;
- },
- remove: function( owner, key ) {
- var i,
- cache = owner[ this.expando ];
+var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
+ rmultiDash = /([A-Z])/g;
- if ( cache === undefined ) {
- return;
- }
+function dataAttr( elem, key, data ) {
- if ( key !== undefined ) {
+ // If nothing was found internally, try to fetch any
+ // data from the HTML5 data-* attribute
+ if ( data === undefined && elem.nodeType === 1 ) {
- // Support array or space separated string of keys
- if ( Array.isArray( key ) ) {
+ var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
- // If key is an array of keys...
- // We always set camelCase keys, so remove that.
- key = key.map( camelCase );
- } else {
- key = camelCase( key );
+ data = elem.getAttribute( name );
- // If a key with the spaces exists, use it.
- // Otherwise, create an array by matching non-whitespace
- key = key in cache ?
- [ key ] :
- ( key.match( rnothtmlwhite ) || [] );
- }
+ if ( typeof data === "string" ) {
+ try {
+ data = data === "true" ? true :
+ data === "false" ? false :
+ data === "null" ? null :
+
+ // Only convert to a number if it doesn't change the string
+ +data + "" === data ? +data :
+ rbrace.test( data ) ? jQuery.parseJSON( data ) :
+ data;
+ } catch ( e ) {}
- i = key.length;
+ // Make sure we set the data so it isn't changed later
+ jQuery.data( elem, key, data );
- while ( i-- ) {
- delete cache[ key[ i ] ];
- }
+ } else {
+ data = undefined;
}
+ }
- // Remove the expando if there's no more data
- if ( key === undefined || jQuery.isEmptyObject( cache ) ) {
+ return data;
+}
- // Support: Chrome <=35 - 45
- // Webkit & Blink performance suffers when deleting properties
- // from DOM nodes, so set to undefined instead
- // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
- if ( owner.nodeType ) {
- owner[ this.expando ] = undefined;
- } else {
- delete owner[ this.expando ];
- }
+// checks a cache object for emptiness
+function isEmptyDataObject( obj ) {
+ var name;
+ for ( name in obj ) {
+
+ // if the public data object is empty, the private is still empty
+ if ( name === "data" && jQuery.isEmptyObject( obj[ name ] ) ) {
+ continue;
+ }
+ if ( name !== "toJSON" ) {
+ return false;
}
- },
- hasData: function( owner ) {
- var cache = owner[ this.expando ];
- return cache !== undefined && !jQuery.isEmptyObject( cache );
}
-};
-var dataPriv = new Data();
-var dataUser = new Data();
+ return true;
+}
+
+function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
+ if ( !acceptData( elem ) ) {
+ return;
+ }
+ var ret, thisCache,
+ internalKey = jQuery.expando,
+ // We have to handle DOM nodes and JS objects differently because IE6-7
+ // can't GC object references properly across the DOM-JS boundary
+ isNode = elem.nodeType,
-// Implementation Summary
-//
-// 1. Enforce API surface and semantic compatibility with 1.9.x branch
-// 2. Improve the module's maintainability by reducing the storage
-// paths to a single mechanism.
-// 3. Use the same single mechanism to support "private" and "user" data.
-// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
-// 5. Avoid exposing implementation details on user objects (eg. expando properties)
-// 6. Provide a clear path for implementation upgrade to WeakMap in 2014
+ // Only DOM nodes need the global jQuery cache; JS object data is
+ // attached directly to the object so GC can occur automatically
+ cache = isNode ? jQuery.cache : elem,
-var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
- rmultiDash = /[A-Z]/g;
+ // Only defining an ID for JS objects if its cache already exists allows
+ // the code to shortcut on the same path as a DOM node with no cache
+ id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
-function getData( data ) {
- if ( data === "true" ) {
- return true;
+ // Avoid doing any more work than we need to when trying to get data on an
+ // object that has no data at all
+ if ( ( !id || !cache[ id ] || ( !pvt && !cache[ id ].data ) ) &&
+ data === undefined && typeof name === "string" ) {
+ return;
}
- if ( data === "false" ) {
- return false;
+ if ( !id ) {
+
+ // Only DOM nodes need a new unique ID for each element since their data
+ // ends up in the global cache
+ if ( isNode ) {
+ id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
+ } else {
+ id = internalKey;
+ }
}
- if ( data === "null" ) {
- return null;
+ if ( !cache[ id ] ) {
+
+ // Avoid exposing jQuery metadata on plain JS objects when the object
+ // is serialized using JSON.stringify
+ cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
- // Only convert to a number if it doesn't change the string
- if ( data === +data + "" ) {
- return +data;
+ // An object can be passed to jQuery.data instead of a key/value pair; this gets
+ // shallow copied over onto the existing cache
+ if ( typeof name === "object" || typeof name === "function" ) {
+ if ( pvt ) {
+ cache[ id ] = jQuery.extend( cache[ id ], name );
+ } else {
+ cache[ id ].data = jQuery.extend( cache[ id ].data, name );
+ }
}
- if ( rbrace.test( data ) ) {
- return JSON.parse( data );
+ thisCache = cache[ id ];
+
+ // jQuery data() is stored in a separate object inside the object's internal data
+ // cache in order to avoid key collisions between internal data and user-defined
+ // data.
+ if ( !pvt ) {
+ if ( !thisCache.data ) {
+ thisCache.data = {};
+ }
+
+ thisCache = thisCache.data;
}
- return data;
-}
+ if ( data !== undefined ) {
+ thisCache[ jQuery.camelCase( name ) ] = data;
+ }
-function dataAttr( elem, key, data ) {
- var name;
+ // Check for both converted-to-camel and non-converted data property names
+ // If a data property was specified
+ if ( typeof name === "string" ) {
- // If nothing was found internally, try to fetch any
- // data from the HTML5 data-* attribute
- if ( data === undefined && elem.nodeType === 1 ) {
- name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase();
- data = elem.getAttribute( name );
+ // First Try to find as-is property data
+ ret = thisCache[ name ];
- if ( typeof data === "string" ) {
- try {
- data = getData( data );
- } catch ( e ) {}
+ // Test for null|undefined property data
+ if ( ret == null ) {
- // Make sure we set the data so it isn't changed later
- dataUser.set( elem, key, data );
- } else {
- data = undefined;
+ // Try to find the camelCased property
+ ret = thisCache[ jQuery.camelCase( name ) ];
}
+ } else {
+ ret = thisCache;
}
- return data;
-}
-jQuery.extend( {
- hasData: function( elem ) {
- return dataUser.hasData( elem ) || dataPriv.hasData( elem );
- },
+ return ret;
+}
- data: function( elem, name, data ) {
- return dataUser.access( elem, name, data );
- },
+function internalRemoveData( elem, name, pvt ) {
+ if ( !acceptData( elem ) ) {
+ return;
+ }
- removeData: function( elem, name ) {
- dataUser.remove( elem, name );
- },
+ var thisCache, i,
+ isNode = elem.nodeType,
- // TODO: Now that all calls to _data and _removeData have been replaced
- // with direct calls to dataPriv methods, these can be deprecated.
- _data: function( elem, name, data ) {
- return dataPriv.access( elem, name, data );
- },
+ // See jQuery.data for more information
+ cache = isNode ? jQuery.cache : elem,
+ id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
- _removeData: function( elem, name ) {
- dataPriv.remove( elem, name );
+ // If there is already no cache entry for this object, there is no
+ // purpose in continuing
+ if ( !cache[ id ] ) {
+ return;
}
-} );
-jQuery.fn.extend( {
- data: function( key, value ) {
- var i, name, data,
- elem = this[ 0 ],
+ if ( name ) {
+
+ thisCache = pvt ? cache[ id ] : cache[ id ].data;
+
+ if ( thisCache ) {
+
+ // Support array or space separated string names for data keys
+ if ( !jQuery.isArray( name ) ) {
+
+ // try the string as a key before any manipulation
+ if ( name in thisCache ) {
+ name = [ name ];
+ } else {
+
+ // split the camel cased version by spaces unless a key with the spaces exists
+ name = jQuery.camelCase( name );
+ if ( name in thisCache ) {
+ name = [ name ];
+ } else {
+ name = name.split( " " );
+ }
+ }
+ } else {
+
+ // If "name" is an array of keys...
+ // When data is initially created, via ("key", "val") signature,
+ // keys will be converted to camelCase.
+ // Since there is no way to tell _how_ a key was added, remove
+ // both plain key and camelCase key. #12786
+ // This will only penalize the array argument path.
+ name = name.concat( jQuery.map( name, jQuery.camelCase ) );
+ }
+
+ i = name.length;
+ while ( i-- ) {
+ delete thisCache[ name[ i ] ];
+ }
+
+ // If there is no data left in the cache, we want to continue
+ // and let the cache object itself get destroyed
+ if ( pvt ? !isEmptyDataObject( thisCache ) : !jQuery.isEmptyObject( thisCache ) ) {
+ return;
+ }
+ }
+ }
+
+ // See jQuery.data for more information
+ if ( !pvt ) {
+ delete cache[ id ].data;
+
+ // Don't destroy the parent cache unless the internal data object
+ // had been the only thing left in it
+ if ( !isEmptyDataObject( cache[ id ] ) ) {
+ return;
+ }
+ }
+
+ // Destroy the cache
+ if ( isNode ) {
+ jQuery.cleanData( [ elem ], true );
+
+ // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
+ /* jshint eqeqeq: false */
+ } else if ( support.deleteExpando || cache != cache.window ) {
+ /* jshint eqeqeq: true */
+ delete cache[ id ];
+
+ // When all else fails, undefined
+ } else {
+ cache[ id ] = undefined;
+ }
+}
+
+jQuery.extend( {
+ cache: {},
+
+ // The following elements (space-suffixed to avoid Object.prototype collisions)
+ // throw uncatchable exceptions if you attempt to set expando properties
+ noData: {
+ "applet ": true,
+ "embed ": true,
+
+ // ...but Flash objects (which have this classid) *can* handle expandos
+ "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
+ },
+
+ hasData: function( elem ) {
+ elem = elem.nodeType ? jQuery.cache[ elem[ jQuery.expando ] ] : elem[ jQuery.expando ];
+ return !!elem && !isEmptyDataObject( elem );
+ },
+
+ data: function( elem, name, data ) {
+ return internalData( elem, name, data );
+ },
+
+ removeData: function( elem, name ) {
+ return internalRemoveData( elem, name );
+ },
+
+ // For internal use only.
+ _data: function( elem, name, data ) {
+ return internalData( elem, name, data, true );
+ },
+
+ _removeData: function( elem, name ) {
+ return internalRemoveData( elem, name, true );
+ }
+} );
+
+jQuery.fn.extend( {
+ data: function( key, value ) {
+ var i, name, data,
+ elem = this[ 0 ],
attrs = elem && elem.attributes;
+ // Special expections of .data basically thwart jQuery.access,
+ // so implement the relevant behavior ourselves
+
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
- data = dataUser.get( elem );
+ data = jQuery.data( elem );
- if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
+ if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
- // Support: IE 11 only
+ // Support: IE11+
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
- name = camelCase( name.slice( 5 ) );
+ name = jQuery.camelCase( name.slice( 5 ) );
dataAttr( elem, name, data[ name ] );
}
}
}
- dataPriv.set( elem, "hasDataAttrs", true );
+ jQuery._data( elem, "parsedAttrs", true );
}
}
@@ -4277,50 +4083,25 @@ jQuery.fn.extend( {
// Sets multiple values
if ( typeof key === "object" ) {
return this.each( function() {
- dataUser.set( this, key );
+ jQuery.data( this, key );
} );
}
- return access( this, function( value ) {
- var data;
-
- // The calling jQuery object (element matches) is not empty
- // (and therefore has an element appears at this[ 0 ]) and the
- // `value` parameter was not undefined. An empty jQuery object
- // will result in `undefined` for elem = this[ 0 ] which will
- // throw an exception if an attempt to read a data cache is made.
- if ( elem && value === undefined ) {
-
- // Attempt to get data from the cache
- // The key will always be camelCased in Data
- data = dataUser.get( elem, key );
- if ( data !== undefined ) {
- return data;
- }
-
- // Attempt to "discover" the data in
- // HTML5 custom data-* attrs
- data = dataAttr( elem, key );
- if ( data !== undefined ) {
- return data;
- }
-
- // We tried really hard, but the data doesn't exist.
- return;
- }
+ return arguments.length > 1 ?
- // Set the data...
+ // Sets one value
this.each( function() {
+ jQuery.data( this, key, value );
+ } ) :
- // We always store the camelCased key
- dataUser.set( this, key, value );
- } );
- }, null, value, arguments.length > 1, null, true );
+ // Gets one value
+ // Try to fetch any internally stored data first
+ elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined;
},
removeData: function( key ) {
return this.each( function() {
- dataUser.remove( this, key );
+ jQuery.removeData( this, key );
} );
}
} );
@@ -4332,12 +4113,12 @@ jQuery.extend( {
if ( elem ) {
type = ( type || "fx" ) + "queue";
- queue = dataPriv.get( elem, type );
+ queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
- if ( !queue || Array.isArray( data ) ) {
- queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
+ if ( !queue || jQuery.isArray( data ) ) {
+ queue = jQuery._data( elem, type, jQuery.makeArray( data ) );
} else {
queue.push( data );
}
@@ -4371,7 +4152,7 @@ jQuery.extend( {
queue.unshift( "inprogress" );
}
- // Clear up the last queue stop function
+ // clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
@@ -4381,12 +4162,14 @@ jQuery.extend( {
}
},
- // Not public - generate a queueHooks object, or return the current one
+ // not intended for public consumption - generates a queueHooks object,
+ // or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
- return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
+ return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks( "once memory" ).add( function() {
- dataPriv.remove( elem, [ type + "queue", key ] );
+ jQuery._removeData( elem, type + "queue" );
+ jQuery._removeData( elem, key );
} )
} );
}
@@ -4411,7 +4194,7 @@ jQuery.fn.extend( {
this.each( function() {
var queue = jQuery.queue( this, type, data );
- // Ensure a hooks for this queue
+ // ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
@@ -4449,7 +4232,7 @@ jQuery.fn.extend( {
type = type || "fx";
while ( i-- ) {
- tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
+ tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
@@ -4459,65 +4242,82 @@ jQuery.fn.extend( {
return defer.promise( obj );
}
} );
-var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
-var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
+( function() {
+ var shrinkWrapBlocksVal;
-var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
+ support.shrinkWrapBlocks = function() {
+ if ( shrinkWrapBlocksVal != null ) {
+ return shrinkWrapBlocksVal;
+ }
-var isHiddenWithinTree = function( elem, el ) {
+ // Will be changed later if needed.
+ shrinkWrapBlocksVal = false;
- // isHiddenWithinTree might be called from jQuery#filter function;
- // in that case, element will be second argument
- elem = el || elem;
+ // Minified: var b,c,d
+ var div, body, container;
+
+ body = document.getElementsByTagName( "body" )[ 0 ];
+ if ( !body || !body.style ) {
+
+ // Test fired too early or in an unsupported environment, exit.
+ return;
+ }
+
+ // Setup
+ div = document.createElement( "div" );
+ container = document.createElement( "div" );
+ container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
+ body.appendChild( container ).appendChild( div );
- // Inline style trumps all
- return elem.style.display === "none" ||
- elem.style.display === "" &&
+ // Support: IE6
+ // Check if elements with layout shrink-wrap their children
+ if ( typeof div.style.zoom !== "undefined" ) {
- // Otherwise, check computed style
- // Support: Firefox <=43 - 45
- // Disconnected elements can have computed display: none, so first confirm that elem is
- // in the document.
- jQuery.contains( elem.ownerDocument, elem ) &&
+ // Reset CSS: box-sizing; display; margin; border
+ div.style.cssText =
- jQuery.css( elem, "display" ) === "none";
+ // Support: Firefox<29, Android 2.3
+ // Vendor-prefix box-sizing
+ "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
+ "box-sizing:content-box;display:block;margin:0;border:0;" +
+ "padding:1px;width:1px;zoom:1";
+ div.appendChild( document.createElement( "div" ) ).style.width = "5px";
+ shrinkWrapBlocksVal = div.offsetWidth !== 3;
+ }
+
+ body.removeChild( container );
+
+ return shrinkWrapBlocksVal;
};
-var swap = function( elem, options, callback, args ) {
- var ret, name,
- old = {};
+} )();
+var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
- // Remember the old values, and insert the new ones
- for ( name in options ) {
- old[ name ] = elem.style[ name ];
- elem.style[ name ] = options[ name ];
- }
+var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
- ret = callback.apply( elem, args || [] );
- // Revert the old values
- for ( name in options ) {
- elem.style[ name ] = old[ name ];
- }
+var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
- return ret;
-};
+var isHidden = function( elem, el ) {
+ // isHidden might be called from jQuery#filter function;
+ // in that case, element will be second argument
+ elem = el || elem;
+ return jQuery.css( elem, "display" ) === "none" ||
+ !jQuery.contains( elem.ownerDocument, elem );
+ };
function adjustCSS( elem, prop, valueParts, tween ) {
- var adjusted, scale,
+ var adjusted,
+ scale = 1,
maxIterations = 20,
currentValue = tween ?
- function() {
- return tween.cur();
- } :
- function() {
- return jQuery.css( elem, prop, "" );
- },
+ function() { return tween.cur(); } :
+ function() { return jQuery.css( elem, prop, "" ); },
initial = currentValue(),
unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
@@ -4527,33 +4327,30 @@ function adjustCSS( elem, prop, valueParts, tween ) {
if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
- // Support: Firefox <=54
- // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144)
- initial = initial / 2;
-
// Trust units reported by jQuery.css
unit = unit || initialInUnit[ 3 ];
+ // Make sure we update the tween properties later on
+ valueParts = valueParts || [];
+
// Iteratively approximate from a nonzero starting point
initialInUnit = +initial || 1;
- while ( maxIterations-- ) {
-
- // Evaluate and update our best guess (doubling guesses that zero out).
- // Finish if the scale equals or crosses 1 (making the old*new product non-positive).
- jQuery.style( elem, prop, initialInUnit + unit );
- if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) {
- maxIterations = 0;
- }
- initialInUnit = initialInUnit / scale;
+ do {
- }
+ // If previous iteration zeroed out, double until we get *something*.
+ // Use string for doubling so we don't accidentally see scale as unchanged below
+ scale = scale || ".5";
- initialInUnit = initialInUnit * 2;
- jQuery.style( elem, prop, initialInUnit + unit );
+ // Adjust and apply
+ initialInUnit = initialInUnit / scale;
+ jQuery.style( elem, prop, initialInUnit + unit );
- // Make sure we update the tween properties later on
- valueParts = valueParts || [];
+ // Update scale, tolerating zero or NaN from tween.cur()
+ // Break the loop if scale is unchanged or perfect, or if we've just had enough.
+ } while (
+ scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations
+ );
}
if ( valueParts ) {
@@ -4573,126 +4370,175 @@ function adjustCSS( elem, prop, valueParts, tween ) {
}
-var defaultDisplayMap = {};
+// Multifunctional method to get and set values of a collection
+// The value/s can optionally be executed if it's a function
+var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
+ var i = 0,
+ length = elems.length,
+ bulk = key == null;
+
+ // Sets many values
+ if ( jQuery.type( key ) === "object" ) {
+ chainable = true;
+ for ( i in key ) {
+ access( elems, fn, i, key[ i ], true, emptyGet, raw );
+ }
+
+ // Sets one value
+ } else if ( value !== undefined ) {
+ chainable = true;
+
+ if ( !jQuery.isFunction( value ) ) {
+ raw = true;
+ }
+
+ if ( bulk ) {
+
+ // Bulk operations run against the entire set
+ if ( raw ) {
+ fn.call( elems, value );
+ fn = null;
-function getDefaultDisplay( elem ) {
- var temp,
- doc = elem.ownerDocument,
- nodeName = elem.nodeName,
- display = defaultDisplayMap[ nodeName ];
+ // ...except when executing function values
+ } else {
+ bulk = fn;
+ fn = function( elem, key, value ) {
+ return bulk.call( jQuery( elem ), value );
+ };
+ }
+ }
- if ( display ) {
- return display;
+ if ( fn ) {
+ for ( ; i < length; i++ ) {
+ fn(
+ elems[ i ],
+ key,
+ raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) )
+ );
+ }
+ }
}
- temp = doc.body.appendChild( doc.createElement( nodeName ) );
- display = jQuery.css( temp, "display" );
+ return chainable ?
+ elems :
- temp.parentNode.removeChild( temp );
+ // Gets
+ bulk ?
+ fn.call( elems ) :
+ length ? fn( elems[ 0 ], key ) : emptyGet;
+};
+var rcheckableType = ( /^(?:checkbox|radio)$/i );
- if ( display === "none" ) {
- display = "block";
- }
- defaultDisplayMap[ nodeName ] = display;
+var rtagName = ( /<([\w:-]+)/ );
- return display;
-}
+var rscriptType = ( /^$|\/(?:java|ecma)script/i );
-function showHide( elements, show ) {
- var display, elem,
- values = [],
- index = 0,
- length = elements.length;
+var rleadingWhitespace = ( /^\s+/ );
- // Determine new display value for elements that need to change
- for ( ; index < length; index++ ) {
- elem = elements[ index ];
- if ( !elem.style ) {
- continue;
- }
+var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|" +
+ "details|dialog|figcaption|figure|footer|header|hgroup|main|" +
+ "mark|meter|nav|output|picture|progress|section|summary|template|time|video";
- display = elem.style.display;
- if ( show ) {
- // Since we force visibility upon cascade-hidden elements, an immediate (and slow)
- // check is required in this first loop unless we have a nonempty display value (either
- // inline or about-to-be-restored)
- if ( display === "none" ) {
- values[ index ] = dataPriv.get( elem, "display" ) || null;
- if ( !values[ index ] ) {
- elem.style.display = "";
- }
- }
- if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
- values[ index ] = getDefaultDisplay( elem );
- }
- } else {
- if ( display !== "none" ) {
- values[ index ] = "none";
- // Remember what we're overwriting
- dataPriv.set( elem, "display", display );
- }
- }
- }
+function createSafeFragment( document ) {
+ var list = nodeNames.split( "|" ),
+ safeFrag = document.createDocumentFragment();
- // Set the display of the elements in a second loop to avoid constant reflow
- for ( index = 0; index < length; index++ ) {
- if ( values[ index ] != null ) {
- elements[ index ].style.display = values[ index ];
+ if ( safeFrag.createElement ) {
+ while ( list.length ) {
+ safeFrag.createElement(
+ list.pop()
+ );
}
}
-
- return elements;
+ return safeFrag;
}
-jQuery.fn.extend( {
- show: function() {
- return showHide( this, true );
- },
- hide: function() {
- return showHide( this );
- },
- toggle: function( state ) {
- if ( typeof state === "boolean" ) {
- return state ? this.show() : this.hide();
- }
- return this.each( function() {
- if ( isHiddenWithinTree( this ) ) {
- jQuery( this ).show();
- } else {
- jQuery( this ).hide();
- }
- } );
- }
-} );
-var rcheckableType = ( /^(?:checkbox|radio)$/i );
+( function() {
+ var div = document.createElement( "div" ),
+ fragment = document.createDocumentFragment(),
+ input = document.createElement( "input" );
+
+ // Setup
+ div.innerHTML = " a ";
+
+ // IE strips leading whitespace when .innerHTML is used
+ support.leadingWhitespace = div.firstChild.nodeType === 3;
+
+ // Make sure that tbody elements aren't automatically inserted
+ // IE will insert them into empty tables
+ support.tbody = !div.getElementsByTagName( "tbody" ).length;
+
+ // Make sure that link elements get serialized correctly by innerHTML
+ // This requires a wrapper element in IE
+ support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;
+
+ // Makes sure cloning an html5 element does not cause problems
+ // Where outerHTML is undefined, this still works
+ support.html5Clone =
+ document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav>";
+
+ // Check if a disconnected checkbox will retain its checked
+ // value of true after appended to the DOM (IE6/7)
+ input.type = "checkbox";
+ input.checked = true;
+ fragment.appendChild( input );
+ support.appendChecked = input.checked;
+
+ // Make sure textarea (and checkbox) defaultValue is properly cloned
+ // Support: IE6-IE11+
+ div.innerHTML = "";
+ support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
+
+ // #11217 - WebKit loses check when the name is after the checked attribute
+ fragment.appendChild( div );
+
+ // Support: Windows Web Apps (WWA)
+ // `name` and `type` must use .setAttribute for WWA (#14901)
+ input = document.createElement( "input" );
+ input.setAttribute( "type", "radio" );
+ input.setAttribute( "checked", "checked" );
+ input.setAttribute( "name", "t" );
+
+ div.appendChild( input );
-var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i );
+ // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
+ // old WebKit doesn't clone checked state correctly in fragments
+ support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
-var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i );
+ // Support: IE<9
+ // Cloned elements keep attachEvent handlers, we use addEventListener on IE9+
+ support.noCloneEvent = !!div.addEventListener;
+ // Support: IE<9
+ // Since attributes and properties are the same in IE,
+ // cleanData must set properties to undefined rather than use removeAttribute
+ div[ jQuery.expando ] = 1;
+ support.attributes = !div.getAttribute( jQuery.expando );
+} )();
// We have to close these tags to support XHTML (#13200)
var wrapMap = {
-
- // Support: IE <=9 only
option: [ 1, "", " " ],
+ legend: [ 1, "", " " ],
+ area: [ 1, "", " " ],
- // XHTML parsers do not magically insert elements in the
- // same way that tag soup parsers do. So we cannot shorten
- // this by omitting or other required elements.
+ // Support: IE8
+ param: [ 1, "", " " ],
thead: [ 1, "" ],
- col: [ 2, "" ],
tr: [ 2, "" ],
+ col: [ 2, "" ],
td: [ 3, "" ],
- _default: [ 0, "", "" ]
+ // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
+ // unless wrapped in a div with non-breaking characters in front of it.
+ _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X", "
" ]
};
-// Support: IE <=9 only
+// Support: IE8-IE9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
@@ -4700,52 +4546,66 @@ wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
-
- // Support: IE <=9 - 11 only
- // Use typeof to avoid zero-argument method invocation on host objects (#15151)
- var ret;
-
- if ( typeof context.getElementsByTagName !== "undefined" ) {
- ret = context.getElementsByTagName( tag || "*" );
-
- } else if ( typeof context.querySelectorAll !== "undefined" ) {
- ret = context.querySelectorAll( tag || "*" );
-
- } else {
- ret = [];
- }
-
- if ( tag === undefined || tag && nodeName( context, tag ) ) {
- return jQuery.merge( [ context ], ret );
+ var elems, elem,
+ i = 0,
+ found = typeof context.getElementsByTagName !== "undefined" ?
+ context.getElementsByTagName( tag || "*" ) :
+ typeof context.querySelectorAll !== "undefined" ?
+ context.querySelectorAll( tag || "*" ) :
+ undefined;
+
+ if ( !found ) {
+ for ( found = [], elems = context.childNodes || context;
+ ( elem = elems[ i ] ) != null;
+ i++
+ ) {
+ if ( !tag || jQuery.nodeName( elem, tag ) ) {
+ found.push( elem );
+ } else {
+ jQuery.merge( found, getAll( elem, tag ) );
+ }
+ }
}
- return ret;
+ return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
+ jQuery.merge( [ context ], found ) :
+ found;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
- var i = 0,
- l = elems.length;
-
- for ( ; i < l; i++ ) {
- dataPriv.set(
- elems[ i ],
+ var elem,
+ i = 0;
+ for ( ; ( elem = elems[ i ] ) != null; i++ ) {
+ jQuery._data(
+ elem,
"globalEval",
- !refElements || dataPriv.get( refElements[ i ], "globalEval" )
+ !refElements || jQuery._data( refElements[ i ], "globalEval" )
);
}
}
-var rhtml = /<|?\w+;/;
+var rhtml = /<|?\w+;/,
+ rtbody = / from table fragments
+ if ( !support.tbody ) {
+
+ // String was a , *may* have spurious
+ elem = tag === "table" && !rtbody.test( elem ) ?
+ tmp.firstChild :
+
+ // String was a bare or
+ wrap[ 1 ] === "" && !rtbody.test( elem ) ?
+ tmp :
+ 0;
+
+ j = elem && elem.childNodes.length;
+ while ( j-- ) {
+ if ( jQuery.nodeName( ( tbody = elem.childNodes[ j ] ), "tbody" ) &&
+ !tbody.childNodes.length ) {
+
+ elem.removeChild( tbody );
+ }
+ }
+ }
- // Remember the top-level container
- tmp = fragment.firstChild;
+ jQuery.merge( nodes, tmp.childNodes );
- // Ensure the created nodes are orphaned (#12392)
+ // Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
+
+ // Fix #12392 for oldIE
+ while ( tmp.firstChild ) {
+ tmp.removeChild( tmp.firstChild );
+ }
+
+ // Remember the top-level container for proper cleanup
+ tmp = safe.lastChild;
}
}
}
- // Remove wrapper from fragment
- fragment.textContent = "";
+ // Fix #11356: Clear elements from fragment
+ if ( tmp ) {
+ safe.removeChild( tmp );
+ }
+
+ // Reset defaultChecked for any radios and checkboxes
+ // about to be appended to the DOM in IE 6/7 (#8060)
+ if ( !support.appendChecked ) {
+ jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
+ }
i = 0;
while ( ( elem = nodes[ i++ ] ) ) {
@@ -4802,13 +4698,14 @@ function buildFragment( elems, context, scripts, selection, ignored ) {
if ( ignored ) {
ignored.push( elem );
}
+
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
- tmp = getAll( fragment.appendChild( elem ), "script" );
+ tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
@@ -4826,41 +4723,37 @@ function buildFragment( elems, context, scripts, selection, ignored ) {
}
}
- return fragment;
+ tmp = null;
+
+ return safe;
}
( function() {
- var fragment = document.createDocumentFragment(),
- div = fragment.appendChild( document.createElement( "div" ) ),
- input = document.createElement( "input" );
+ var i, eventName,
+ div = document.createElement( "div" );
- // Support: Android 4.0 - 4.3 only
- // Check state lost if the name is set (#11217)
- // Support: Windows Web Apps (WWA)
- // `name` and `type` must use .setAttribute for WWA (#14901)
- input.setAttribute( "type", "radio" );
- input.setAttribute( "checked", "checked" );
- input.setAttribute( "name", "t" );
+ // Support: IE<9 (lack submit/change bubble), Firefox (lack focus(in | out) events)
+ for ( i in { submit: true, change: true, focusin: true } ) {
+ eventName = "on" + i;
- div.appendChild( input );
+ if ( !( support[ i ] = eventName in window ) ) {
- // Support: Android <=4.1 only
- // Older WebKit doesn't clone checked state correctly in fragments
- support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
+ // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
+ div.setAttribute( eventName, "t" );
+ support[ i ] = div.attributes[ eventName ].expando === false;
+ }
+ }
- // Support: IE <=11 only
- // Make sure textarea (and checkbox) defaultValue is properly cloned
- div.innerHTML = "";
- support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
+ // Null elements to avoid leaks in IE.
+ div = null;
} )();
-var documentElement = document.documentElement;
-
-var
+var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
+ rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
function returnTrue() {
@@ -4871,7 +4764,7 @@ function returnFalse() {
return false;
}
-// Support: IE <=9 only
+// Support: IE9
// See #13393 for more info
function safeActiveElement() {
try {
@@ -4949,11 +4842,10 @@ jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
-
- var handleObjIn, eventHandle, tmp,
- events, t, handleObj,
- special, handlers, type, namespaces, origType,
- elemData = dataPriv.get( elem );
+ var tmp, events, t, handleObjIn,
+ special, eventHandle, handleObj,
+ handlers, type, namespaces, origType,
+ elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
@@ -4967,12 +4859,6 @@ jQuery.event = {
selector = handleObjIn.selector;
}
- // Ensure that invalid selectors throw exceptions at attach time
- // Evaluate against documentElement in case elem is a non-element node (e.g., document)
- if ( selector ) {
- jQuery.find.matchesSelector( documentElement, selector );
- }
-
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
@@ -4987,13 +4873,19 @@ jQuery.event = {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
- return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
- jQuery.event.dispatch.apply( elem, arguments ) : undefined;
+ return typeof jQuery !== "undefined" &&
+ ( !e || jQuery.event.triggered !== e.type ) ?
+ jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
+ undefined;
};
+
+ // Add elem as a property of the handle fn to prevent a memory leak
+ // with IE non-native events
+ eventHandle.elem = elem;
}
// Handle multiple events separated by a space
- types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
+ types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
@@ -5031,12 +4923,16 @@ jQuery.event = {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
- // Only use addEventListener if the special events handler returns false
+ // Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup ||
special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
+ // Bind the global event handler to the element
if ( elem.addEventListener ) {
- elem.addEventListener( type, eventHandle );
+ elem.addEventListener( type, eventHandle, false );
+
+ } else if ( elem.attachEvent ) {
+ elem.attachEvent( "on" + type, eventHandle );
}
}
}
@@ -5060,22 +4956,24 @@ jQuery.event = {
jQuery.event.global[ type ] = true;
}
+ // Nullify elem to prevent memory leaks in IE
+ elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
-
- var j, origCount, tmp,
- events, t, handleObj,
- special, handlers, type, namespaces, origType,
- elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );
+ var j, handleObj, tmp,
+ origCount, t, events,
+ special, handlers, type,
+ namespaces, origType,
+ elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !( events = elemData.events ) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
- types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
+ types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
@@ -5130,29 +5028,174 @@ jQuery.event = {
}
}
- // Remove data and the expando if it's no longer used
+ // Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
- dataPriv.remove( elem, "handle events" );
+ delete elemData.handle;
+
+ // removeData also checks for emptiness and clears the expando if empty
+ // so use it instead of delete
+ jQuery._removeData( elem, "events" );
+ }
+ },
+
+ trigger: function( event, data, elem, onlyHandlers ) {
+ var handle, ontype, cur,
+ bubbleType, special, tmp, i,
+ eventPath = [ elem || document ],
+ type = hasOwn.call( event, "type" ) ? event.type : event,
+ namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];
+
+ cur = tmp = elem = elem || document;
+
+ // Don't do events on text and comment nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ // focus/blur morphs to focusin/out; ensure we're not firing them right now
+ if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
+ return;
+ }
+
+ if ( type.indexOf( "." ) > -1 ) {
+
+ // Namespaced trigger; create a regexp to match event type in handle()
+ namespaces = type.split( "." );
+ type = namespaces.shift();
+ namespaces.sort();
+ }
+ ontype = type.indexOf( ":" ) < 0 && "on" + type;
+
+ // Caller can pass in a jQuery.Event object, Object, or just an event type string
+ event = event[ jQuery.expando ] ?
+ event :
+ new jQuery.Event( type, typeof event === "object" && event );
+
+ // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
+ event.isTrigger = onlyHandlers ? 2 : 3;
+ event.namespace = namespaces.join( "." );
+ event.rnamespace = event.namespace ?
+ new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
+ null;
+
+ // Clean up the event in case it is being reused
+ event.result = undefined;
+ if ( !event.target ) {
+ event.target = elem;
+ }
+
+ // Clone any incoming data and prepend the event, creating the handler arg list
+ data = data == null ?
+ [ event ] :
+ jQuery.makeArray( data, [ event ] );
+
+ // Allow special events to draw outside the lines
+ special = jQuery.event.special[ type ] || {};
+ if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
+ return;
+ }
+
+ // Determine event propagation path in advance, per W3C events spec (#9951)
+ // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
+ if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
+
+ bubbleType = special.delegateType || type;
+ if ( !rfocusMorph.test( bubbleType + type ) ) {
+ cur = cur.parentNode;
+ }
+ for ( ; cur; cur = cur.parentNode ) {
+ eventPath.push( cur );
+ tmp = cur;
+ }
+
+ // Only add window if we got to document (e.g., not plain obj or detached DOM)
+ if ( tmp === ( elem.ownerDocument || document ) ) {
+ eventPath.push( tmp.defaultView || tmp.parentWindow || window );
+ }
+ }
+
+ // Fire handlers on the event path
+ i = 0;
+ while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
+
+ event.type = i > 1 ?
+ bubbleType :
+ special.bindType || type;
+
+ // jQuery handler
+ handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] &&
+ jQuery._data( cur, "handle" );
+
+ if ( handle ) {
+ handle.apply( cur, data );
+ }
+
+ // Native handler
+ handle = ontype && cur[ ontype ];
+ if ( handle && handle.apply && acceptData( cur ) ) {
+ event.result = handle.apply( cur, data );
+ if ( event.result === false ) {
+ event.preventDefault();
+ }
+ }
+ }
+ event.type = type;
+
+ // If nobody prevented the default action, do it now
+ if ( !onlyHandlers && !event.isDefaultPrevented() ) {
+
+ if (
+ ( !special._default ||
+ special._default.apply( eventPath.pop(), data ) === false
+ ) && acceptData( elem )
+ ) {
+
+ // Call a native DOM method on the target with the same name name as the event.
+ // Can't use an .isFunction() check here because IE6/7 fails that test.
+ // Don't do default actions on window, that's where global variables be (#6170)
+ if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
+
+ // Don't re-trigger an onFOO event when we call its FOO() method
+ tmp = elem[ ontype ];
+
+ if ( tmp ) {
+ elem[ ontype ] = null;
+ }
+
+ // Prevent re-triggering of the same event, since we already bubbled it above
+ jQuery.event.triggered = type;
+ try {
+ elem[ type ]();
+ } catch ( e ) {
+
+ // IE<9 dies on focus/blur to hidden element (#1486,#12518)
+ // only reproducible on winXP IE8 native, not IE9 in IE8 mode
+ }
+ jQuery.event.triggered = undefined;
+
+ if ( tmp ) {
+ elem[ ontype ] = tmp;
+ }
+ }
+ }
}
+
+ return event.result;
},
- dispatch: function( nativeEvent ) {
+ dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
- var event = jQuery.event.fix( nativeEvent );
+ event = jQuery.event.fix( event );
- var i, j, ret, matched, handleObj, handlerQueue,
- args = new Array( arguments.length ),
- handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [],
+ var i, j, ret, matched, handleObj,
+ handlerQueue = [],
+ args = slice.call( arguments ),
+ handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[ 0 ] = event;
-
- for ( i = 1; i < arguments.length; i++ ) {
- args[ i ] = arguments[ i ];
- }
-
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
@@ -5201,95 +5244,160 @@ jQuery.event = {
},
handlers: function( event, handlers ) {
- var i, handleObj, sel, matchedHandlers, matchedSelectors,
+ var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
+ // Support (at least): Chrome, IE9
// Find delegate handlers
- if ( delegateCount &&
-
- // Support: IE <=9
- // Black-hole SVG instance trees (trac-13180)
- cur.nodeType &&
-
- // Support: Firefox <=42
- // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
- // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
- // Support: IE 11 only
- // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
- !( event.type === "click" && event.button >= 1 ) ) {
+ // Black-hole SVG instance trees (#13180)
+ //
+ // Support: Firefox<=42+
+ // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343)
+ if ( delegateCount && cur.nodeType &&
+ ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) {
- for ( ; cur !== this; cur = cur.parentNode || this ) {
+ /* jshint eqeqeq: false */
+ for ( ; cur != this; cur = cur.parentNode || this ) {
+ /* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
- if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) {
- matchedHandlers = [];
- matchedSelectors = {};
+ if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) {
+ matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
- if ( matchedSelectors[ sel ] === undefined ) {
- matchedSelectors[ sel ] = handleObj.needsContext ?
+ if ( matches[ sel ] === undefined ) {
+ matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) > -1 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
- if ( matchedSelectors[ sel ] ) {
- matchedHandlers.push( handleObj );
+ if ( matches[ sel ] ) {
+ matches.push( handleObj );
}
}
- if ( matchedHandlers.length ) {
- handlerQueue.push( { elem: cur, handlers: matchedHandlers } );
+ if ( matches.length ) {
+ handlerQueue.push( { elem: cur, handlers: matches } );
}
}
}
}
// Add the remaining (directly-bound) handlers
- cur = this;
if ( delegateCount < handlers.length ) {
- handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } );
+ handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } );
}
return handlerQueue;
},
- addProp: function( name, hook ) {
- Object.defineProperty( jQuery.Event.prototype, name, {
- enumerable: true,
- configurable: true,
+ fix: function( event ) {
+ if ( event[ jQuery.expando ] ) {
+ return event;
+ }
- get: isFunction( hook ) ?
- function() {
- if ( this.originalEvent ) {
- return hook( this.originalEvent );
- }
- } :
- function() {
- if ( this.originalEvent ) {
- return this.originalEvent[ name ];
- }
- },
+ // Create a writable copy of the event object and normalize some properties
+ var i, prop, copy,
+ type = event.type,
+ originalEvent = event,
+ fixHook = this.fixHooks[ type ];
- set: function( value ) {
- Object.defineProperty( this, name, {
- enumerable: true,
- configurable: true,
- writable: true,
- value: value
- } );
+ if ( !fixHook ) {
+ this.fixHooks[ type ] = fixHook =
+ rmouseEvent.test( type ) ? this.mouseHooks :
+ rkeyEvent.test( type ) ? this.keyHooks :
+ {};
+ }
+ copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
+
+ event = new jQuery.Event( originalEvent );
+
+ i = copy.length;
+ while ( i-- ) {
+ prop = copy[ i ];
+ event[ prop ] = originalEvent[ prop ];
+ }
+
+ // Support: IE<9
+ // Fix target property (#1925)
+ if ( !event.target ) {
+ event.target = originalEvent.srcElement || document;
+ }
+
+ // Support: Safari 6-8+
+ // Target should not be a text node (#504, #13143)
+ if ( event.target.nodeType === 3 ) {
+ event.target = event.target.parentNode;
+ }
+
+ // Support: IE<9
+ // For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
+ event.metaKey = !!event.metaKey;
+
+ return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
+ },
+
+ // Includes some event props shared by KeyEvent and MouseEvent
+ props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " +
+ "metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ),
+
+ fixHooks: {},
+
+ keyHooks: {
+ props: "char charCode key keyCode".split( " " ),
+ filter: function( event, original ) {
+
+ // Add which for key events
+ if ( event.which == null ) {
+ event.which = original.charCode != null ? original.charCode : original.keyCode;
}
- } );
+
+ return event;
+ }
},
- fix: function( originalEvent ) {
- return originalEvent[ jQuery.expando ] ?
- originalEvent :
- new jQuery.Event( originalEvent );
+ mouseHooks: {
+ props: ( "button buttons clientX clientY fromElement offsetX offsetY " +
+ "pageX pageY screenX screenY toElement" ).split( " " ),
+ filter: function( event, original ) {
+ var body, eventDoc, doc,
+ button = original.button,
+ fromElement = original.fromElement;
+
+ // Calculate pageX/Y if missing and clientX/Y available
+ if ( event.pageX == null && original.clientX != null ) {
+ eventDoc = event.target.ownerDocument || document;
+ doc = eventDoc.documentElement;
+ body = eventDoc.body;
+
+ event.pageX = original.clientX +
+ ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
+ ( doc && doc.clientLeft || body && body.clientLeft || 0 );
+ event.pageY = original.clientY +
+ ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
+ ( doc && doc.clientTop || body && body.clientTop || 0 );
+ }
+
+ // Add relatedTarget, if necessary
+ if ( !event.relatedTarget && fromElement ) {
+ event.relatedTarget = fromElement === event.target ?
+ original.toElement :
+ fromElement;
+ }
+
+ // Add which for click: 1 === left; 2 === middle; 3 === right
+ // Note: button is not normalized, so don't use it
+ if ( !event.which && button !== undefined ) {
+ event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
+ }
+
+ return event;
+ }
},
special: {
@@ -5303,8 +5411,15 @@ jQuery.event = {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
- this.focus();
- return false;
+ try {
+ this.focus();
+ return false;
+ } catch ( e ) {
+
+ // Support: IE<9
+ // If we error on focus to hidden element (#1486, #12518),
+ // let .trigger() run the handlers
+ }
}
},
delegateType: "focusin"
@@ -5322,7 +5437,7 @@ jQuery.event = {
// For checkbox, fire native event so checked state will be right
trigger: function() {
- if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) {
+ if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
@@ -5330,7 +5445,7 @@ jQuery.event = {
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
- return nodeName( event.target, "a" );
+ return jQuery.nodeName( event.target, "a" );
}
},
@@ -5344,17 +5459,60 @@ jQuery.event = {
}
}
}
- }
-};
+ },
+
+ // Piggyback on a donor event to simulate a different one
+ simulate: function( type, elem, event ) {
+ var e = jQuery.extend(
+ new jQuery.Event(),
+ event,
+ {
+ type: type,
+ isSimulated: true
+
+ // Previously, `originalEvent: {}` was set here, so stopPropagation call
+ // would not be triggered on donor event, since in our own
+ // jQuery.event.stopPropagation function we had a check for existence of
+ // originalEvent.stopPropagation method, so, consequently it would be a noop.
+ //
+ // Guard for simulated events was moved to jQuery.event.stopPropagation function
+ // since `originalEvent` should point to the original event for the
+ // constancy with other events and for more focused logic
+ }
+ );
-jQuery.removeEvent = function( elem, type, handle ) {
+ jQuery.event.trigger( e, null, elem );
- // This "if" is needed for plain objects
- if ( elem.removeEventListener ) {
- elem.removeEventListener( type, handle );
+ if ( e.isDefaultPrevented() ) {
+ event.preventDefault();
+ }
}
};
+jQuery.removeEvent = document.removeEventListener ?
+ function( elem, type, handle ) {
+
+ // This "if" is needed for plain objects
+ if ( elem.removeEventListener ) {
+ elem.removeEventListener( type, handle );
+ }
+ } :
+ function( elem, type, handle ) {
+ var name = "on" + type;
+
+ if ( elem.detachEvent ) {
+
+ // #8545, #7054, preventing memory leaks for custom events in IE6-8
+ // detachEvent needed property on element, by name of that event,
+ // to properly expose it to GC
+ if ( typeof elem[ name ] === "undefined" ) {
+ elem[ name ] = null;
+ }
+
+ elem.detachEvent( name, handle );
+ }
+ };
+
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
@@ -5372,21 +5530,11 @@ jQuery.Event = function( src, props ) {
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
- // Support: Android <=2.3 only
+ // Support: IE < 9, Android < 4.0
src.returnValue === false ?
returnTrue :
returnFalse;
- // Create target properties
- // Support: Safari <=6 - 7 only
- // Target should not be a text node (#504, #13143)
- this.target = ( src.target && src.target.nodeType === 3 ) ?
- src.target.parentNode :
- src.target;
-
- this.currentTarget = src.currentTarget;
- this.relatedTarget = src.relatedTarget;
-
// Event type
} else {
this.type = src;
@@ -5398,28 +5546,36 @@ jQuery.Event = function( src, props ) {
}
// Create a timestamp if incoming event doesn't have one
- this.timeStamp = src && src.timeStamp || Date.now();
+ this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
-// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
constructor: jQuery.Event,
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
- isSimulated: false,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
+ if ( !e ) {
+ return;
+ }
- if ( e && !this.isSimulated ) {
+ // If preventDefault exists, run it on the original event
+ if ( e.preventDefault ) {
e.preventDefault();
+
+ // Support: IE
+ // Otherwise set the returnValue property of the original event to false
+ } else {
+ e.returnValue = false;
}
},
stopPropagation: function() {
@@ -5427,16 +5583,25 @@ jQuery.Event.prototype = {
this.isPropagationStopped = returnTrue;
- if ( e && !this.isSimulated ) {
+ if ( !e || this.isSimulated ) {
+ return;
+ }
+
+ // If stopPropagation exists, run it on the original event
+ if ( e.stopPropagation ) {
e.stopPropagation();
}
+
+ // Support: IE
+ // Set the cancelBubble property of the original event to true
+ e.cancelBubble = true;
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
- if ( e && !this.isSimulated ) {
+ if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
@@ -5444,74 +5609,13 @@ jQuery.Event.prototype = {
}
};
-// Includes all common event props including KeyEvent and MouseEvent specific props
-jQuery.each( {
- altKey: true,
- bubbles: true,
- cancelable: true,
- changedTouches: true,
- ctrlKey: true,
- detail: true,
- eventPhase: true,
- metaKey: true,
- pageX: true,
- pageY: true,
- shiftKey: true,
- view: true,
- "char": true,
- charCode: true,
- key: true,
- keyCode: true,
- button: true,
- buttons: true,
- clientX: true,
- clientY: true,
- offsetX: true,
- offsetY: true,
- pointerId: true,
- pointerType: true,
- screenX: true,
- screenY: true,
- targetTouches: true,
- toElement: true,
- touches: true,
-
- which: function( event ) {
- var button = event.button;
-
- // Add which for key events
- if ( event.which == null && rkeyEvent.test( event.type ) ) {
- return event.charCode != null ? event.charCode : event.keyCode;
- }
-
- // Add which for click: 1 === left; 2 === middle; 3 === right
- if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) {
- if ( button & 1 ) {
- return 1;
- }
-
- if ( button & 2 ) {
- return 3;
- }
-
- if ( button & 4 ) {
- return 2;
- }
-
- return 0;
- }
-
- return event.which;
- }
-}, jQuery.event.addProp );
-
// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
-// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
+// https://code.google.com/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
mouseenter: "mouseover",
@@ -5541,6 +5645,171 @@ jQuery.each( {
};
} );
+// IE submit delegation
+if ( !support.submit ) {
+
+ jQuery.event.special.submit = {
+ setup: function() {
+
+ // Only need this for delegated form submit events
+ if ( jQuery.nodeName( this, "form" ) ) {
+ return false;
+ }
+
+ // Lazy-add a submit handler when a descendant form may potentially be submitted
+ jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
+
+ // Node name check avoids a VML-related crash in IE (#9807)
+ var elem = e.target,
+ form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ?
+
+ // Support: IE <=8
+ // We use jQuery.prop instead of elem.form
+ // to allow fixing the IE8 delegated submit issue (gh-2332)
+ // by 3rd party polyfills/workarounds.
+ jQuery.prop( elem, "form" ) :
+ undefined;
+
+ if ( form && !jQuery._data( form, "submit" ) ) {
+ jQuery.event.add( form, "submit._submit", function( event ) {
+ event._submitBubble = true;
+ } );
+ jQuery._data( form, "submit", true );
+ }
+ } );
+
+ // return undefined since we don't need an event listener
+ },
+
+ postDispatch: function( event ) {
+
+ // If form was submitted by the user, bubble the event up the tree
+ if ( event._submitBubble ) {
+ delete event._submitBubble;
+ if ( this.parentNode && !event.isTrigger ) {
+ jQuery.event.simulate( "submit", this.parentNode, event );
+ }
+ }
+ },
+
+ teardown: function() {
+
+ // Only need this for delegated form submit events
+ if ( jQuery.nodeName( this, "form" ) ) {
+ return false;
+ }
+
+ // Remove delegated handlers; cleanData eventually reaps submit handlers attached above
+ jQuery.event.remove( this, "._submit" );
+ }
+ };
+}
+
+// IE change delegation and checkbox/radio fix
+if ( !support.change ) {
+
+ jQuery.event.special.change = {
+
+ setup: function() {
+
+ if ( rformElems.test( this.nodeName ) ) {
+
+ // IE doesn't fire change on a check/radio until blur; trigger it on click
+ // after a propertychange. Eat the blur-change in special.change.handle.
+ // This still fires onchange a second time for check/radio after blur.
+ if ( this.type === "checkbox" || this.type === "radio" ) {
+ jQuery.event.add( this, "propertychange._change", function( event ) {
+ if ( event.originalEvent.propertyName === "checked" ) {
+ this._justChanged = true;
+ }
+ } );
+ jQuery.event.add( this, "click._change", function( event ) {
+ if ( this._justChanged && !event.isTrigger ) {
+ this._justChanged = false;
+ }
+
+ // Allow triggered, simulated change events (#11500)
+ jQuery.event.simulate( "change", this, event );
+ } );
+ }
+ return false;
+ }
+
+ // Delegated event; lazy-add a change handler on descendant inputs
+ jQuery.event.add( this, "beforeactivate._change", function( e ) {
+ var elem = e.target;
+
+ if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "change" ) ) {
+ jQuery.event.add( elem, "change._change", function( event ) {
+ if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
+ jQuery.event.simulate( "change", this.parentNode, event );
+ }
+ } );
+ jQuery._data( elem, "change", true );
+ }
+ } );
+ },
+
+ handle: function( event ) {
+ var elem = event.target;
+
+ // Swallow native change events from checkbox/radio, we already triggered them above
+ if ( this !== elem || event.isSimulated || event.isTrigger ||
+ ( elem.type !== "radio" && elem.type !== "checkbox" ) ) {
+
+ return event.handleObj.handler.apply( this, arguments );
+ }
+ },
+
+ teardown: function() {
+ jQuery.event.remove( this, "._change" );
+
+ return !rformElems.test( this.nodeName );
+ }
+ };
+}
+
+// Support: Firefox
+// Firefox doesn't have focus(in | out) events
+// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
+//
+// Support: Chrome, Safari
+// focus(in | out) events fire after focus & blur events,
+// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
+// Related ticket - https://code.google.com/p/chromium/issues/detail?id=449857
+if ( !support.focusin ) {
+ jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {
+
+ // Attach a single capturing handler on the document while someone wants focusin/focusout
+ var handler = function( event ) {
+ jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
+ };
+
+ jQuery.event.special[ fix ] = {
+ setup: function() {
+ var doc = this.ownerDocument || this,
+ attaches = jQuery._data( doc, fix );
+
+ if ( !attaches ) {
+ doc.addEventListener( orig, handler, true );
+ }
+ jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
+ },
+ teardown: function() {
+ var doc = this.ownerDocument || this,
+ attaches = jQuery._data( doc, fix ) - 1;
+
+ if ( !attaches ) {
+ doc.removeEventListener( orig, handler, true );
+ jQuery._removeData( doc, fix );
+ } else {
+ jQuery._data( doc, fix, attaches );
+ }
+ }
+ };
+ } );
+}
+
jQuery.fn.extend( {
on: function( types, selector, data, fn ) {
@@ -5584,97 +5853,154 @@ jQuery.fn.extend( {
return this.each( function() {
jQuery.event.remove( this, types, fn, selector );
} );
+ },
+
+ trigger: function( type, data ) {
+ return this.each( function() {
+ jQuery.event.trigger( type, data, this );
+ } );
+ },
+ triggerHandler: function( type, data ) {
+ var elem = this[ 0 ];
+ if ( elem ) {
+ return jQuery.event.trigger( type, data, elem, true );
+ }
}
} );
-var
-
- /* eslint-disable max-len */
-
- // See https://github.com/eslint/eslint/issues/3229
- rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,
-
- /* eslint-enable */
+var rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
+ rnoshimcache = new RegExp( "<(?:" + nodeNames + ")[\\s/>]", "i" ),
+ rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,
- // Support: IE <=10 - 11, Edge 12 - 13 only
+ // Support: IE 10-11, Edge 10240+
// In IE/Edge using regex groups here causes severe slowdowns.
// See https://connect.microsoft.com/IE/feedback/details/1736512/
rnoInnerhtml = /
-
+
+
diff --git a/test/test.js b/test/test.js
index fc1d1a7..2a8ea21 100644
--- a/test/test.js
+++ b/test/test.js
@@ -9,44 +9,108 @@
* https://opensource.org/licenses/MIT
*/
-/* global describe, it */
+/* global describe, before, after, it, Promise, ArrayBuffer */
/* eslint-disable no-unused-expressions */
-;(function(expect, loadImage) {
+;(function (expect, loadImage) {
'use strict'
- var canCreateBlob = !!window.dataURLtoBlob
- // 80x60px GIF image (color black, base64 data):
+ var browser = {
+ canCreateBlob: !!window.dataURLtoBlob
+ }
+
+ // black+white 60x40 GIF
+ // Image data layout (B=black, F=white), scaled to 3x2:
+ // BFF
+ // BBB
var b64DataGIF =
- 'R0lGODdhUAA8AIABAAAAAP///ywAAAAAUAA8AAACS4SPqcvtD6' +
- 'OctNqLs968+w+G4kiW5omm6sq27gvH8kzX9o3n+s73/g8MCofE' +
- 'ovGITCqXzKbzCY1Kp9Sq9YrNarfcrvcLDovH5PKsAAA7'
+ 'R0lGODlhPAAoAPECAAAAAP///wAAAAAAACH5BAUAAAIALAAAAAA8ACgAQAJihI+Zwe0Po3Sq' +
+ '1okztvzoDwbdSJbmiaaqGbbTCrjyA9f2jef6Ts6+uPrNYEIZsdg6IkG8pvMJjUqnVOgypLxm' +
+ 'stpXsLv9gr2q8UZshnDTjTUbWH7TqvS6/Y7P6/f8vv9vVwAAOw=='
var imageUrlGIF = 'data:image/gif;base64,' + b64DataGIF
- var blobGIF = canCreateBlob && window.dataURLtoBlob(imageUrlGIF)
- // 2x1px JPEG (color white, with the Exif orientation flag set to 6 and the
- // IPTC ObjectName (2:5) set to 'objectname'):
+ var blobGIF = browser.canCreateBlob && window.dataURLtoBlob(imageUrlGIF)
+ var fileGIF
+ try {
+ fileGIF = new File([blobGIF], 'image.gif')
+ } catch (_) {
+ // No File constructor support
+ }
+
+ // black+white 3x2 GIF
+ // Image data layout (B=black, F=white):
+ // BFF
+ // BBB
+ var b64DataGIF2 =
+ 'R0lGODdhAwACAPEAAAAAAP///yZFySZFySH5BAEAAAIALAAAAAADAAIAAAIDRAJZADs='
+ var imageUrlGIF2 = 'data:image/gif;base64,' + b64DataGIF2
+ var blobGIF2 = browser.canCreateBlob && window.dataURLtoBlob(imageUrlGIF2)
+
+ // black+white 3x2 JPEG, with the following meta information set:
+ // - EXIF Orientation: 6 (Rotated 90° CCW)
+ // - IPTC ObjectName: blueimp.net
+ // Meta information has been set via exiftool (exiftool.org):
+ // exiftool -all= -Orientation#=6 -YCbCrPositioning= -ResolutionUnit= \
+ // -YResolution= -XResolution= -ObjectName=blueimp.net black+white-3x2.jpg
+ // Image data layout (B=black, F=white):
+ // BFF
+ // BBB
var b64DataJPEG =
- '/9j/4AAQSkZJRgABAQEAYABgAAD/4QAiRXhpZgAASUkqAAgAAAABABIBAwABAAAA' +
- 'BgASAAAAAAD/7QAsUGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAA8cAgUACm9iamVj' +
- 'dG5hbWUA/9sAQwABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB' +
- 'AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB/9sAQwEBAQEBAQEBAQEBAQEBAQEB' +
- 'AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB' +
- '/8AAEQgAAQACAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYH' +
- 'CAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGh' +
- 'CCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldY' +
- 'WVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1' +
- 'tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8B' +
- 'AAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAEC' +
- 'dwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBka' +
- 'JicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWG' +
- 'h4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ' +
- '2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A/v4ooooA/9k='
+ '/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAAAAAD/7QA0UGhvdG9zaG9wIDMu' +
+ 'MAA4QklNBAQAAAAAABccAgUAC2JsdWVpbXAubmV0HAIAAAIABAD/2wCEAAEBAQEBAQEBAQEB' +
+ 'AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB' +
+ 'AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB' +
+ 'AQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/xABRAAEAAAAAAAAAAAAAAAAAAAAKEAEB' +
+ 'AQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAAAAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAA' +
+ 'AAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQvoP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyej' +
+ 'v8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXwH/9k='
var imageUrlJPEG = 'data:image/jpeg;base64,' + b64DataJPEG
- var blobJPEG = canCreateBlob && window.dataURLtoBlob(imageUrlJPEG)
+ var blobJPEG = browser.canCreateBlob && window.dataURLtoBlob(imageUrlJPEG)
+
+ ;(function imageSmoothingTest($) {
+ var canvas = document.createElement('canvas')
+ if (!canvas.getContext) return
+ var ctx = canvas.getContext('2d')
+ if (ctx.msImageSmoothingEnabled) {
+ $.imageSmoothingEnabled = ctx.msImageSmoothingEnabled
+ $.imageSmoothingEnabledKey = 'msImageSmoothingEnabled'
+ } else {
+ $.imageSmoothingEnabled = ctx.imageSmoothingEnabled
+ $.imageSmoothingEnabledKey = 'imageSmoothingEnabled'
+ }
+ $.imageSmoothingQuality = ctx.imageSmoothingQuality
+ })(browser)
+
+ // Test if the browser is using exact image data when transforming the canvas.
+ // Both Internet Explorer and Edge Legacy have off-by-one changes to color and
+ // transparency values when flipping images.
+ ;(function exactImageDataTest($) {
+ var img = document.createElement('img')
+ img.onload = function () {
+ var canvas = document.createElement('canvas')
+ if (!canvas.getContext) return
+ var ctx = canvas.getContext('2d')
+ // horizontal flip:
+ ctx.translate(img.width, 0)
+ ctx.scale(-1, 1)
+ ctx.drawImage(img, 0, 0)
+ $.exactImageData =
+ // Workaround for IE11 not supporting .join() for imageData.data:
+ Array.prototype.slice
+ .call(ctx.getImageData(0, 0, img.width, img.height).data)
+ // Resulting image data layout (B=black, F=white): FB
+ .join(',') === '255,255,255,255,0,0,0,255'
+ }
+ // black+white 2x1 GIF
+ // Image data layout (B=black, F=white): BF
+ img.src =
+ 'data:image/gif;base64,' +
+ 'R0lGODdhAgABAPEAAAAAAP///yZFySZFySH5BAEAAAIALAAAAAACAAEAAAICRAoAOw=='
+ })(browser)
+
/**
* Helper function to create a blob object from the given image data
*
- * @param {*} data Image data
+ * @param {ArrayBuffer} data Image data
* @param {string} type Image content type
* @returns {Blob} Image Blob object
*/
@@ -60,325 +124,553 @@
window.MozBlobBuilder ||
window.MSBlobBuilder
var builder = new BlobBuilder()
- builder.append(data.buffer || data)
+ builder.append(data)
return builder.getBlob(type)
}
}
- describe('Loading', function() {
- it('Return an object with onload and onerror methods', function() {
- var img = loadImage(blobGIF, function() {})
+ /**
+ * Request helper function.
+ *
+ * @param {string} url URL to request
+ * @param {Function} callback Request callback
+ */
+ function request(url, callback) {
+ var xhr = new XMLHttpRequest()
+ xhr.onload = callback
+ xhr.onerror = callback
+ try {
+ xhr.open('GET', url, true)
+ } catch (e) {
+ callback.call(xhr, e)
+ return
+ }
+ xhr.send()
+ }
+
+ describe('Loading', function () {
+ it('Return an object with onload and onerror methods', function () {
+ var img = loadImage(blobGIF, function () {})
expect(img).to.be.an.instanceOf(Object)
- expect(img.onload).to.be.a('function')
- expect(img.onerror).to.be.a('function')
+ expect(img.onload).to.be.an.instanceOf(Function)
+ expect(img.onerror).to.be.an.instanceOf(Function)
+ })
+
+ it('Load image url as img element', function (done) {
+ expect(
+ loadImage(imageUrlGIF, function (img) {
+ expect(img.nodeName.toLowerCase()).to.equal('img')
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(40)
+ done()
+ })
+ ).to.be.ok
})
- it('Load image url', function(done) {
+ it('Load image blob as img element', function (done) {
expect(
- loadImage(imageUrlGIF, function(img) {
- expect(img.width).to.equal(80)
- expect(img.height).to.equal(60)
+ loadImage(blobGIF, function (img) {
+ expect(img.nodeName.toLowerCase()).to.equal('img')
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(40)
done()
})
).to.be.ok
})
- it('Load image blob', function(done) {
+ it('Handle image loading error', function (done) {
expect(
- loadImage(blobGIF, function(img) {
- expect(img.width).to.equal(80)
- expect(img.height).to.equal(60)
+ loadImage('404', function (err) {
+ expect(err).to.be.an.instanceOf(window.Event)
+ expect(err.type).to.equal('error')
done()
})
).to.be.ok
})
- it('Return image loading error to callback', function(done) {
+ it('Provide original image width+height in callback data', function (done) {
expect(
- loadImage('404', function(img) {
- expect(img).to.be.an.instanceOf(window.Event)
- expect(img.type).to.equal('error')
+ loadImage(imageUrlGIF, function (img, data) {
+ expect(data.originalWidth).to.equal(60)
+ expect(data.originalHeight).to.equal(40)
done()
})
).to.be.ok
})
- it('Keep object URL if noRevoke is true', function(done) {
+ it('Load image as canvas for canvas: true', function (done) {
expect(
loadImage(
- blobGIF,
- function(img) {
- loadImage(img.src, function(img2) {
- expect(img.width).to.equal(img2.width)
- expect(img.height).to.equal(img2.height)
+ imageUrlGIF,
+ function (img) {
+ expect(img.getContext).to.be.an.instanceOf(Function)
+ expect(img.nodeName.toLowerCase()).to.equal('canvas')
+ done()
+ },
+ { canvas: true }
+ )
+ ).to.be.ok
+ })
+
+ describe('File', function () {
+ if (!fileGIF) return
+
+ it('Load image file as img element', function (done) {
+ expect(
+ loadImage(fileGIF, function (img) {
+ expect(img.nodeName.toLowerCase()).to.equal('img')
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(40)
+ done()
+ })
+ ).to.be.ok
+ })
+ })
+
+ describe('Object URL', function () {
+ // Using XMLHttpRequest via the request helper function to test Object
+ // URLs to work around Edge Legacy and IE caching image URLs.
+ if (!window.XMLHttpRequest) return
+
+ it('Keep object URL if noRevoke is set to true', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ request(img.src, function (event) {
+ expect(event.type).to.equal('load')
+ done()
+ })
+ },
+ { noRevoke: true }
+ )
+ ).to.be.ok
+ })
+
+ it('Discard object URL if noRevoke is not set', function (done) {
+ expect(
+ loadImage(blobGIF, function (img) {
+ request(img.src, function (event) {
+ // IE throws an error that has no type property:
+ expect(event.type).to.be.oneOf(['error', undefined])
done()
})
+ })
+ ).to.be.ok
+ })
+ })
+
+ describe('Promise', function () {
+ if (!window.Promise) return
+
+ it('Load image url as img element', function () {
+ return loadImage(imageUrlGIF).then(function (data) {
+ var img = data.image
+ expect(img.nodeName.toLowerCase()).to.equal('img')
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(40)
+ })
+ })
+
+ it('Load image blob as img element', function () {
+ return loadImage(blobGIF).then(function (data) {
+ var img = data.image
+ expect(img.nodeName.toLowerCase()).to.equal('img')
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(40)
+ })
+ })
+
+ it('Handle image loading error', function () {
+ return loadImage('404')
+ .then(function () {
+ throw new Error('Promise not rejected')
+ })
+ .catch(function (err) {
+ expect(err).to.be.an.instanceOf(window.Event)
+ expect(err.type).to.equal('error')
+ })
+ })
+
+ it('Provide original image width+height in callback data', function () {
+ return loadImage(imageUrlGIF).then(function (data) {
+ expect(data.originalWidth).to.equal(60)
+ expect(data.originalHeight).to.equal(40)
+ })
+ })
+
+ it('Load image as canvas for canvas: true', function () {
+ return loadImage(imageUrlGIF, { canvas: true }).then(function (data) {
+ var img = data.image
+ expect(img.getContext).to.be.an.instanceOf(Function)
+ expect(img.nodeName.toLowerCase()).to.equal('canvas')
+ })
+ })
+ })
+ })
+
+ describe('Exceptions', function () {
+ var originalTransform = loadImage.transform
+
+ before(function () {
+ loadImage.transform = function (img, options, callback) {
+ if (options.throwError) throw options.throwError
+ callback(options.callbackError)
+ }
+ })
+
+ after(function () {
+ loadImage.transform = originalTransform
+ })
+
+ it('Pass error to callback', function (done) {
+ var error = new Error('ERROR')
+ expect(
+ loadImage(
+ imageUrlGIF,
+ function (err) {
+ expect(err).to.be.an.instanceOf(Error)
+ expect(err.message).to.equal(error.message)
+ done()
},
- { noRevoke: true }
+ { callbackError: error }
)
).to.be.ok
})
- it('Discard object URL if noRevoke is undefined/false', function(done) {
+ it('Pass exception error to callback', function (done) {
+ var error = new Error('ERROR')
expect(
- loadImage(blobGIF, function(img) {
- loadImage(img.src, function(img2) {
- if (!window.callPhantom) {
- // revokeObjectUrl doesn't seem to have an effect in PhantomJS
- expect(img2).to.be.an.instanceOf(window.Event)
- expect(img2.type).to.equal('error')
- }
+ loadImage(
+ imageUrlGIF,
+ function (err) {
+ expect(err).to.be.an.instanceOf(Error)
+ expect(err.message).to.equal(error.message)
done()
- })
- })
+ },
+ { throwError: error }
+ )
).to.be.ok
})
- it('Provide original image width+height in callback data', function(done) {
+ it('Pass exception string to callback', function (done) {
+ var error = 'ERROR'
expect(
- loadImage(imageUrlGIF, function(img, data) {
- expect(data.originalWidth).to.equal(80)
- expect(data.originalHeight).to.equal(60)
- done()
- })
+ loadImage(
+ imageUrlGIF,
+ function (err) {
+ expect(err).to.be.a('string')
+ expect(err).to.equal(error)
+ done()
+ },
+ { throwError: error }
+ )
).to.be.ok
})
+
+ describe('Promise', function () {
+ it('Reject with error ', function () {
+ var error = new Error('ERROR')
+ return loadImage(imageUrlGIF, { callbackError: error })
+ .then(function () {
+ throw new Error('Promise not rejected')
+ })
+ .catch(function (err) {
+ expect(err).to.be.an.instanceOf(Error)
+ expect(err.message).to.equal(error.message)
+ })
+ })
+
+ it('Reject with exception error ', function () {
+ var error = new Error('ERROR')
+ return loadImage(imageUrlGIF, { throwError: error })
+ .then(function () {
+ throw new Error('Promise not rejected')
+ })
+ .catch(function (err) {
+ expect(err).to.be.an.instanceOf(Error)
+ expect(err.message).to.equal(error.message)
+ })
+ })
+
+ it('Reject with exception string ', function () {
+ var error = 'ERROR'
+ return loadImage(imageUrlGIF, { throwError: error })
+ .then(function () {
+ throw new Error('Promise not rejected')
+ })
+ .catch(function (err) {
+ expect(err).to.be.a('string')
+ expect(err).to.equal(error)
+ })
+ })
+ })
})
- describe('Scaling', function() {
- describe('max/min', function() {
- it('Scale to maxWidth', function(done) {
+ describe('Scaling', function () {
+ describe('max/min', function () {
+ it('Scale to maxWidth', function (done) {
expect(
loadImage(
blobGIF,
- function(img, data) {
- expect(img.width).to.equal(40)
- expect(img.height).to.equal(30)
- expect(data.originalWidth).to.equal(80)
- expect(data.originalHeight).to.equal(60)
+ function (img, data) {
+ expect(img.width).to.equal(30)
+ expect(img.height).to.equal(20)
+ expect(data.originalWidth).to.equal(60)
+ expect(data.originalHeight).to.equal(40)
done()
},
- { maxWidth: 40 }
+ { maxWidth: 30 }
)
).to.be.ok
})
- it('Scale to maxHeight', function(done) {
+ it('Scale to maxHeight', function (done) {
expect(
loadImage(
blobGIF,
- function(img, data) {
- expect(img.width).to.equal(20)
- expect(img.height).to.equal(15)
- expect(data.originalWidth).to.equal(80)
- expect(data.originalHeight).to.equal(60)
+ function (img, data) {
+ expect(img.width).to.equal(30)
+ expect(img.height).to.equal(20)
+ expect(data.originalWidth).to.equal(60)
+ expect(data.originalHeight).to.equal(40)
done()
},
- { maxHeight: 15 }
+ { maxHeight: 20 }
)
).to.be.ok
})
- it('Scale to minWidth', function(done) {
+ it('Scale to minWidth', function (done) {
expect(
loadImage(
blobGIF,
- function(img, data) {
- expect(img.width).to.equal(160)
- expect(img.height).to.equal(120)
- expect(data.originalWidth).to.equal(80)
- expect(data.originalHeight).to.equal(60)
+ function (img, data) {
+ expect(img.width).to.equal(120)
+ expect(img.height).to.equal(80)
+ expect(data.originalWidth).to.equal(60)
+ expect(data.originalHeight).to.equal(40)
done()
},
- { minWidth: 160 }
+ { minWidth: 120 }
)
).to.be.ok
})
- it('Scale to minHeight', function(done) {
+ it('Scale to minHeight', function (done) {
expect(
loadImage(
blobGIF,
- function(img, data) {
- expect(img.width).to.equal(320)
- expect(img.height).to.equal(240)
- expect(data.originalWidth).to.equal(80)
- expect(data.originalHeight).to.equal(60)
+ function (img, data) {
+ expect(img.width).to.equal(120)
+ expect(img.height).to.equal(80)
+ expect(data.originalWidth).to.equal(60)
+ expect(data.originalHeight).to.equal(40)
done()
},
- { minHeight: 240 }
+ { minHeight: 80 }
)
).to.be.ok
})
- it('Scale to minWidth but respect maxWidth', function(done) {
+ it('Scale to minWidth but respect maxWidth', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(160)
- expect(img.height).to.equal(120)
+ function (img) {
+ expect(img.width).to.equal(120)
+ expect(img.height).to.equal(80)
done()
},
- { minWidth: 240, maxWidth: 160 }
+ { minWidth: 240, maxWidth: 120 }
)
).to.be.ok
})
- it('Scale to minHeight but respect maxHeight', function(done) {
+ it('Scale to minHeight but respect maxHeight', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(160)
- expect(img.height).to.equal(120)
+ function (img) {
+ expect(img.width).to.equal(120)
+ expect(img.height).to.equal(80)
done()
},
- { minHeight: 180, maxHeight: 120 }
+ { minHeight: 160, maxHeight: 80 }
)
).to.be.ok
})
- it('Scale to minWidth but respect maxHeight', function(done) {
+ it('Scale to minWidth but respect maxHeight', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(160)
- expect(img.height).to.equal(120)
+ function (img) {
+ expect(img.width).to.equal(120)
+ expect(img.height).to.equal(80)
done()
},
- { minWidth: 240, maxHeight: 120 }
+ { minWidth: 240, maxHeight: 80 }
)
).to.be.ok
})
- it('Scale to minHeight but respect maxWidth', function(done) {
+ it('Scale to minHeight but respect maxWidth', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(160)
- expect(img.height).to.equal(120)
+ function (img) {
+ expect(img.width).to.equal(120)
+ expect(img.height).to.equal(80)
done()
},
- { minHeight: 180, maxWidth: 160 }
+ { minHeight: 160, maxWidth: 120 }
)
).to.be.ok
})
- it('Scale up with the given pixelRatio', function(done) {
+ it('Scale up with the given pixelRatio', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(320)
- expect(img.height).to.equal(240)
- expect(img.style.width).to.equal('160px')
- expect(img.style.height).to.equal('120px')
+ function (img) {
+ expect(img.width).to.equal(240)
+ expect(img.height).to.equal(160)
+ expect(img.style.width).to.equal('120px')
+ // Check if pixelRatio scaling is idempotent:
+ var img2 = loadImage.scale(img, { minWidth: 120, pixelRatio: 2 })
+ expect(img2.width).to.equal(240)
+ expect(img2.height).to.equal(160)
+ expect(img2.style.width).to.equal('120px')
done()
},
- { minWidth: 160, canvas: true, pixelRatio: 2 }
+ { minWidth: 120, canvas: true, pixelRatio: 2 }
)
).to.be.ok
})
- it('Scale down with the given pixelRatio', function(done) {
+ it('Scale down with the given pixelRatio', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(80)
- expect(img.height).to.equal(60)
- expect(img.style.width).to.equal('40px')
- expect(img.style.height).to.equal('30px')
+ function (img) {
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(40)
+ expect(img.style.width).to.equal('30px')
+ // Check if pixelRatio scaling is idempotent:
+ var img2 = loadImage.scale(img, { minWidth: 30, pixelRatio: 2 })
+ expect(img2.width).to.equal(60)
+ expect(img2.height).to.equal(40)
+ expect(img2.style.width).to.equal('30px')
done()
},
- { maxWidth: 40, canvas: true, pixelRatio: 2 }
+ { maxWidth: 30, canvas: true, pixelRatio: 2 }
)
).to.be.ok
})
- it('Scale down with the given downsamplingRatio', function(done) {
+ it('Scale down with the given downsamplingRatio', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(20)
- expect(img.height).to.equal(15)
+ function (img) {
+ expect(img.width).to.equal(15)
+ expect(img.height).to.equal(10)
done()
},
- { maxWidth: 20, canvas: true, downsamplingRatio: 0.5 }
+ { maxWidth: 15, canvas: true, downsamplingRatio: 0.5 }
)
).to.be.ok
})
- it('Ignore max settings for smaller image dimensions', function(done) {
+ it('Ignore max settings for smaller image dimensions', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(80)
- expect(img.height).to.equal(60)
+ function (img) {
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(40)
done()
},
- { maxWidth: 160, maxHeight: 120 }
+ { maxWidth: 120, maxHeight: 80 }
)
).to.be.ok
})
- it('Ignore min settings for larger image dimensions', function(done) {
+ it('Ignore min settings for larger image dimensions', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(80)
- expect(img.height).to.equal(60)
+ function (img) {
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(40)
+ done()
+ },
+ { minWidth: 30, minHeight: 20 }
+ )
+ ).to.be.ok
+ })
+
+ it('Accept a canvas element as source image', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.getContext).to.be.an.instanceOf(Function)
+ expect(img.nodeName.toLowerCase()).to.equal('canvas')
+ // eslint-disable-next-line no-param-reassign
+ img = loadImage.scale(img, {
+ maxWidth: 30
+ })
+ expect(img.getContext).to.be.an.instanceOf(Function)
+ expect(img.nodeName.toLowerCase()).to.equal('canvas')
+ expect(img.width).to.equal(30)
+ expect(img.height).to.equal(20)
done()
},
- { minWidth: 40, minHeight: 30 }
+ { canvas: true }
)
).to.be.ok
})
})
- describe('contain', function() {
- it('Scale up to contain image in max dimensions', function(done) {
+ describe('contain', function () {
+ it('Scale up to contain image in max dimensions', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(160)
- expect(img.height).to.equal(120)
+ function (img) {
+ expect(img.width).to.equal(120)
+ expect(img.height).to.equal(80)
done()
},
- { maxWidth: 160, maxHeight: 160, contain: true }
+ { maxWidth: 120, maxHeight: 120, contain: true }
)
).to.be.ok
})
- it('Scale down to contain image in max dimensions', function(done) {
+ it('Scale down to contain image in max dimensions', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(40)
- expect(img.height).to.equal(30)
+ function (img) {
+ expect(img.width).to.equal(30)
+ expect(img.height).to.equal(20)
done()
},
- { maxWidth: 40, maxHeight: 40, contain: true }
+ { maxWidth: 30, maxHeight: 30, contain: true }
)
).to.be.ok
})
})
- describe('cover', function() {
- it('Scale up to cover max dimensions with image dimensions', function(done) {
+ describe('cover', function () {
+ it('Scale up to cover max dimensions with image dimensions', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(160)
+ function (img) {
+ expect(img.width).to.equal(180)
expect(img.height).to.equal(120)
done()
},
@@ -387,100 +679,207 @@
).to.be.ok
})
- it('Scale down to cover max dimensions with image dimensions', function(done) {
+ it('Scale down to cover max dimensions with image dimensions', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(40)
- expect(img.height).to.equal(30)
+ function (img) {
+ expect(img.width).to.equal(30)
+ expect(img.height).to.equal(20)
+ done()
+ },
+ { maxWidth: 20, maxHeight: 20, cover: true }
+ )
+ ).to.be.ok
+ })
+ })
+
+ describe('image smoothing', function () {
+ if (!browser.imageSmoothingEnabled) {
+ return
+ }
+
+ it('imageSmoothingEnabled defaults to true', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(120)
+ expect(
+ img.getContext('2d')[browser.imageSmoothingEnabledKey]
+ ).to.equal(true)
+ done()
+ },
+ { minWidth: 120, canvas: true }
+ )
+ ).to.be.ok
+ })
+
+ it('Sets imageSmoothingEnabled to false', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(120)
+ expect(
+ img.getContext('2d')[browser.imageSmoothingEnabledKey]
+ ).to.equal(false)
+ done()
+ },
+ { minWidth: 120, canvas: true, imageSmoothingEnabled: false }
+ )
+ ).to.be.ok
+ })
+
+ if (browser.imageSmoothingQuality !== 'low') {
+ return
+ }
+
+ it('imageSmoothingQuality defaults to "low"', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(120)
+ expect(img.getContext('2d').imageSmoothingQuality).to.equal('low')
+ done()
+ },
+ { minWidth: 120, canvas: true }
+ )
+ ).to.be.ok
+ })
+
+ it('Sets imageSmoothingQuality to "medium"', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(120)
+ expect(img.getContext('2d').imageSmoothingQuality).to.equal(
+ 'medium'
+ )
+ done()
+ },
+ { minWidth: 120, canvas: true, imageSmoothingQuality: 'medium' }
+ )
+ ).to.be.ok
+ })
+
+ it('Sets imageSmoothingQuality to "high"', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(120)
+ expect(img.getContext('2d').imageSmoothingQuality).to.equal(
+ 'high'
+ )
done()
},
- { maxWidth: 30, maxHeight: 30, cover: true }
+ { minWidth: 120, canvas: true, imageSmoothingQuality: 'high' }
+ )
+ ).to.be.ok
+ })
+
+ it('Ignores imageSmoothingQuality if imageSmoothingEnabled is false', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(120)
+ expect(img.getContext('2d').imageSmoothingQuality).to.equal('low')
+ done()
+ },
+ {
+ minWidth: 120,
+ canvas: true,
+ imageSmoothingQuality: 'high',
+ imageSmoothingEnabled: false
+ }
)
).to.be.ok
})
})
})
- describe('Cropping', function() {
- it('Crop to same values for maxWidth and maxHeight', function(done) {
+ describe('Cropping', function () {
+ it('Crop to same values for maxWidth and maxHeight', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(40)
- expect(img.height).to.equal(40)
+ function (img) {
+ expect(img.width).to.equal(30)
+ expect(img.height).to.equal(30)
done()
},
- { maxWidth: 40, maxHeight: 40, crop: true }
+ { maxWidth: 30, maxHeight: 30, crop: true }
)
).to.be.ok
})
- it('Crop to different values for maxWidth and maxHeight', function(done) {
+ it('Crop to different values for maxWidth and maxHeight', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(40)
- expect(img.height).to.equal(60)
+ function (img) {
+ expect(img.width).to.equal(30)
+ expect(img.height).to.equal(40)
done()
},
- { maxWidth: 40, maxHeight: 60, crop: true }
+ { maxWidth: 30, maxHeight: 40, crop: true }
)
).to.be.ok
})
- it('Crop using the given sourceWidth/sourceHeight dimensions', function(done) {
+ it('Crop using the given sourceWidth/sourceHeight dimensions', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(40)
- expect(img.height).to.equal(40)
+ function (img) {
+ expect(img.width).to.equal(30)
+ expect(img.height).to.equal(30)
done()
},
- { sourceWidth: 40, sourceHeight: 40, crop: true }
+ { sourceWidth: 30, sourceHeight: 30, crop: true }
)
).to.be.ok
})
- it('Crop using the given left/top coordinates', function(done) {
+ it('Crop using the given left/top coordinates', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
+ function (img) {
expect(img.width).to.equal(40)
expect(img.height).to.equal(20)
done()
},
- { left: 40, top: 40, crop: true }
+ { left: 20, top: 20, crop: true }
)
).to.be.ok
})
- it('Crop using the given right/bottom coordinates', function(done) {
+ it('Crop using the given right/bottom coordinates', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
+ function (img) {
expect(img.width).to.equal(40)
expect(img.height).to.equal(20)
done()
},
- { right: 40, bottom: 40, crop: true }
+ { right: 20, bottom: 20, crop: true }
)
).to.be.ok
})
- it('Crop using the given 2:1 aspectRatio', function(done) {
+ it('Crop using the given 2:1 aspectRatio', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(80)
- expect(img.height).to.equal(40)
+ function (img) {
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(30)
done()
},
{ aspectRatio: 2 }
@@ -488,29 +887,28 @@
).to.be.ok
})
- it('Crop using the given 2:3 aspectRatio', function(done) {
+ it('Crop using the given 1:2 aspectRatio', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
- expect(img.width).to.equal(40)
- expect(img.height).to.equal(60)
+ function (img) {
+ expect(img.width).to.equal(20)
+ expect(img.height).to.equal(40)
done()
},
- { aspectRatio: 2 / 3 }
+ { aspectRatio: 1 / 2 }
)
).to.be.ok
})
- it('Crop using maxWidth/maxHeight and pixelRatio', function(done) {
+ it('Crop using maxWidth/maxHeight and pixelRatio', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
+ function (img) {
expect(img.width).to.equal(80)
expect(img.height).to.equal(80)
expect(img.style.width).to.equal('40px')
- expect(img.style.height).to.equal('40px')
done()
},
{ maxWidth: 40, maxHeight: 40, crop: true, pixelRatio: 2 }
@@ -518,15 +916,14 @@
).to.be.ok
})
- it('Crop using sourceWidth/sourceHeight and pixelRatio', function(done) {
+ it('Crop using sourceWidth/sourceHeight and pixelRatio', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
+ function (img) {
expect(img.width).to.equal(80)
expect(img.height).to.equal(80)
expect(img.style.width).to.equal('40px')
- expect(img.style.height).to.equal('40px')
done()
},
{ sourceWidth: 40, sourceHeight: 40, crop: true, pixelRatio: 2 }
@@ -534,22 +931,13 @@
).to.be.ok
})
- it('Crop using maxWidth/maxHeight and downsamplingRatio', function(done) {
+ it('Crop using maxWidth/maxHeight and downsamplingRatio', function (done) {
expect(
loadImage(
blobGIF,
- function(img) {
+ function (img) {
expect(img.width).to.equal(10)
expect(img.height).to.equal(10)
-
- var data = img.getContext('2d').getImageData(0, 0, 10, 10).data
- for (var i = 0; i < data.length / 4; i += 4) {
- expect(data[i]).to.equal(0)
- expect(data[i + 1]).to.equal(0)
- expect(data[i + 2]).to.equal(0)
- expect(data[i + 3]).to.equal(255)
- }
-
done()
},
{ maxWidth: 10, maxHeight: 10, crop: true, downsamplingRatio: 0.5 }
@@ -558,296 +946,1683 @@
})
})
- describe('Orientation', function() {
- it('Should keep the orientation', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- expect(img.width).to.equal(80)
- expect(img.height).to.equal(60)
- done()
- },
- { orientation: 1 }
- )
- ).to.be.ok
- })
-
- it('Should rotate left', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- expect(img.width).to.equal(60)
- expect(img.height).to.equal(80)
- done()
- },
- { orientation: 8 }
- )
- ).to.be.ok
- })
+ describe('Orientation', function () {
+ describe('EXIF Orientation: undefined', function () {
+ it('1: keep original', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(40)
+ done()
+ },
+ { orientation: 1 }
+ )
+ ).to.be.ok
+ })
- it('Should rotate right', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- expect(img.width).to.equal(60)
- expect(img.height).to.equal(80)
- done()
- },
- { orientation: 6 }
- )
- ).to.be.ok
- })
+ it('2: horizontal flip', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(40)
+ done()
+ },
+ { orientation: 2 }
+ )
+ ).to.be.ok
+ })
- it('Should adjust constraints to new coordinates', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- expect(img.width).to.equal(30)
- expect(img.height).to.equal(40)
- done()
- },
- { orientation: 6, maxWidth: 30, maxHeight: 40 }
- )
- ).to.be.ok
- })
+ it('3: 180° rotate left', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(40)
+ done()
+ },
+ { orientation: 3 }
+ )
+ ).to.be.ok
+ })
- it('Should adjust left and top to new coordinates', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- expect(img.width).to.equal(30)
- expect(img.height).to.equal(60)
- done()
- },
- { orientation: 5, left: 30, top: 20 }
- )
- ).to.be.ok
- })
+ it('4: vertical flip', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(40)
+ done()
+ },
+ { orientation: 4 }
+ )
+ ).to.be.ok
+ })
- it('Should adjust right and bottom to new coordinates', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- expect(img.width).to.equal(30)
- expect(img.height).to.equal(60)
- done()
- },
- { orientation: 5, right: 30, bottom: 20 }
- )
- ).to.be.ok
- })
+ it('5: vertical flip + 90° rotate right', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(40)
+ expect(img.height).to.equal(60)
+ done()
+ },
+ { orientation: 5 }
+ )
+ ).to.be.ok
+ })
- it('Should adjust left and bottom to new coordinates', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- expect(img.width).to.equal(30)
- expect(img.height).to.equal(60)
- done()
- },
- { orientation: 7, left: 30, bottom: 20 }
- )
- ).to.be.ok
- })
+ it('6: 90° rotate right', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(40)
+ expect(img.height).to.equal(60)
+ done()
+ },
+ { orientation: 6 }
+ )
+ ).to.be.ok
+ })
- it('Should adjust right and top to new coordinates', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- expect(img.width).to.equal(30)
- expect(img.height).to.equal(60)
- done()
- },
- { orientation: 7, right: 30, top: 20 }
- )
- ).to.be.ok
- })
+ it('7: horizontal flip + 90° rotate right', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(40)
+ expect(img.height).to.equal(60)
+ done()
+ },
+ { orientation: 7 }
+ )
+ ).to.be.ok
+ })
- it('Should rotate left with the given pixelRatio', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- expect(img.width).to.equal(120)
- expect(img.height).to.equal(160)
- expect(img.style.width).to.equal('60px')
- expect(img.style.height).to.equal('80px')
- done()
- },
- { orientation: 8, pixelRatio: 2 }
- )
- ).to.be.ok
- })
+ it('8: 90° rotate left', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(40)
+ expect(img.height).to.equal(60)
+ done()
+ },
+ { orientation: 8 }
+ )
+ ).to.be.ok
+ })
+ it('Adjust constraints to new coordinates', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(20)
+ expect(img.height).to.equal(30)
+ done()
+ },
+ { orientation: 6, maxWidth: 20, maxHeight: 30 }
+ )
+ ).to.be.ok
+ })
- it('Should rotate right with the given pixelRatio', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- expect(img.width).to.equal(120)
- expect(img.height).to.equal(160)
- expect(img.style.width).to.equal('60px')
- expect(img.style.height).to.equal('80px')
- done()
- },
- { orientation: 6, pixelRatio: 2 }
- )
- ).to.be.ok
- })
+ it('Rotate left with the given pixelRatio', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(80)
+ expect(img.height).to.equal(120)
+ expect(img.style.width).to.equal('40px')
+ done()
+ },
+ { orientation: 8, pixelRatio: 2 }
+ )
+ ).to.be.ok
+ })
- it('Should ignore too small orientation value', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- expect(img.width).to.equal(80)
- expect(img.height).to.equal(60)
- done()
- },
- { orientation: -1 }
- )
- ).to.be.ok
- })
+ it('Rotate right with the given pixelRatio', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(80)
+ expect(img.height).to.equal(120)
+ expect(img.style.width).to.equal('40px')
+ done()
+ },
+ { orientation: 6, pixelRatio: 2 }
+ )
+ ).to.be.ok
+ })
- it('Should ignore too large orientation value', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- expect(img.width).to.equal(80)
- expect(img.height).to.equal(60)
- done()
- },
- { orientation: 9 }
- )
- ).to.be.ok
- })
+ it('Ignore too small orientation value', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(40)
+ done()
+ },
+ { orientation: -1 }
+ )
+ ).to.be.ok
+ })
- it('Should rotate right based on the exif orientation value', function(done) {
- expect(
- loadImage(
- blobJPEG,
- function(img, data) {
- expect(data).to.be.ok
- expect(data.exif).to.be.ok
- expect(data.exif.get('Orientation')).to.equal(6)
- expect(img.width).to.equal(1)
- expect(img.height).to.equal(2)
- done()
- },
- { orientation: true }
- )
- ).to.be.ok
+ it('Ignore too large orientation value', function (done) {
+ expect(
+ loadImage(
+ blobGIF,
+ function (img) {
+ expect(img.width).to.equal(60)
+ expect(img.height).to.equal(40)
+ done()
+ },
+ { orientation: 9 }
+ )
+ ).to.be.ok
+ })
+
+ describe('Cropping', function () {
+ it('1: keep original, right: 1, bottom: 1', function (done) {
+ expect(
+ loadImage(
+ blobGIF2,
+ function (img) {
+ expect(img.width).to.equal(2)
+ expect(img.height).to.equal(1)
+ // Image data layout after orientation (B=black, F=white):
+ // BF
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 2, 1).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque white
+ expect(imageData[0 + 4]).to.equal(255)
+ expect(imageData[1 + 4]).to.equal(255)
+ expect(imageData[2 + 4]).to.equal(255)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 1,
+ right: 1,
+ bottom: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('2: horizontal flip, bottom: 1, left: 1', function (done) {
+ expect(
+ loadImage(
+ blobGIF2,
+ function (img) {
+ expect(img.width).to.equal(2)
+ expect(img.height).to.equal(1)
+ if (!browser.exactImageData) {
+ done()
+ return
+ }
+ // Image data layout after orientation (B=black, F=white):
+ // FB
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 2, 1).data
+ // 0:0 opaque white
+ expect(imageData[0]).to.equal(255)
+ expect(imageData[1]).to.equal(255)
+ expect(imageData[2]).to.equal(255)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 2,
+ bottom: 1,
+ left: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('3: 180° rotate left, top: 1, left: 1', function (done) {
+ expect(
+ loadImage(
+ blobGIF2,
+ function (img) {
+ expect(img.width).to.equal(2)
+ expect(img.height).to.equal(1)
+ // Image data layout after orientation (B=black, F=white):
+ // FB
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 2, 1).data
+ // 0:0 opaque white
+ expect(imageData[0]).to.equal(255)
+ expect(imageData[1]).to.equal(255)
+ expect(imageData[2]).to.equal(255)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 3,
+ top: 1,
+ left: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('4: vertical flip, top: 1, right: 1', function (done) {
+ expect(
+ loadImage(
+ blobGIF2,
+ function (img) {
+ expect(img.width).to.equal(2)
+ expect(img.height).to.equal(1)
+ if (!browser.exactImageData) {
+ done()
+ return
+ }
+ // Image data layout after orientation (B=black, F=white):
+ // BF
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 2, 1).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque white
+ expect(imageData[0 + 4]).to.equal(255)
+ expect(imageData[1 + 4]).to.equal(255)
+ expect(imageData[2 + 4]).to.equal(255)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 4,
+ top: 1,
+ right: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('5: vertical flip + 90° rotate right, right: 1, bottom: 1', function (done) {
+ expect(
+ loadImage(
+ blobGIF2,
+ function (img) {
+ expect(img.width).to.equal(1)
+ expect(img.height).to.equal(2)
+ if (!browser.exactImageData) {
+ done()
+ return
+ }
+ // Image data layout after orientation (B=black, F=white):
+ // B
+ // F
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 1, 2).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 0:1 opaque white
+ expect(imageData[0 + 4]).to.equal(255)
+ expect(imageData[1 + 4]).to.equal(255)
+ expect(imageData[2 + 4]).to.equal(255)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 5,
+ right: 1,
+ bottom: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('6: 90° rotate right, bottom: 1, left: 1', function (done) {
+ expect(
+ loadImage(
+ blobGIF2,
+ function (img) {
+ expect(img.width).to.equal(1)
+ expect(img.height).to.equal(2)
+ // Image data layout after orientation (B=black, F=white):
+ // B
+ // F
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 1, 2).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 0:1 opaque white
+ expect(imageData[0 + 4]).to.equal(255)
+ expect(imageData[1 + 4]).to.equal(255)
+ expect(imageData[2 + 4]).to.equal(255)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 6,
+ bottom: 1,
+ left: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('7: horizontal flip + 90° rotate right, top: 1, left: 1', function (done) {
+ expect(
+ loadImage(
+ blobGIF2,
+ function (img) {
+ expect(img.width).to.equal(1)
+ expect(img.height).to.equal(2)
+ if (!browser.exactImageData) {
+ done()
+ return
+ }
+ // Image data layout after orientation (B=black, F=white):
+ // F
+ // B
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 1, 2).data
+ // 0:0 opaque white
+ expect(imageData[0]).to.equal(255)
+ expect(imageData[1]).to.equal(255)
+ expect(imageData[2]).to.equal(255)
+ expect(imageData[3]).to.equal(255)
+ // 0:1 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 7,
+ top: 1,
+ left: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('8: 90° rotate left, top: 1, right: 1', function (done) {
+ expect(
+ loadImage(
+ blobGIF2,
+ function (img) {
+ expect(img.width).to.equal(1)
+ expect(img.height).to.equal(2)
+ // Image data layout after orientation (B=black, F=white):
+ // F
+ // B
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 1, 2).data
+ // 0:0 opaque white
+ expect(imageData[0]).to.equal(255)
+ expect(imageData[1]).to.equal(255)
+ expect(imageData[2]).to.equal(255)
+ expect(imageData[3]).to.equal(255)
+ // 0:1 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 8,
+ top: 1,
+ right: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+ })
})
- it('Should scale image after exif based orientation', function(done) {
- expect(
- loadImage(
- blobJPEG,
- function(img) {
- expect(img.width).to.equal(10)
- expect(img.height).to.equal(20)
- done()
- },
- { orientation: true, minWidth: 10, minHeight: 20 }
- )
- ).to.be.ok
+ describe('EXIF Orientation: 6', function () {
+ it('1: keep original', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(3)
+ expect(img.height).to.equal(2)
+ // Image data layout after orientation (B=black, F=white):
+ // BFF
+ // BBB
+ var imageData = img.getContext('2d').getImageData(0, 0, 3, 2).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque white
+ expect(imageData[0 + 4]).to.equal(255)
+ expect(imageData[1 + 4]).to.equal(255)
+ expect(imageData[2 + 4]).to.equal(255)
+ expect(imageData[3 + 4]).to.equal(255)
+ // 2:0 opaque white
+ expect(imageData[0 + 8]).to.equal(255)
+ expect(imageData[1 + 8]).to.equal(255)
+ expect(imageData[2 + 8]).to.equal(255)
+ expect(imageData[3 + 8]).to.equal(255)
+ // 0:1 opaque black
+ expect(imageData[0 + 12]).to.equal(0)
+ expect(imageData[1 + 12]).to.equal(0)
+ expect(imageData[2 + 12]).to.equal(0)
+ expect(imageData[3 + 12]).to.equal(255)
+ // 1:1 opaque black
+ expect(imageData[0 + 16]).to.equal(0)
+ expect(imageData[1 + 16]).to.equal(0)
+ expect(imageData[2 + 16]).to.equal(0)
+ expect(imageData[3 + 16]).to.equal(255)
+ // 2:1 opaque black
+ expect(imageData[0 + 20]).to.equal(0)
+ expect(imageData[1 + 20]).to.equal(0)
+ expect(imageData[2 + 20]).to.equal(0)
+ expect(imageData[3 + 20]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('2: horizontal flip', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(3)
+ expect(img.height).to.equal(2)
+ if (!browser.exactImageData) {
+ done()
+ return
+ }
+ // Image data layout after orientation (B=black, F=white):
+ // FFB
+ // BBB
+ var imageData = img.getContext('2d').getImageData(0, 0, 3, 2).data
+ // 0:0 opaque white
+ expect(imageData[0]).to.equal(255)
+ expect(imageData[1]).to.equal(255)
+ expect(imageData[2]).to.equal(255)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque white
+ expect(imageData[0 + 4]).to.equal(255)
+ expect(imageData[1 + 4]).to.equal(255)
+ expect(imageData[2 + 4]).to.equal(255)
+ expect(imageData[3 + 4]).to.equal(255)
+ // 2:0 opaque black
+ expect(imageData[0 + 8]).to.equal(0)
+ expect(imageData[1 + 8]).to.equal(0)
+ expect(imageData[2 + 8]).to.equal(0)
+ expect(imageData[3 + 8]).to.equal(255)
+ // 0:1 opaque black
+ expect(imageData[0 + 12]).to.equal(0)
+ expect(imageData[1 + 12]).to.equal(0)
+ expect(imageData[2 + 12]).to.equal(0)
+ expect(imageData[3 + 12]).to.equal(255)
+ // 1:1 opaque black
+ expect(imageData[0 + 16]).to.equal(0)
+ expect(imageData[1 + 16]).to.equal(0)
+ expect(imageData[2 + 16]).to.equal(0)
+ expect(imageData[3 + 16]).to.equal(255)
+ // 2:1 opaque black
+ expect(imageData[0 + 20]).to.equal(0)
+ expect(imageData[1 + 20]).to.equal(0)
+ expect(imageData[2 + 20]).to.equal(0)
+ expect(imageData[3 + 20]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 2,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('3: 180° rotate left', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(3)
+ expect(img.height).to.equal(2)
+ // Image data layout after orientation (B=black, F=white):
+ // BBB
+ // FFB
+ var imageData = img.getContext('2d').getImageData(0, 0, 3, 2).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ // 2:0 opaque black
+ expect(imageData[0 + 8]).to.equal(0)
+ expect(imageData[1 + 8]).to.equal(0)
+ expect(imageData[2 + 8]).to.equal(0)
+ expect(imageData[3 + 8]).to.equal(255)
+ // 0:1 opaque white
+ expect(imageData[0 + 12]).to.equal(255)
+ expect(imageData[1 + 12]).to.equal(255)
+ expect(imageData[2 + 12]).to.equal(255)
+ expect(imageData[3 + 12]).to.equal(255)
+ // 1:1 opaque white
+ expect(imageData[0 + 16]).to.equal(255)
+ expect(imageData[1 + 16]).to.equal(255)
+ expect(imageData[2 + 16]).to.equal(255)
+ expect(imageData[3 + 16]).to.equal(255)
+ // 2:1 opaque black
+ expect(imageData[0 + 20]).to.equal(0)
+ expect(imageData[1 + 20]).to.equal(0)
+ expect(imageData[2 + 20]).to.equal(0)
+ expect(imageData[3 + 20]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 3,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('4: vertical flip', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(3)
+ expect(img.height).to.equal(2)
+ if (!browser.exactImageData) {
+ done()
+ return
+ }
+ // Image data layout after orientation (B=black, F=white):
+ // BBB
+ // BFF
+ var imageData = img.getContext('2d').getImageData(0, 0, 3, 2).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ // 2:0 opaque black
+ expect(imageData[0 + 8]).to.equal(0)
+ expect(imageData[1 + 8]).to.equal(0)
+ expect(imageData[2 + 8]).to.equal(0)
+ expect(imageData[3 + 8]).to.equal(255)
+ // 0:1 opaque black
+ expect(imageData[0 + 12]).to.equal(0)
+ expect(imageData[1 + 12]).to.equal(0)
+ expect(imageData[2 + 12]).to.equal(0)
+ expect(imageData[3 + 12]).to.equal(255)
+ // 1:1 opaque white
+ expect(imageData[0 + 16]).to.equal(255)
+ expect(imageData[1 + 16]).to.equal(255)
+ expect(imageData[2 + 16]).to.equal(255)
+ expect(imageData[3 + 16]).to.equal(255)
+ // 2:1 opaque white
+ expect(imageData[0 + 20]).to.equal(255)
+ expect(imageData[1 + 20]).to.equal(255)
+ expect(imageData[2 + 20]).to.equal(255)
+ expect(imageData[3 + 20]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 4,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('5: vertical flip + 90° rotate right', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(2)
+ expect(img.height).to.equal(3)
+ if (!browser.exactImageData) {
+ done()
+ return
+ }
+ // Image data layout after orientation (B=black, F=white):
+ // BB
+ // FB
+ // FB
+ var imageData = img.getContext('2d').getImageData(0, 0, 2, 3).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ // 0:1 opaque white
+ expect(imageData[0 + 8]).to.equal(255)
+ expect(imageData[1 + 8]).to.equal(255)
+ expect(imageData[2 + 8]).to.equal(255)
+ expect(imageData[3 + 8]).to.equal(255)
+ // 1:1 opaque black
+ expect(imageData[0 + 12]).to.equal(0)
+ expect(imageData[1 + 12]).to.equal(0)
+ expect(imageData[2 + 12]).to.equal(0)
+ expect(imageData[3 + 12]).to.equal(255)
+ // 0:2 opaque white
+ expect(imageData[0 + 16]).to.equal(255)
+ expect(imageData[1 + 16]).to.equal(255)
+ expect(imageData[2 + 16]).to.equal(255)
+ expect(imageData[3 + 16]).to.equal(255)
+ // 1:2 opaque black
+ expect(imageData[0 + 20]).to.equal(0)
+ expect(imageData[1 + 20]).to.equal(0)
+ expect(imageData[2 + 20]).to.equal(0)
+ expect(imageData[3 + 20]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 5,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('6: 90° rotate right', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(2)
+ expect(img.height).to.equal(3)
+ // Image data layout after orientation (B=black, F=white):
+ // BB
+ // BF
+ // BF
+ var imageData = img.getContext('2d').getImageData(0, 0, 2, 3).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ // 0:1 opaque black
+ expect(imageData[0 + 8]).to.equal(0)
+ expect(imageData[1 + 8]).to.equal(0)
+ expect(imageData[2 + 8]).to.equal(0)
+ expect(imageData[3 + 8]).to.equal(255)
+ // 1:1 opaque white
+ expect(imageData[0 + 12]).to.equal(255)
+ expect(imageData[1 + 12]).to.equal(255)
+ expect(imageData[2 + 12]).to.equal(255)
+ expect(imageData[3 + 12]).to.equal(255)
+ // 0:2 opaque black
+ expect(imageData[0 + 16]).to.equal(0)
+ expect(imageData[1 + 16]).to.equal(0)
+ expect(imageData[2 + 16]).to.equal(0)
+ expect(imageData[3 + 16]).to.equal(255)
+ // 1:2 opaque white
+ expect(imageData[0 + 20]).to.equal(255)
+ expect(imageData[1 + 20]).to.equal(255)
+ expect(imageData[2 + 20]).to.equal(255)
+ expect(imageData[3 + 20]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 6,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('7: horizontal flip + 90° rotate right', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(2)
+ expect(img.height).to.equal(3)
+ if (!browser.exactImageData) {
+ done()
+ return
+ }
+ // Image data layout after orientation (B=black, F=white):
+ // BF
+ // BF
+ // BB
+ var imageData = img.getContext('2d').getImageData(0, 0, 2, 3).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque white
+ expect(imageData[0 + 4]).to.equal(255)
+ expect(imageData[1 + 4]).to.equal(255)
+ expect(imageData[2 + 4]).to.equal(255)
+ expect(imageData[3 + 4]).to.equal(255)
+ // 0:1 opaque black
+ expect(imageData[0 + 8]).to.equal(0)
+ expect(imageData[1 + 8]).to.equal(0)
+ expect(imageData[2 + 8]).to.equal(0)
+ expect(imageData[3 + 8]).to.equal(255)
+ // 1:1 opaque white
+ expect(imageData[0 + 12]).to.equal(255)
+ expect(imageData[1 + 12]).to.equal(255)
+ expect(imageData[2 + 12]).to.equal(255)
+ expect(imageData[3 + 12]).to.equal(255)
+ // 0:2 opaque black
+ expect(imageData[0 + 16]).to.equal(0)
+ expect(imageData[1 + 16]).to.equal(0)
+ expect(imageData[2 + 16]).to.equal(0)
+ expect(imageData[3 + 16]).to.equal(255)
+ // 1:2 opaque black
+ expect(imageData[0 + 20]).to.equal(0)
+ expect(imageData[1 + 20]).to.equal(0)
+ expect(imageData[2 + 20]).to.equal(0)
+ expect(imageData[3 + 20]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 7,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('8: 90° rotate left', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(2)
+ expect(img.height).to.equal(3)
+ // Image data layout after orientation (B=black, F=white):
+ // FB
+ // FB
+ // BB
+ var imageData = img.getContext('2d').getImageData(0, 0, 2, 3).data
+ // 0:0 opaque white
+ expect(imageData[0]).to.equal(255)
+ expect(imageData[1]).to.equal(255)
+ expect(imageData[2]).to.equal(255)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ // 0:1 opaque white
+ expect(imageData[0 + 8]).to.equal(255)
+ expect(imageData[1 + 8]).to.equal(255)
+ expect(imageData[2 + 8]).to.equal(255)
+ expect(imageData[3 + 8]).to.equal(255)
+ // 1:1 opaque black
+ expect(imageData[0 + 12]).to.equal(0)
+ expect(imageData[1 + 12]).to.equal(0)
+ expect(imageData[2 + 12]).to.equal(0)
+ expect(imageData[3 + 12]).to.equal(255)
+ // 0:2 opaque black
+ expect(imageData[0 + 16]).to.equal(0)
+ expect(imageData[1 + 16]).to.equal(0)
+ expect(imageData[2 + 16]).to.equal(0)
+ expect(imageData[3 + 16]).to.equal(255)
+ // 1:2 opaque black
+ expect(imageData[0 + 20]).to.equal(0)
+ expect(imageData[1 + 20]).to.equal(0)
+ expect(imageData[2 + 20]).to.equal(0)
+ expect(imageData[3 + 20]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 8,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('true: follow EXIF Orientation value', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(2)
+ expect(img.height).to.equal(3)
+ // Image data layout after orientation (B=black, F=white):
+ // BB
+ // BF
+ // BF
+ var imageData = img.getContext('2d').getImageData(0, 0, 2, 3).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ // 0:1 opaque black
+ expect(imageData[0 + 8]).to.equal(0)
+ expect(imageData[1 + 8]).to.equal(0)
+ expect(imageData[2 + 8]).to.equal(0)
+ expect(imageData[3 + 8]).to.equal(255)
+ // 1:1 opaque white
+ expect(imageData[0 + 12]).to.equal(255)
+ expect(imageData[1 + 12]).to.equal(255)
+ expect(imageData[2 + 12]).to.equal(255)
+ expect(imageData[3 + 12]).to.equal(255)
+ // 0:2 opaque black
+ expect(imageData[0 + 16]).to.equal(0)
+ expect(imageData[1 + 16]).to.equal(0)
+ expect(imageData[2 + 16]).to.equal(0)
+ expect(imageData[3 + 16]).to.equal(255)
+ // 1:2 opaque white
+ expect(imageData[0 + 20]).to.equal(255)
+ expect(imageData[1 + 20]).to.equal(255)
+ expect(imageData[2 + 20]).to.equal(255)
+ expect(imageData[3 + 20]).to.equal(255)
+ done()
+ },
+ {
+ orientation: true,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('Only use EXIF data and canvas if necessary', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img, data) {
+ expect(img.width).to.equal(2)
+ expect(img.height).to.equal(3)
+ expect(data).to.be.ok
+ if (loadImage.orientation) {
+ expect(data.exif).to.be.undefined
+ expect(img.getContext).to.be.undefined
+ } else {
+ expect(img.getContext).to.be.an.instanceOf(Function)
+ expect(data.exif).to.be.ok
+ expect(data.exif.get('Orientation')).to.equal(6)
+ }
+ done()
+ },
+ { orientation: true }
+ )
+ ).to.be.ok
+ })
+
+ it('Scale image after EXIF based orientation', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(20)
+ expect(img.height).to.equal(30)
+ done()
+ },
+ { orientation: true, minWidth: 20, minHeight: 30 }
+ )
+ ).to.be.ok
+ })
+
+ it('Provide original image width+height from before orientation', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img, data) {
+ expect(data.originalWidth).to.equal(3)
+ expect(data.originalHeight).to.equal(2)
+ done()
+ },
+ { meta: true, minWidth: 20, minHeight: 30 }
+ )
+ ).to.be.ok
+ })
+
+ describe('Cropping', function () {
+ it('1: keep original, right: 1, bottom: 1', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(2)
+ expect(img.height).to.equal(1)
+ // Image data layout after orientation (B=black, F=white):
+ // BF
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 2, 1).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque white
+ expect(imageData[0 + 4]).to.equal(255)
+ expect(imageData[1 + 4]).to.equal(255)
+ expect(imageData[2 + 4]).to.equal(255)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 1,
+ right: 1,
+ bottom: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('2: horizontal flip, bottom: 1, left: 1', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(2)
+ expect(img.height).to.equal(1)
+ if (!browser.exactImageData) {
+ done()
+ return
+ }
+ // Image data layout after orientation (B=black, F=white):
+ // FB
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 2, 1).data
+ // 0:0 opaque white
+ expect(imageData[0]).to.equal(255)
+ expect(imageData[1]).to.equal(255)
+ expect(imageData[2]).to.equal(255)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 2,
+ bottom: 1,
+ left: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('3: 180° rotate left, top: 1, left: 1', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(2)
+ expect(img.height).to.equal(1)
+ // Image data layout after orientation (B=black, F=white):
+ // FB
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 2, 1).data
+ // 0:0 opaque white
+ expect(imageData[0]).to.equal(255)
+ expect(imageData[1]).to.equal(255)
+ expect(imageData[2]).to.equal(255)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 3,
+ top: 1,
+ left: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('4: vertical flip, top: 1, right: 1', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(2)
+ expect(img.height).to.equal(1)
+ if (!browser.exactImageData) {
+ done()
+ return
+ }
+ // Image data layout after orientation (B=black, F=white):
+ // BF
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 2, 1).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 1:0 opaque white
+ expect(imageData[0 + 4]).to.equal(255)
+ expect(imageData[1 + 4]).to.equal(255)
+ expect(imageData[2 + 4]).to.equal(255)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 4,
+ top: 1,
+ right: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('5: vertical flip + 90° rotate right, right: 1, bottom: 1', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(1)
+ expect(img.height).to.equal(2)
+ if (!browser.exactImageData) {
+ done()
+ return
+ }
+ // Image data layout after orientation (B=black, F=white):
+ // B
+ // F
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 1, 2).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 0:1 opaque white
+ expect(imageData[0 + 4]).to.equal(255)
+ expect(imageData[1 + 4]).to.equal(255)
+ expect(imageData[2 + 4]).to.equal(255)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 5,
+ right: 1,
+ bottom: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('6: 90° rotate right, bottom: 1, left: 1', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(1)
+ expect(img.height).to.equal(2)
+ // Image data layout after orientation (B=black, F=white):
+ // B
+ // F
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 1, 2).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 0:1 opaque white
+ expect(imageData[0 + 4]).to.equal(255)
+ expect(imageData[1 + 4]).to.equal(255)
+ expect(imageData[2 + 4]).to.equal(255)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 6,
+ bottom: 1,
+ left: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('7: horizontal flip + 90° rotate right, top: 1, left: 1', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(1)
+ expect(img.height).to.equal(2)
+ if (!browser.exactImageData) {
+ done()
+ return
+ }
+ // Image data layout after orientation (B=black, F=white):
+ // F
+ // B
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 1, 2).data
+ // 0:0 opaque white
+ expect(imageData[0]).to.equal(255)
+ expect(imageData[1]).to.equal(255)
+ expect(imageData[2]).to.equal(255)
+ expect(imageData[3]).to.equal(255)
+ // 0:1 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 7,
+ top: 1,
+ left: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('8: 90° rotate left, top: 1, right: 1', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(1)
+ expect(img.height).to.equal(2)
+ // Image data layout after orientation (B=black, F=white):
+ // F
+ // B
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 1, 2).data
+ // 0:0 opaque white
+ expect(imageData[0]).to.equal(255)
+ expect(imageData[1]).to.equal(255)
+ expect(imageData[2]).to.equal(255)
+ expect(imageData[3]).to.equal(255)
+ // 0:1 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: 8,
+ top: 1,
+ right: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('true: follow EXIF Orientation value, bottom: 1, left: 1', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(1)
+ expect(img.height).to.equal(2)
+ // Image data layout after orientation (B=black, F=white):
+ // B
+ // F
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 1, 2).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 0:1 opaque white
+ expect(imageData[0 + 4]).to.equal(255)
+ expect(imageData[1 + 4]).to.equal(255)
+ expect(imageData[2 + 4]).to.equal(255)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: true,
+ left: 1,
+ bottom: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('true: follow EXIF Orientation value, top: 1, left: 1', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(1)
+ expect(img.height).to.equal(2)
+ // Image data layout after orientation (B=black, F=white):
+ // F
+ // F
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 1, 2).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(255)
+ expect(imageData[1]).to.equal(255)
+ expect(imageData[2]).to.equal(255)
+ expect(imageData[3]).to.equal(255)
+ // 0:1 opaque black
+ expect(imageData[0 + 4]).to.equal(255)
+ expect(imageData[1 + 4]).to.equal(255)
+ expect(imageData[2 + 4]).to.equal(255)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: true,
+ top: 1,
+ left: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('true: follow EXIF Orientation value, top: 1, right: 1', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(1)
+ expect(img.height).to.equal(2)
+ // Image data layout after orientation (B=black, F=white):
+ // B
+ // B
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 1, 2).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 0:1 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: true,
+ top: 1,
+ right: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+
+ it('true: follow EXIF Orientation value, right: 1, bottom: 1', function (done) {
+ expect(
+ loadImage(
+ blobJPEG,
+ function (img) {
+ expect(img.width).to.equal(1)
+ expect(img.height).to.equal(2)
+ // Image data layout after orientation (B=black, F=white):
+ // B
+ // B
+ var imageData = img
+ .getContext('2d')
+ .getImageData(0, 0, 1, 2).data
+ // 0:0 opaque black
+ expect(imageData[0]).to.equal(0)
+ expect(imageData[1]).to.equal(0)
+ expect(imageData[2]).to.equal(0)
+ expect(imageData[3]).to.equal(255)
+ // 0:1 opaque black
+ expect(imageData[0 + 4]).to.equal(0)
+ expect(imageData[1 + 4]).to.equal(0)
+ expect(imageData[2 + 4]).to.equal(0)
+ expect(imageData[3 + 4]).to.equal(255)
+ done()
+ },
+ {
+ orientation: true,
+ right: 1,
+ bottom: 1,
+ meta: true,
+ canvas: true,
+ imageSmoothingEnabled: false
+ }
+ )
+ ).to.be.ok
+ })
+ })
})
})
- describe('Canvas', function() {
- it('Return img element to callback if canvas is not true', function(done) {
- expect(
- loadImage(blobGIF, function(img) {
- expect(img.getContext).to.be.undefined
- expect(img.nodeName.toLowerCase()).to.equal('img')
+ describe('Metadata', function () {
+ if (!window.DataView || !loadImage.blobSlice) return
+
+ it('Parse EXIF tags', function (done) {
+ loadImage.parseMetaData(blobJPEG, function (data) {
+ expect(data.exif).to.be.ok
+ expect(data.exif.get('Orientation')).to.equal(6)
+ done()
+ })
+ })
+
+ it('Do not parse EXIF tags if disabled', function (done) {
+ loadImage.parseMetaData(
+ blobJPEG,
+ function (data) {
+ expect(data.exif).to.be.undefined
done()
- })
- ).to.be.ok
+ },
+ { disableExif: true }
+ )
})
- it('Return canvas element to callback if canvas is true', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- expect(img.getContext).to.be.ok
- expect(img.nodeName.toLowerCase()).to.equal('canvas')
- done()
- },
- { canvas: true }
- )
- ).to.be.ok
+ it('Parse EXIF tag offsets', function (done) {
+ loadImage.parseMetaData(blobJPEG, function (data) {
+ expect(data.exifOffsets).to.be.ok
+ expect(data.exifOffsets.get('Orientation')).to.equal(0x16)
+ expect(data.exifTiffOffset).to.equal(0xc)
+ expect(data.exifLittleEndian).to.equal(false)
+ done()
+ })
})
- it('Return scaled canvas element to callback', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- expect(img.getContext).to.be.ok
- expect(img.nodeName.toLowerCase()).to.equal('canvas')
- expect(img.width).to.equal(40)
- expect(img.height).to.equal(30)
- done()
- },
- { canvas: true, maxWidth: 40 }
- )
- ).to.be.ok
+ it('Do not parse EXIF tag offsets if disabled', function (done) {
+ loadImage.parseMetaData(
+ blobJPEG,
+ function (data) {
+ expect(data.exifOffsets).to.be.undefined
+ done()
+ },
+ { disableExifOffsets: true }
+ )
})
- it('Accept a canvas element as parameter for loadImage.scale', function(done) {
- expect(
- loadImage(
- blobGIF,
- function(img) {
- // eslint-disable-next-line no-param-reassign
- img = loadImage.scale(img, {
- maxWidth: 40
- })
- expect(img.getContext).to.be.ok
- expect(img.nodeName.toLowerCase()).to.equal('canvas')
- expect(img.width).to.equal(40)
- expect(img.height).to.equal(30)
- done()
- },
- { canvas: true }
- )
- ).to.be.ok
+ it('Only parse included EXIF tags', function (done) {
+ loadImage.parseMetaData(
+ blobJPEG,
+ function (data) {
+ expect(data.exif).to.be.ok
+ expect(data.exif.get('Orientation')).to.equal(6)
+ loadImage.parseMetaData(
+ blobJPEG,
+ function (data) {
+ expect(data.exif).to.be.ok
+ expect(data.exif.get('Orientation')).to.be.undefined
+ done()
+ },
+ { includeExifTags: { 0x0132: true } } // DateTime
+ )
+ },
+ { includeExifTags: { 0x0112: true } } // Orientation
+ )
})
- })
- describe('Metadata', function() {
- it('Should parse Exif tags', function(done) {
- loadImage.parseMetaData(blobJPEG, function(data) {
- expect(data.exif).to.be.ok
- expect(data.exif.get('Orientation')).to.equal(6)
+ it('Do not parse excluded EXIF tags', function (done) {
+ loadImage.parseMetaData(
+ blobJPEG,
+ function (data) {
+ expect(data.exif).to.be.ok
+ expect(data.exif.get('Orientation')).to.equal(6)
+ loadImage.parseMetaData(
+ blobJPEG,
+ function (data) {
+ expect(data.exif).to.be.ok
+ expect(data.exif.get('Orientation')).to.be.undefined
+ done()
+ },
+ { excludeExifTags: { 0x0112: true } } // Orientation
+ )
+ },
+ { excludeExifTags: { 0x0132: true } } // DateTime
+ )
+ })
+
+ it('Parse IPTC tags', function (done) {
+ loadImage.parseMetaData(blobJPEG, function (data) {
+ expect(data.iptc).to.be.ok
+ expect(data.iptc.get('ObjectName')).to.equal('blueimp.net')
done()
})
})
- it('Should parse IPTC tags', function(done) {
- loadImage.parseMetaData(blobJPEG, function(data) {
- expect(data.iptc).to.be.ok
- expect(data.iptc.get('ObjectName')).to.equal('objectname')
+ it('Do not parse IPTC tags if disabled', function (done) {
+ loadImage.parseMetaData(
+ blobJPEG,
+ function (data) {
+ expect(data.iptc).to.be.undefined
+ done()
+ },
+ { disableIptc: true }
+ )
+ })
+
+ it('Parse IPTC tag offsets', function (done) {
+ loadImage.parseMetaData(blobJPEG, function (data) {
+ expect(data.iptcOffsets).to.be.ok
+ expect(data.iptcOffsets.get('ObjectName')).to.equal(0x44)
done()
})
})
- it('Should parse the complete image head', function(done) {
- loadImage.parseMetaData(blobJPEG, function(data) {
+ it('Do not parse IPTC tag offsets if disabled', function (done) {
+ loadImage.parseMetaData(
+ blobJPEG,
+ function (data) {
+ expect(data.iptcOffsets).to.be.undefined
+ done()
+ },
+ { disableIptcOffsets: true }
+ )
+ })
+
+ it('Only parse included IPTC tags', function (done) {
+ loadImage.parseMetaData(
+ blobJPEG,
+ function (data) {
+ expect(data.iptc).to.be.ok
+ expect(data.iptc.get('ApplicationRecordVersion')).to.be.undefined
+ expect(data.iptc.get('ObjectName')).to.equal('blueimp.net')
+ loadImage.parseMetaData(
+ blobJPEG,
+ function (data) {
+ expect(data.iptc).to.be.ok
+ expect(data.iptc.get('ApplicationRecordVersion')).to.equal(4)
+ expect(data.iptc.get('ObjectName')).to.be.undefined
+ done()
+ },
+ { includeIptcTags: { 0: true } } // ApplicationRecordVersion
+ )
+ },
+ { includeIptcTags: { 5: true } } // ObjectName
+ )
+ })
+
+ it('Do not parse excluded IPTC tags', function (done) {
+ loadImage.parseMetaData(
+ blobJPEG,
+ function (data) {
+ expect(data.iptc).to.be.ok
+ expect(data.iptc.get('ApplicationRecordVersion')).to.equal(4)
+ expect(data.iptc.get('ObjectName')).to.be.undefined
+ loadImage.parseMetaData(
+ blobJPEG,
+ function (data) {
+ expect(data.iptc).to.be.ok
+ expect(data.iptc.get('ApplicationRecordVersion')).to.be.undefined
+ expect(data.iptc.get('ObjectName')).to.equal('blueimp.net')
+ done()
+ },
+ { excludeIptcTags: { 0: true } } // Orientation
+ )
+ },
+ { excludeIptcTags: { 5: true } } // DateTime
+ )
+ })
+
+ it('Parse the complete image head', function (done) {
+ loadImage.parseMetaData(blobJPEG, function (data) {
expect(data.imageHead).to.be.ok
loadImage.parseMetaData(
createBlob(data.imageHead, 'image/jpeg'),
- function(data) {
+ function (data) {
expect(data.exif).to.be.ok
expect(data.exif.get('Orientation')).to.equal(6)
done()
@@ -856,59 +2631,199 @@
})
})
- it('Should parse meta data automatically', function(done) {
+ it('Do not parse the complete image head if disabled', function (done) {
+ loadImage.parseMetaData(
+ blobJPEG,
+ function (data) {
+ expect(data.imageHead).to.be.undefined
+ done()
+ },
+ { disableImageHead: true }
+ )
+ })
+
+ it('Parse metadata automatically', function (done) {
expect(
loadImage(
blobJPEG,
- function(img, data) {
+ function (img, data) {
expect(data).to.be.ok
expect(data.imageHead).to.be.ok
expect(data.exif).to.be.ok
expect(data.exif.get('Orientation')).to.equal(6)
expect(data.iptc).to.be.ok
- expect(data.iptc.get('ObjectName')).to.equal('objectname')
+ expect(data.iptc.get('ObjectName')).to.equal('blueimp.net')
done()
},
{ meta: true }
)
).to.be.ok
})
- })
- if (
- ('fetch' in window && 'Request' in window) ||
- ('XMLHttpRequest' in window && 'ProgressEvent' in window)
- ) {
- describe('Fetch', function() {
- it('Should fetch image URL as blob if meta option is true', function(done) {
- expect(
- loadImage(
- imageUrlJPEG,
- function(img, data) {
- expect(data).to.be.ok
- expect(data.imageHead).to.be.ok
+ it('Write EXIF Orientation tag and replace image head', function (done) {
+ loadImage(
+ blobJPEG,
+ function (img, data) {
+ expect(data.imageHead).to.be.ok
+ expect(data.exif).to.be.ok
+ expect(data.exif.get('Orientation')).to.equal(6)
+ expect(data.iptc).to.be.ok
+ expect(data.iptc.get('ObjectName')).to.equal('blueimp.net')
+ // Reset EXIF Orientation data:
+ var buffer = loadImage.writeExifData(
+ data.imageHead,
+ data,
+ 'Orientation',
+ 1
+ )
+ // Check if Orientation writer changes image head buffer in place:
+ expect(buffer).to.equal(data.imageHead)
+ img.toBlob(function (blob) {
+ loadImage.replaceHead(blob, data.imageHead, function (newBlob) {
+ loadImage(
+ newBlob,
+ function (img, data) {
+ expect(img.width).to.equal(40)
+ expect(img.height).to.equal(60)
+ expect(data.imageHead).to.be.ok
+ expect(data.exif).to.be.ok
+ expect(data.exif.get('Orientation')).to.equal(1)
+ expect(data.iptc).to.be.ok
+ expect(data.iptc.get('ObjectName')).to.equal('blueimp.net')
+ done()
+ },
+ { meta: true }
+ )
+ })
+ }, 'image/jpeg')
+ },
+ { meta: true, orientation: true, canvas: true, minWidth: 40 }
+ )
+ })
+
+ describe('Promise', function () {
+ if (!window.Promise) return
+
+ it('Parse the complete image head', function () {
+ return loadImage.parseMetaData(blobJPEG).then(function (data) {
+ expect(data.imageHead).to.be.ok
+ return loadImage
+ .parseMetaData(createBlob(data.imageHead, 'image/jpeg'))
+ .then(function (data) {
expect(data.exif).to.be.ok
expect(data.exif.get('Orientation')).to.equal(6)
+ })
+ })
+ })
+
+ it('Write EXIF Orientation tag and replace image head', function () {
+ return loadImage(blobJPEG, {
+ meta: true,
+ orientation: true,
+ canvas: true,
+ minWidth: 40
+ })
+ .then(function (data) {
+ expect(data.imageHead).to.be.ok
+ expect(data.exif).to.be.ok
+ expect(data.exif.get('Orientation')).to.equal(6)
+ expect(data.iptc).to.be.ok
+ expect(data.iptc.get('ObjectName')).to.equal('blueimp.net')
+ // Reset EXIF Orientation data:
+ var buffer = loadImage.writeExifData(
+ data.imageHead,
+ data,
+ 'Orientation',
+ 1
+ )
+ // Check if Orientation writer changes image head buffer in place:
+ expect(buffer).to.equal(data.imageHead)
+ return new Promise(function (resolve) {
+ data.image.toBlob(function (blob) {
+ data.blob = blob
+ resolve(data)
+ }, 'image/jpeg')
+ })
+ })
+ .then(function (data) {
+ return loadImage.replaceHead(data.blob, data.imageHead)
+ })
+ .then(function (blob) {
+ return loadImage(blob, { meta: true }).then(function (data) {
+ var img = data.image
+ expect(img.width).to.equal(40)
+ expect(img.height).to.equal(60)
+ expect(data.imageHead).to.be.ok
+ expect(data.exif).to.be.ok
+ expect(data.exif.get('Orientation')).to.equal(1)
expect(data.iptc).to.be.ok
- expect(data.iptc.get('ObjectName')).to.equal('objectname')
- done()
- },
- { meta: true }
- )
- ).to.be.ok
+ expect(data.iptc.get('ObjectName')).to.equal('blueimp.net')
+ })
+ })
})
+ })
+ })
- it('Should load image URL as img if meta option is false', function(done) {
- expect(
- loadImage(imageUrlJPEG, function(img, data) {
- expect(data.imageHead).to.be.undefined
- expect(data.exif).to.be.undefined
- expect(img.width).to.equal(2)
- expect(img.height).to.equal(1)
+ describe('Fetch', function () {
+ if (
+ !(window.fetch && window.Request) &&
+ !(window.XMLHttpRequest && window.ProgressEvent)
+ ) {
+ return
+ }
+
+ it('Fetch image URL as blob', function (done) {
+ // IE does not allow XMLHttpRequest access to data URLs,
+ // so we use an ObjectURL instead of imageUrlJPEG directly:
+ loadImage.fetchBlob(loadImage.createObjectURL(blobJPEG), function (blob) {
+ expect(blob).to.be.an.instanceOf(Blob)
+ done()
+ })
+ })
+
+ it('Fetch image URL as blob if meta option is true', function (done) {
+ expect(
+ loadImage(
+ // IE does not allow XMLHttpRequest access to data URLs,
+ // so we use an ObjectURL instead of imageUrlJPEG directly:
+ loadImage.createObjectURL(blobJPEG),
+ function (img, data) {
+ expect(data).to.be.ok
+ expect(data.imageHead).to.be.ok
+ expect(data.exif).to.be.ok
+ expect(data.exif.get('Orientation')).to.equal(6)
+ expect(data.iptc).to.be.ok
+ expect(data.iptc.get('ObjectName')).to.equal('blueimp.net')
done()
+ },
+ { meta: true }
+ )
+ ).to.be.ok
+ })
+
+ it('Load image URL as img if meta option is false', function (done) {
+ expect(
+ loadImage(imageUrlJPEG, function (img, data) {
+ expect(data.imageHead).to.be.undefined
+ expect(data.exif).to.be.undefined
+ expect(data.iptc).to.be.undefined
+ done()
+ })
+ ).to.be.ok
+ })
+
+ describe('Promise', function () {
+ if (!window.Promise) return
+
+ it('Fetch image URL as blob', function () {
+ // IE does not allow XMLHttpRequest access to data URLs,
+ // so we use an ObjectURL instead of imageUrlJPEG directly:
+ return loadImage
+ .fetchBlob(loadImage.createObjectURL(blobJPEG))
+ .then(function (blob) {
+ expect(blob).to.be.an.instanceOf(Blob)
})
- ).to.be.ok
})
})
- }
+ })
})(this.chai.expect, this.loadImage)
diff --git a/test/vendor/chai.js b/test/vendor/chai.js
index 39429c5..e1520f7 100644
--- a/test/vendor/chai.js
+++ b/test/vendor/chai.js
@@ -14,7 +14,7 @@ var used = [];
* Chai version
*/
-exports.version = '4.2.0';
+exports.version = '4.3.3';
/*!
* Assertion Error
@@ -95,7 +95,7 @@ exports.use(should);
var assert = require('./chai/interface/assert');
exports.use(assert);
-},{"./chai/assertion":3,"./chai/config":4,"./chai/core/assertions":5,"./chai/interface/assert":6,"./chai/interface/expect":7,"./chai/interface/should":8,"./chai/utils":22,"assertion-error":33}],3:[function(require,module,exports){
+},{"./chai/assertion":3,"./chai/config":4,"./chai/core/assertions":5,"./chai/interface/assert":6,"./chai/interface/expect":7,"./chai/interface/should":8,"./chai/utils":23,"assertion-error":34}],3:[function(require,module,exports){
/*!
* chai
* http://chaijs.com
@@ -236,11 +236,21 @@ module.exports = function (_chai, util) {
if (!ok) {
msg = util.getMessage(this, arguments);
var actual = util.getActual(this, arguments);
- throw new AssertionError(msg, {
+ var assertionErrorObjectProperties = {
actual: actual
, expected: expected
, showDiff: showDiff
- }, (config.includeStack) ? this.assert : flag(this, 'ssfi'));
+ };
+
+ var operator = util.getOperator(this, arguments);
+ if (operator) {
+ assertionErrorObjectProperties.operator = operator;
+ }
+
+ throw new AssertionError(
+ msg,
+ assertionErrorObjectProperties,
+ (config.includeStack) ? this.assert : flag(this, 'ssfi'));
}
};
@@ -395,6 +405,7 @@ module.exports = function (chai, _) {
* - but
* - does
* - still
+ * - also
*
* @name language chains
* @namespace BDD
@@ -404,7 +415,7 @@ module.exports = function (chai, _) {
[ 'to', 'be', 'been', 'is'
, 'and', 'has', 'have', 'with'
, 'that', 'which', 'at', 'of'
- , 'same', 'but', 'does', 'still' ].forEach(function (chain) {
+ , 'same', 'but', 'does', 'still', "also" ].forEach(function (chain) {
Assertion.addProperty(chain);
});
@@ -894,8 +905,13 @@ module.exports = function (chai, _) {
// objects with a custom `@@toStringTag`.
if (val !== Object(val)) {
throw new AssertionError(
- flagMsg + 'object tested must be an array, a map, an object,'
- + ' a set, a string, or a weakset, but ' + objType + ' given',
+ flagMsg + 'the given combination of arguments ('
+ + objType + ' and '
+ + _.type(val).toLowerCase() + ')'
+ + ' is invalid for this assertion. '
+ + 'You can use an array, a map, an object, a set, a string, '
+ + 'or a weakset instead of a '
+ + _.type(val).toLowerCase(),
undefined,
ssfi
);
@@ -1179,19 +1195,25 @@ module.exports = function (chai, _) {
*
* expect(null, 'nooo why fail??').to.exist;
*
+ * The alias `.exists` can be used interchangeably with `.exist`.
+ *
* @name exist
+ * @alias exists
* @namespace BDD
* @api public
*/
- Assertion.addProperty('exist', function () {
+ function assertExist () {
var val = flag(this, 'object');
this.assert(
val !== null && val !== undefined
, 'expected #{this} to exist'
, 'expected #{this} to not exist'
);
- });
+ }
+
+ Assertion.addProperty('exist', assertExist);
+ Assertion.addProperty('exists', assertExist);
/**
* ### .empty
@@ -1300,7 +1322,7 @@ module.exports = function (chai, _) {
*
* Add `.not` earlier in the chain to negate `.arguments`. However, it's often
* best to assert which type the target is expected to be, rather than
- * asserting that its not an `arguments` object.
+ * asserting that it’s not an `arguments` object.
*
* expect('foo').to.be.a('string'); // Recommended
* expect('foo').to.not.be.arguments; // Not recommended
@@ -1591,10 +1613,12 @@ module.exports = function (chai, _) {
* expect(1).to.be.at.least(2, 'nooo why fail??');
* expect(1, 'nooo why fail??').to.be.at.least(2);
*
- * The alias `.gte` can be used interchangeably with `.least`.
+ * The aliases `.gte` and `.greaterThanOrEqual` can be used interchangeably with
+ * `.least`.
*
* @name least
* @alias gte
+ * @alias greaterThanOrEqual
* @param {Number} n
* @param {String} msg _optional_
* @namespace BDD
@@ -1660,6 +1684,7 @@ module.exports = function (chai, _) {
Assertion.addMethod('least', assertLeast);
Assertion.addMethod('gte', assertLeast);
+ Assertion.addMethod('greaterThanOrEqual', assertLeast);
/**
* ### .below(n[, msg])
@@ -1797,10 +1822,12 @@ module.exports = function (chai, _) {
* expect(2).to.be.at.most(1, 'nooo why fail??');
* expect(2, 'nooo why fail??').to.be.at.most(1);
*
- * The alias `.lte` can be used interchangeably with `.most`.
+ * The aliases `.lte` and `.lessThanOrEqual` can be used interchangeably with
+ * `.most`.
*
* @name most
* @alias lte
+ * @alias lessThanOrEqual
* @param {Number} n
* @param {String} msg _optional_
* @namespace BDD
@@ -1866,6 +1893,7 @@ module.exports = function (chai, _) {
Assertion.addMethod('most', assertMost);
Assertion.addMethod('lte', assertMost);
+ Assertion.addMethod('lessThanOrEqual', assertMost);
/**
* ### .within(start, finish[, msg])
@@ -2282,7 +2310,7 @@ module.exports = function (chai, _) {
* a `descriptor`. The problem is that it creates uncertain expectations by
* asserting that the target either doesn't have a property descriptor with
* the given key `name`, or that it does have a property descriptor with the
- * given key `name` but its not deeply equal to the given `descriptor`. It's
+ * given key `name` but it’s not deeply equal to the given `descriptor`. It's
* often best to identify the exact output that's expected, and then write an
* assertion that only accepts that exact output.
*
@@ -3311,8 +3339,9 @@ module.exports = function (chai, _) {
new Assertion(obj, flagMsg, ssfi, true).is.a('number');
if (typeof expected !== 'number' || typeof delta !== 'number') {
flagMsg = flagMsg ? flagMsg + ': ' : '';
+ var deltaMessage = delta === undefined ? ", and a delta is required" : "";
throw new AssertionError(
- flagMsg + 'the arguments to closeTo or approximately must be numbers',
+ flagMsg + 'the arguments to closeTo or approximately must be numbers' + deltaMessage,
undefined,
ssfi
);
@@ -3478,6 +3507,14 @@ module.exports = function (chai, _) {
* expect(1).to.equal(1); // Recommended
* expect(1).to.not.be.oneOf([2, 3, 4]); // Not recommended
*
+ * It can also be chained with `.contain` or `.include`, which will work with
+ * both arrays and strings:
+ *
+ * expect('Today is sunny').to.contain.oneOf(['sunny', 'cloudy'])
+ * expect('Today is rainy').to.not.contain.oneOf(['sunny', 'cloudy'])
+ * expect([1,2,3]).to.contain.oneOf([3,4,5])
+ * expect([1,2,3]).to.not.contain.oneOf([4,5,6])
+ *
* `.oneOf` accepts an optional `msg` argument which is a custom error message
* to show when the assertion fails. The message can also be given as the
* second argument to `expect`.
@@ -3496,16 +3533,38 @@ module.exports = function (chai, _) {
if (msg) flag(this, 'message', msg);
var expected = flag(this, 'object')
, flagMsg = flag(this, 'message')
- , ssfi = flag(this, 'ssfi');
+ , ssfi = flag(this, 'ssfi')
+ , contains = flag(this, 'contains')
+ , isDeep = flag(this, 'deep');
new Assertion(list, flagMsg, ssfi, true).to.be.an('array');
- this.assert(
- list.indexOf(expected) > -1
- , 'expected #{this} to be one of #{exp}'
- , 'expected #{this} to not be one of #{exp}'
- , list
- , expected
- );
+ if (contains) {
+ this.assert(
+ list.some(function(possibility) { return expected.indexOf(possibility) > -1 })
+ , 'expected #{this} to contain one of #{exp}'
+ , 'expected #{this} to not contain one of #{exp}'
+ , list
+ , expected
+ );
+ } else {
+ if (isDeep) {
+ this.assert(
+ list.some(function(possibility) { return _.eql(expected, possibility) })
+ , 'expected #{this} to deeply equal one of #{exp}'
+ , 'expected #{this} to deeply equal one of #{exp}'
+ , list
+ , expected
+ );
+ } else {
+ this.assert(
+ list.indexOf(expected) > -1
+ , 'expected #{this} to be one of #{exp}'
+ , 'expected #{this} to not be one of #{exp}'
+ , list
+ , expected
+ );
+ }
+ }
}
Assertion.addMethod('oneOf', oneOf);
@@ -5993,7 +6052,7 @@ module.exports = function (chai, util) {
* assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {three: 'three'}]);
* assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]);
*
- * @name doesNotHaveAllKeys
+ * @name hasAnyDeepKeys
* @param {Mixed} object
* @param {Array|Object} keys
* @param {String} message
@@ -6427,7 +6486,7 @@ module.exports = function (chai, util) {
* Asserts that `set1` and `set2` have the same members in the same order.
* Uses a deep equality check.
*
- * assert.sameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { c: 3 } ], 'same deep ordered members');
+ * assert.sameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { c: 3 } ], 'same deep ordered members');
*
* @name sameDeepOrderedMembers
* @param {Array} set1
@@ -6448,8 +6507,8 @@ module.exports = function (chai, util) {
* Asserts that `set1` and `set2` don't have the same members in the same
* order. Uses a deep equality check.
*
- * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { z: 5 } ], 'not same deep ordered members');
- * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { c: 3 } ], 'not same deep ordered members');
+ * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { z: 5 } ], 'not same deep ordered members');
+ * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { c: 3 } ], 'not same deep ordered members');
*
* @name notSameDeepOrderedMembers
* @param {Array} set1
@@ -6869,7 +6928,7 @@ module.exports = function (chai, util) {
}
/**
- * ### .increasesButNotBy(function, object, property, [message])
+ * ### .increasesButNotBy(function, object, property, delta, [message])
*
* Asserts that a function does not increase a numeric object property or function's return value by an amount (delta).
*
@@ -6999,7 +7058,7 @@ module.exports = function (chai, util) {
* var fn = function() { obj.val = 5 };
* assert.doesNotDecreaseBy(fn, obj, 'val', 1);
*
- * @name doesNotDecrease
+ * @name doesNotDecreaseBy
* @param {Function} modifier function
* @param {Object} object or getter function
* @param {String} property name _optional_
@@ -7344,7 +7403,8 @@ module.exports = function (chai, util) {
if (this instanceof String
|| this instanceof Number
|| this instanceof Boolean
- || typeof Symbol === 'function' && this instanceof Symbol) {
+ || typeof Symbol === 'function' && this instanceof Symbol
+ || typeof BigInt === 'function' && this instanceof BigInt) {
return new Assertion(this.valueOf(), null, shouldGetter);
}
return new Assertion(this, null, shouldGetter);
@@ -7702,7 +7762,7 @@ module.exports = function addChainableMethod(ctx, name, method, chainingBehavior
});
};
-},{"../../chai":2,"./addLengthGuard":10,"./flag":15,"./proxify":30,"./transferFlags":32}],10:[function(require,module,exports){
+},{"../../chai":2,"./addLengthGuard":10,"./flag":15,"./proxify":31,"./transferFlags":33}],10:[function(require,module,exports){
var fnLengthDesc = Object.getOwnPropertyDescriptor(function () {}, 'length');
/*!
@@ -7834,7 +7894,7 @@ module.exports = function addMethod(ctx, name, method) {
ctx[name] = proxify(methodWrapper, name);
};
-},{"../../chai":2,"./addLengthGuard":10,"./flag":15,"./proxify":30,"./transferFlags":32}],12:[function(require,module,exports){
+},{"../../chai":2,"./addLengthGuard":10,"./flag":15,"./proxify":31,"./transferFlags":33}],12:[function(require,module,exports){
/*!
* Chai - addProperty utility
* Copyright(c) 2012-2014 Jake Luer
@@ -7908,7 +7968,7 @@ module.exports = function addProperty(ctx, name, getter) {
});
};
-},{"../../chai":2,"./flag":15,"./isProxyEnabled":25,"./transferFlags":32}],13:[function(require,module,exports){
+},{"../../chai":2,"./flag":15,"./isProxyEnabled":26,"./transferFlags":33}],13:[function(require,module,exports){
/*!
* Chai - compareByInspect utility
* Copyright(c) 2011-2016 Jake Luer
@@ -7941,7 +8001,7 @@ module.exports = function compareByInspect(a, b) {
return inspect(a) < inspect(b) ? -1 : 1;
};
-},{"./inspect":23}],14:[function(require,module,exports){
+},{"./inspect":24}],14:[function(require,module,exports){
/*!
* Chai - expectTypes utility
* Copyright(c) 2012-2014 Jake Luer
@@ -7994,7 +8054,7 @@ module.exports = function expectTypes(obj, types) {
}
};
-},{"./flag":15,"assertion-error":33,"type-detect":38}],15:[function(require,module,exports){
+},{"./flag":15,"assertion-error":34,"type-detect":39}],15:[function(require,module,exports){
/*!
* Chai - flag utility
* Copyright(c) 2012-2014 Jake Luer
@@ -8131,7 +8191,64 @@ module.exports = function getMessage(obj, args) {
return flagMsg ? flagMsg + ': ' + msg : msg;
};
-},{"./flag":15,"./getActual":16,"./objDisplay":26}],19:[function(require,module,exports){
+},{"./flag":15,"./getActual":16,"./objDisplay":27}],19:[function(require,module,exports){
+var type = require('type-detect');
+
+var flag = require('./flag');
+
+function isObjectType(obj) {
+ var objectType = type(obj);
+ var objectTypes = ['Array', 'Object', 'function'];
+
+ return objectTypes.indexOf(objectType) !== -1;
+}
+
+/**
+ * ### .getOperator(message)
+ *
+ * Extract the operator from error message.
+ * Operator defined is based on below link
+ * https://nodejs.org/api/assert.html#assert_assert.
+ *
+ * Returns the `operator` or `undefined` value for an Assertion.
+ *
+ * @param {Object} object (constructed Assertion)
+ * @param {Arguments} chai.Assertion.prototype.assert arguments
+ * @namespace Utils
+ * @name getOperator
+ * @api public
+ */
+
+module.exports = function getOperator(obj, args) {
+ var operator = flag(obj, 'operator');
+ var negate = flag(obj, 'negate');
+ var expected = args[3];
+ var msg = negate ? args[2] : args[1];
+
+ if (operator) {
+ return operator;
+ }
+
+ if (typeof msg === 'function') msg = msg();
+
+ msg = msg || '';
+ if (!msg) {
+ return undefined;
+ }
+
+ if (/\shave\s/.test(msg)) {
+ return undefined;
+ }
+
+ var isObject = isObjectType(expected);
+ if (/\snot\s/.test(msg)) {
+ return isObject ? 'notDeepStrictEqual' : 'notStrictEqual';
+ }
+
+ return isObject ? 'deepStrictEqual' : 'strictEqual';
+};
+
+},{"./flag":15,"type-detect":39}],20:[function(require,module,exports){
/*!
* Chai - getOwnEnumerableProperties utility
* Copyright(c) 2011-2016 Jake Luer
@@ -8162,7 +8279,7 @@ module.exports = function getOwnEnumerableProperties(obj) {
return Object.keys(obj).concat(getOwnEnumerablePropertySymbols(obj));
};
-},{"./getOwnEnumerablePropertySymbols":20}],20:[function(require,module,exports){
+},{"./getOwnEnumerablePropertySymbols":21}],21:[function(require,module,exports){
/*!
* Chai - getOwnEnumerablePropertySymbols utility
* Copyright(c) 2011-2016 Jake Luer
@@ -8191,7 +8308,7 @@ module.exports = function getOwnEnumerablePropertySymbols(obj) {
});
};
-},{}],21:[function(require,module,exports){
+},{}],22:[function(require,module,exports){
/*!
* Chai - getProperties utility
* Copyright(c) 2012-2014 Jake Luer
@@ -8229,7 +8346,7 @@ module.exports = function getProperties(object) {
return result;
};
-},{}],22:[function(require,module,exports){
+},{}],23:[function(require,module,exports){
/*!
* chai
* Copyright(c) 2011 Jake Luer
@@ -8403,7 +8520,12 @@ exports.isProxyEnabled = require('./isProxyEnabled');
exports.isNaN = require('./isNaN');
-},{"./addChainableMethod":9,"./addLengthGuard":10,"./addMethod":11,"./addProperty":12,"./compareByInspect":13,"./expectTypes":14,"./flag":15,"./getActual":16,"./getMessage":18,"./getOwnEnumerableProperties":19,"./getOwnEnumerablePropertySymbols":20,"./inspect":23,"./isNaN":24,"./isProxyEnabled":25,"./objDisplay":26,"./overwriteChainableMethod":27,"./overwriteMethod":28,"./overwriteProperty":29,"./proxify":30,"./test":31,"./transferFlags":32,"check-error":34,"deep-eql":35,"get-func-name":36,"pathval":37,"type-detect":38}],23:[function(require,module,exports){
+/*!
+ * getOperator method
+ */
+
+exports.getOperator = require('./getOperator');
+},{"./addChainableMethod":9,"./addLengthGuard":10,"./addMethod":11,"./addProperty":12,"./compareByInspect":13,"./expectTypes":14,"./flag":15,"./getActual":16,"./getMessage":18,"./getOperator":19,"./getOwnEnumerableProperties":20,"./getOwnEnumerablePropertySymbols":21,"./inspect":24,"./isNaN":25,"./isProxyEnabled":26,"./objDisplay":27,"./overwriteChainableMethod":28,"./overwriteMethod":29,"./overwriteProperty":30,"./proxify":31,"./test":32,"./transferFlags":33,"check-error":35,"deep-eql":36,"get-func-name":37,"pathval":38,"type-detect":39}],24:[function(require,module,exports){
// This is (almost) directly from Node.js utils
// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js
@@ -8624,6 +8746,9 @@ function formatPrimitive(ctx, value) {
case 'symbol':
return ctx.stylize(value.toString(), 'symbol');
+
+ case 'bigint':
+ return ctx.stylize(value.toString() + 'n', 'bigint');
}
// For some reason typeof null is "object", so special case here.
if (value === null) {
@@ -8781,7 +8906,7 @@ function objectToString(o) {
return Object.prototype.toString.call(o);
}
-},{"../config":4,"./getEnumerableProperties":17,"./getProperties":21,"get-func-name":36}],24:[function(require,module,exports){
+},{"../config":4,"./getEnumerableProperties":17,"./getProperties":22,"get-func-name":37}],25:[function(require,module,exports){
/*!
* Chai - isNaN utility
* Copyright(c) 2012-2015 Sakthipriyan Vairamani
@@ -8809,7 +8934,7 @@ function isNaN(value) {
// If ECMAScript 6's Number.isNaN is present, prefer that.
module.exports = Number.isNaN || isNaN;
-},{}],25:[function(require,module,exports){
+},{}],26:[function(require,module,exports){
var config = require('../config');
/*!
@@ -8835,7 +8960,7 @@ module.exports = function isProxyEnabled() {
typeof Reflect !== 'undefined';
};
-},{"../config":4}],26:[function(require,module,exports){
+},{"../config":4}],27:[function(require,module,exports){
/*!
* Chai - flag utility
* Copyright(c) 2012-2014 Jake Luer
@@ -8887,7 +9012,7 @@ module.exports = function objDisplay(obj) {
}
};
-},{"../config":4,"./inspect":23}],27:[function(require,module,exports){
+},{"../config":4,"./inspect":24}],28:[function(require,module,exports){
/*!
* Chai - overwriteChainableMethod utility
* Copyright(c) 2012-2014 Jake Luer
@@ -8958,7 +9083,7 @@ module.exports = function overwriteChainableMethod(ctx, name, method, chainingBe
};
};
-},{"../../chai":2,"./transferFlags":32}],28:[function(require,module,exports){
+},{"../../chai":2,"./transferFlags":33}],29:[function(require,module,exports){
/*!
* Chai - overwriteMethod utility
* Copyright(c) 2012-2014 Jake Luer
@@ -9052,7 +9177,7 @@ module.exports = function overwriteMethod(ctx, name, method) {
ctx[name] = proxify(overwritingMethodWrapper, name);
};
-},{"../../chai":2,"./addLengthGuard":10,"./flag":15,"./proxify":30,"./transferFlags":32}],29:[function(require,module,exports){
+},{"../../chai":2,"./addLengthGuard":10,"./flag":15,"./proxify":31,"./transferFlags":33}],30:[function(require,module,exports){
/*!
* Chai - overwriteProperty utility
* Copyright(c) 2012-2014 Jake Luer
@@ -9146,7 +9271,7 @@ module.exports = function overwriteProperty(ctx, name, getter) {
});
};
-},{"../../chai":2,"./flag":15,"./isProxyEnabled":25,"./transferFlags":32}],30:[function(require,module,exports){
+},{"../../chai":2,"./flag":15,"./isProxyEnabled":26,"./transferFlags":33}],31:[function(require,module,exports){
var config = require('../config');
var flag = require('./flag');
var getProperties = require('./getProperties');
@@ -9295,7 +9420,7 @@ function stringDistanceCapped(strA, strB, cap) {
return memo[strA.length][strB.length];
}
-},{"../config":4,"./flag":15,"./getProperties":21,"./isProxyEnabled":25}],31:[function(require,module,exports){
+},{"../config":4,"./flag":15,"./getProperties":22,"./isProxyEnabled":26}],32:[function(require,module,exports){
/*!
* Chai - test utility
* Copyright(c) 2012-2014 Jake Luer
@@ -9325,7 +9450,7 @@ module.exports = function test(obj, args) {
return negate ? !expr : expr;
};
-},{"./flag":15}],32:[function(require,module,exports){
+},{"./flag":15}],33:[function(require,module,exports){
/*!
* Chai - transferFlags utility
* Copyright(c) 2012-2014 Jake Luer
@@ -9372,7 +9497,7 @@ module.exports = function transferFlags(assertion, object, includeAll) {
}
};
-},{}],33:[function(require,module,exports){
+},{}],34:[function(require,module,exports){
/*!
* assertion-error
* Copyright(c) 2013 Jake Luer
@@ -9490,7 +9615,7 @@ AssertionError.prototype.toJSON = function (stack) {
return props;
};
-},{}],34:[function(require,module,exports){
+},{}],35:[function(require,module,exports){
'use strict';
/* !
@@ -9664,7 +9789,7 @@ module.exports = {
getConstructorName: getConstructorName,
};
-},{}],35:[function(require,module,exports){
+},{}],36:[function(require,module,exports){
'use strict';
/* globals Symbol: false, Uint8Array: false, WeakMap: false */
/*!
@@ -10121,7 +10246,7 @@ function isPrimitive(value) {
return value === null || typeof value !== 'object';
}
-},{"type-detect":38}],36:[function(require,module,exports){
+},{"type-detect":39}],37:[function(require,module,exports){
'use strict';
/* !
@@ -10167,7 +10292,7 @@ function getFuncName(aFunc) {
module.exports = getFuncName;
-},{}],37:[function(require,module,exports){
+},{}],38:[function(require,module,exports){
'use strict';
/* !
@@ -10246,13 +10371,20 @@ function parsePath(path) {
var str = path.replace(/([^\\])\[/g, '$1.[');
var parts = str.match(/(\\\.|[^.]+?)+/g);
return parts.map(function mapMatches(value) {
+ if (
+ value === 'constructor' ||
+ value === '__proto__' ||
+ value === 'prototype'
+ ) {
+ return {};
+ }
var regexp = /^\[(\d+)\]$/;
var mArr = regexp.exec(value);
var parsed = null;
if (mArr) {
parsed = { i: parseFloat(mArr[1]) };
} else {
- parsed = { p: value.replace(/\\([.\[\]])/g, '$1') };
+ parsed = { p: value.replace(/\\([.[\]])/g, '$1') };
}
return parsed;
@@ -10277,7 +10409,7 @@ function parsePath(path) {
function internalGetPathValue(obj, parsed, pathDepth) {
var temporaryValue = obj;
var res = null;
- pathDepth = (typeof pathDepth === 'undefined' ? parsed.length : pathDepth);
+ pathDepth = typeof pathDepth === 'undefined' ? parsed.length : pathDepth;
for (var i = 0; i < pathDepth; i++) {
var part = parsed[i];
@@ -10288,7 +10420,7 @@ function internalGetPathValue(obj, parsed, pathDepth) {
temporaryValue = temporaryValue[part.p];
}
- if (i === (pathDepth - 1)) {
+ if (i === pathDepth - 1) {
res = temporaryValue;
}
}
@@ -10322,7 +10454,7 @@ function internalSetPathValue(obj, val, parsed) {
part = parsed[i];
// If it's the last part of the path, we set the 'propName' value with the property name
- if (i === (pathDepth - 1)) {
+ if (i === pathDepth - 1) {
propName = typeof part.p === 'undefined' ? part.i : part.p;
// Now we set the property with the name held by 'propName' on object with the desired val
tempObj[propName] = val;
@@ -10369,7 +10501,10 @@ function getPathInfo(obj, path) {
var parsed = parsePath(path);
var last = parsed[parsed.length - 1];
var info = {
- parent: parsed.length > 1 ? internalGetPathValue(obj, parsed, parsed.length - 1) : obj,
+ parent:
+ parsed.length > 1 ?
+ internalGetPathValue(obj, parsed, parsed.length - 1) :
+ obj,
name: last.p || last.i,
value: internalGetPathValue(obj, parsed),
};
@@ -10460,7 +10595,7 @@ module.exports = {
setPathValue: setPathValue,
};
-},{}],38:[function(require,module,exports){
+},{}],39:[function(require,module,exports){
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
diff --git a/test/vendor/mocha.css b/test/vendor/mocha.css
index ec96b00..4ca8fcb 100644
--- a/test/vendor/mocha.css
+++ b/test/vendor/mocha.css
@@ -139,7 +139,6 @@ body {
#mocha .test .html-error {
overflow: auto;
color: black;
- line-height: 1.5;
display: block;
float: left;
clear: left;
diff --git a/test/vendor/mocha.js b/test/vendor/mocha.js
index 508a306..2c8a9c3 100644
--- a/test/vendor/mocha.js
+++ b/test/vendor/mocha.js
@@ -1,18076 +1,30844 @@
-(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i} promise determining if browser notification
- * permissible when fulfilled.
- */
-function isPermitted() {
- var permitted = {
- granted: function allow() {
- return Promise.resolve(true);
- },
- denied: function deny() {
- return Promise.resolve(false);
- },
- default: function ask() {
- return Notification.requestPermission().then(function(permission) {
- return permission === 'granted';
- });
- }
- };
-
- return permitted[Notification.permission]();
-}
-
-/**
- * @summary
- * Determines if notification should proceed.
- *
- * @description
- * Notification shall not proceed unless `value` is true.
- *
- * `value` will equal one of:
- *
- * true
(from `isPermitted`)
- * false
(from `isPermitted`)
- * undefined
(from `Promise.race`)
- *
- *
- * @private
- * @param {boolean|undefined} value - Determines if notification permissible.
- * @returns {Promise} Notification can proceed
- */
-function canNotify(value) {
- if (!value) {
- var why = value === false ? 'blocked' : 'unacknowledged';
- var reason = 'not permitted by user (' + why + ')';
- return Promise.reject(new Error(reason));
- }
- return Promise.resolve();
-}
-
-/**
- * Displays the notification.
- *
- * @private
- * @param {Runner} runner - Runner instance.
- */
-function display(runner) {
- var stats = runner.stats;
- var symbol = {
- cross: '\u274C',
- tick: '\u2705'
- };
- var logo = require('../../package').notifyLogo;
- var _message;
- var message;
- var title;
-
- if (stats.failures) {
- _message = stats.failures + ' of ' + stats.tests + ' tests failed';
- message = symbol.cross + ' ' + _message;
- title = 'Failed';
- } else {
- _message = stats.passes + ' tests passed in ' + stats.duration + 'ms';
- message = symbol.tick + ' ' + _message;
- title = 'Passed';
- }
-
- // Send notification
- var options = {
- badge: logo,
- body: message,
- dir: 'ltr',
- icon: logo,
- lang: 'en-US',
- name: 'mocha',
- requireInteraction: false,
- timestamp: Date.now()
- };
- var notification = new Notification(title, options);
-
- // Autoclose after brief delay (makes various browsers act same)
- var FORCE_DURATION = 4000;
- setTimeout(notification.close.bind(notification), FORCE_DURATION);
-}
-
-/**
- * As notifications are tangential to our purpose, just log the error.
- *
- * @private
- * @param {Error} err - Why notification didn't happen.
- */
-function notPermitted(err) {
- console.error('notification error:', err.message);
-}
-
-}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"../../package":90,"../runner":34,"_process":69}],3:[function(require,module,exports){
-'use strict';
-
-/**
- * Expose `Progress`.
- */
-
-module.exports = Progress;
-
-/**
- * Initialize a new `Progress` indicator.
- */
-function Progress() {
- this.percent = 0;
- this.size(0);
- this.fontSize(11);
- this.font('helvetica, arial, sans-serif');
-}
-
-/**
- * Set progress size to `size`.
- *
- * @public
- * @param {number} size
- * @return {Progress} Progress instance.
- */
-Progress.prototype.size = function(size) {
- this._size = size;
- return this;
-};
-
-/**
- * Set text to `text`.
- *
- * @public
- * @param {string} text
- * @return {Progress} Progress instance.
- */
-Progress.prototype.text = function(text) {
- this._text = text;
- return this;
-};
-
-/**
- * Set font size to `size`.
- *
- * @public
- * @param {number} size
- * @return {Progress} Progress instance.
- */
-Progress.prototype.fontSize = function(size) {
- this._fontSize = size;
- return this;
-};
-
-/**
- * Set font to `family`.
- *
- * @param {string} family
- * @return {Progress} Progress instance.
- */
-Progress.prototype.font = function(family) {
- this._font = family;
- return this;
-};
-
-/**
- * Update percentage to `n`.
- *
- * @param {number} n
- * @return {Progress} Progress instance.
- */
-Progress.prototype.update = function(n) {
- this.percent = n;
- return this;
-};
-
-/**
- * Draw on `ctx`.
- *
- * @param {CanvasRenderingContext2d} ctx
- * @return {Progress} Progress instance.
- */
-Progress.prototype.draw = function(ctx) {
- try {
- var percent = Math.min(this.percent, 100);
- var size = this._size;
- var half = size / 2;
- var x = half;
- var y = half;
- var rad = half - 1;
- var fontSize = this._fontSize;
-
- ctx.font = fontSize + 'px ' + this._font;
-
- var angle = Math.PI * 2 * (percent / 100);
- ctx.clearRect(0, 0, size, size);
-
- // outer circle
- ctx.strokeStyle = '#9f9f9f';
- ctx.beginPath();
- ctx.arc(x, y, rad, 0, angle, false);
- ctx.stroke();
-
- // inner circle
- ctx.strokeStyle = '#eee';
- ctx.beginPath();
- ctx.arc(x, y, rad - 1, 0, angle, true);
- ctx.stroke();
-
- // text
- var text = this._text || (percent | 0) + '%';
- var w = ctx.measureText(text).width;
-
- ctx.fillText(text, x - w / 2 + 1, y + fontSize / 2 - 1);
- } catch (ignore) {
- // don't fail if we can't render progress
- }
- return this;
-};
-
-},{}],4:[function(require,module,exports){
-(function (global){
-'use strict';
-
-exports.isatty = function isatty() {
- return true;
-};
-
-exports.getWindowSize = function getWindowSize() {
- if ('innerHeight' in global) {
- return [global.innerHeight, global.innerWidth];
- }
- // In a Web Worker, the DOM Window is not available.
- return [640, 480];
-};
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],5:[function(require,module,exports){
-'use strict';
-/**
- * @module Context
- */
-/**
- * Expose `Context`.
- */
-
-module.exports = Context;
-
-/**
- * Initialize a new `Context`.
- *
- * @private
- */
-function Context() {}
-
-/**
- * Set or get the context `Runnable` to `runnable`.
- *
- * @private
- * @param {Runnable} runnable
- * @return {Context} context
- */
-Context.prototype.runnable = function(runnable) {
- if (!arguments.length) {
- return this._runnable;
- }
- this.test = this._runnable = runnable;
- return this;
-};
-
-/**
- * Set or get test timeout `ms`.
- *
- * @private
- * @param {number} ms
- * @return {Context} self
- */
-Context.prototype.timeout = function(ms) {
- if (!arguments.length) {
- return this.runnable().timeout();
- }
- this.runnable().timeout(ms);
- return this;
-};
-
-/**
- * Set test timeout `enabled`.
- *
- * @private
- * @param {boolean} enabled
- * @return {Context} self
- */
-Context.prototype.enableTimeouts = function(enabled) {
- if (!arguments.length) {
- return this.runnable().enableTimeouts();
- }
- this.runnable().enableTimeouts(enabled);
- return this;
-};
-
-/**
- * Set or get test slowness threshold `ms`.
- *
- * @private
- * @param {number} ms
- * @return {Context} self
- */
-Context.prototype.slow = function(ms) {
- if (!arguments.length) {
- return this.runnable().slow();
- }
- this.runnable().slow(ms);
- return this;
-};
-
-/**
- * Mark a test as skipped.
- *
- * @private
- * @throws Pending
- */
-Context.prototype.skip = function() {
- this.runnable().skip();
-};
-
-/**
- * Set or get a number of allowed retries on failed tests
- *
- * @private
- * @param {number} n
- * @return {Context} self
- */
-Context.prototype.retries = function(n) {
- if (!arguments.length) {
- return this.runnable().retries();
- }
- this.runnable().retries(n);
- return this;
-};
-
-},{}],6:[function(require,module,exports){
-'use strict';
-/**
- * @module Errors
- */
-/**
- * Factory functions to create throwable error objects
- */
-
-/**
- * Creates an error object to be thrown when no files to be tested could be found using specified pattern.
- *
- * @public
- * @param {string} message - Error message to be displayed.
- * @param {string} pattern - User-specified argument value.
- * @returns {Error} instance detailing the error condition
- */
-function createNoFilesMatchPatternError(message, pattern) {
- var err = new Error(message);
- err.code = 'ERR_MOCHA_NO_FILES_MATCH_PATTERN';
- err.pattern = pattern;
- return err;
-}
-
-/**
- * Creates an error object to be thrown when the reporter specified in the options was not found.
- *
- * @public
- * @param {string} message - Error message to be displayed.
- * @param {string} reporter - User-specified reporter value.
- * @returns {Error} instance detailing the error condition
- */
-function createInvalidReporterError(message, reporter) {
- var err = new TypeError(message);
- err.code = 'ERR_MOCHA_INVALID_REPORTER';
- err.reporter = reporter;
- return err;
-}
-
-/**
- * Creates an error object to be thrown when the interface specified in the options was not found.
- *
- * @public
- * @param {string} message - Error message to be displayed.
- * @param {string} ui - User-specified interface value.
- * @returns {Error} instance detailing the error condition
- */
-function createInvalidInterfaceError(message, ui) {
- var err = new Error(message);
- err.code = 'ERR_MOCHA_INVALID_INTERFACE';
- err.interface = ui;
- return err;
-}
-
-/**
- * Creates an error object to be thrown when a behavior, option, or parameter is unsupported.
- *
- * @public
- * @param {string} message - Error message to be displayed.
- * @returns {Error} instance detailing the error condition
- */
-function createUnsupportedError(message) {
- var err = new Error(message);
- err.code = 'ERR_MOCHA_UNSUPPORTED';
- return err;
-}
-
-/**
- * Creates an error object to be thrown when an argument is missing.
- *
- * @public
- * @param {string} message - Error message to be displayed.
- * @param {string} argument - Argument name.
- * @param {string} expected - Expected argument datatype.
- * @returns {Error} instance detailing the error condition
- */
-function createMissingArgumentError(message, argument, expected) {
- return createInvalidArgumentTypeError(message, argument, expected);
-}
-
-/**
- * Creates an error object to be thrown when an argument did not use the supported type
- *
- * @public
- * @param {string} message - Error message to be displayed.
- * @param {string} argument - Argument name.
- * @param {string} expected - Expected argument datatype.
- * @returns {Error} instance detailing the error condition
- */
-function createInvalidArgumentTypeError(message, argument, expected) {
- var err = new TypeError(message);
- err.code = 'ERR_MOCHA_INVALID_ARG_TYPE';
- err.argument = argument;
- err.expected = expected;
- err.actual = typeof argument;
- return err;
-}
-
-/**
- * Creates an error object to be thrown when an argument did not use the supported value
- *
- * @public
- * @param {string} message - Error message to be displayed.
- * @param {string} argument - Argument name.
- * @param {string} value - Argument value.
- * @param {string} [reason] - Why value is invalid.
- * @returns {Error} instance detailing the error condition
- */
-function createInvalidArgumentValueError(message, argument, value, reason) {
- var err = new TypeError(message);
- err.code = 'ERR_MOCHA_INVALID_ARG_VALUE';
- err.argument = argument;
- err.value = value;
- err.reason = typeof reason !== 'undefined' ? reason : 'is invalid';
- return err;
-}
-
-/**
- * Creates an error object to be thrown when an exception was caught, but the `Error` is falsy or undefined.
- *
- * @public
- * @param {string} message - Error message to be displayed.
- * @returns {Error} instance detailing the error condition
- */
-function createInvalidExceptionError(message, value) {
- var err = new Error(message);
- err.code = 'ERR_MOCHA_INVALID_EXCEPTION';
- err.valueType = typeof value;
- err.value = value;
- return err;
-}
-
-module.exports = {
- createInvalidArgumentTypeError: createInvalidArgumentTypeError,
- createInvalidArgumentValueError: createInvalidArgumentValueError,
- createInvalidExceptionError: createInvalidExceptionError,
- createInvalidInterfaceError: createInvalidInterfaceError,
- createInvalidReporterError: createInvalidReporterError,
- createMissingArgumentError: createMissingArgumentError,
- createNoFilesMatchPatternError: createNoFilesMatchPatternError,
- createUnsupportedError: createUnsupportedError
-};
-
-},{}],7:[function(require,module,exports){
-'use strict';
-
-var Runnable = require('./runnable');
-var inherits = require('./utils').inherits;
-
-/**
- * Expose `Hook`.
- */
-
-module.exports = Hook;
-
-/**
- * Initialize a new `Hook` with the given `title` and callback `fn`
- *
- * @class
- * @extends Runnable
- * @param {String} title
- * @param {Function} fn
- */
-function Hook(title, fn) {
- Runnable.call(this, title, fn);
- this.type = 'hook';
-}
-
-/**
- * Inherit from `Runnable.prototype`.
- */
-inherits(Hook, Runnable);
-
-/**
- * Get or set the test `err`.
- *
- * @memberof Hook
- * @public
- * @param {Error} err
- * @return {Error}
- */
-Hook.prototype.error = function(err) {
- if (!arguments.length) {
- err = this._error;
- this._error = null;
- return err;
- }
-
- this._error = err;
-};
-
-},{"./runnable":33,"./utils":38}],8:[function(require,module,exports){
-'use strict';
-
-var Test = require('../test');
-var EVENT_FILE_PRE_REQUIRE = require('../suite').constants
- .EVENT_FILE_PRE_REQUIRE;
-
-/**
- * BDD-style interface:
- *
- * describe('Array', function() {
- * describe('#indexOf()', function() {
- * it('should return -1 when not present', function() {
- * // ...
- * });
- *
- * it('should return the index when present', function() {
- * // ...
- * });
- * });
- * });
- *
- * @param {Suite} suite Root suite.
- */
-module.exports = function bddInterface(suite) {
- var suites = [suite];
-
- suite.on(EVENT_FILE_PRE_REQUIRE, function(context, file, mocha) {
- var common = require('./common')(suites, context, mocha);
-
- context.before = common.before;
- context.after = common.after;
- context.beforeEach = common.beforeEach;
- context.afterEach = common.afterEach;
- context.run = mocha.options.delay && common.runWithSuite(suite);
- /**
- * Describe a "suite" with the given `title`
- * and callback `fn` containing nested suites
- * and/or tests.
- */
-
- context.describe = context.context = function(title, fn) {
- return common.suite.create({
- title: title,
- file: file,
- fn: fn
- });
- };
-
- /**
- * Pending describe.
- */
-
- context.xdescribe = context.xcontext = context.describe.skip = function(
- title,
- fn
- ) {
- return common.suite.skip({
- title: title,
- file: file,
- fn: fn
- });
- };
-
- /**
- * Exclusive suite.
- */
-
- context.describe.only = function(title, fn) {
- return common.suite.only({
- title: title,
- file: file,
- fn: fn
- });
- };
-
- /**
- * Describe a specification or test-case
- * with the given `title` and callback `fn`
- * acting as a thunk.
- */
-
- context.it = context.specify = function(title, fn) {
- var suite = suites[0];
- if (suite.isPending()) {
- fn = null;
- }
- var test = new Test(title, fn);
- test.file = file;
- suite.addTest(test);
- return test;
- };
-
- /**
- * Exclusive test-case.
- */
-
- context.it.only = function(title, fn) {
- return common.test.only(mocha, context.it(title, fn));
- };
-
- /**
- * Pending test case.
- */
-
- context.xit = context.xspecify = context.it.skip = function(title) {
- return context.it(title);
- };
-
- /**
- * Number of attempts to retry.
- */
- context.it.retries = function(n) {
- context.retries(n);
- };
- });
-};
-
-module.exports.description = 'BDD or RSpec style [default]';
-
-},{"../suite":36,"../test":37,"./common":9}],9:[function(require,module,exports){
-'use strict';
-
-var Suite = require('../suite');
-var errors = require('../errors');
-var createMissingArgumentError = errors.createMissingArgumentError;
-
-/**
- * Functions common to more than one interface.
- *
- * @param {Suite[]} suites
- * @param {Context} context
- * @param {Mocha} mocha
- * @return {Object} An object containing common functions.
- */
-module.exports = function(suites, context, mocha) {
- /**
- * Check if the suite should be tested.
- *
- * @private
- * @param {Suite} suite - suite to check
- * @returns {boolean}
- */
- function shouldBeTested(suite) {
- return (
- !mocha.options.grep ||
- (mocha.options.grep &&
- mocha.options.grep.test(suite.fullTitle()) &&
- !mocha.options.invert)
- );
- }
-
- return {
- /**
- * This is only present if flag --delay is passed into Mocha. It triggers
- * root suite execution.
- *
- * @param {Suite} suite The root suite.
- * @return {Function} A function which runs the root suite
- */
- runWithSuite: function runWithSuite(suite) {
- return function run() {
- suite.run();
- };
- },
-
- /**
- * Execute before running tests.
- *
- * @param {string} name
- * @param {Function} fn
- */
- before: function(name, fn) {
- suites[0].beforeAll(name, fn);
- },
-
- /**
- * Execute after running tests.
- *
- * @param {string} name
- * @param {Function} fn
- */
- after: function(name, fn) {
- suites[0].afterAll(name, fn);
- },
-
- /**
- * Execute before each test case.
- *
- * @param {string} name
- * @param {Function} fn
- */
- beforeEach: function(name, fn) {
- suites[0].beforeEach(name, fn);
- },
-
- /**
- * Execute after each test case.
- *
- * @param {string} name
- * @param {Function} fn
- */
- afterEach: function(name, fn) {
- suites[0].afterEach(name, fn);
- },
-
- suite: {
- /**
- * Create an exclusive Suite; convenience function
- * See docstring for create() below.
- *
- * @param {Object} opts
- * @returns {Suite}
- */
- only: function only(opts) {
- opts.isOnly = true;
- return this.create(opts);
- },
-
- /**
- * Create a Suite, but skip it; convenience function
- * See docstring for create() below.
- *
- * @param {Object} opts
- * @returns {Suite}
- */
- skip: function skip(opts) {
- opts.pending = true;
- return this.create(opts);
- },
-
- /**
- * Creates a suite.
- *
- * @param {Object} opts Options
- * @param {string} opts.title Title of Suite
- * @param {Function} [opts.fn] Suite Function (not always applicable)
- * @param {boolean} [opts.pending] Is Suite pending?
- * @param {string} [opts.file] Filepath where this Suite resides
- * @param {boolean} [opts.isOnly] Is Suite exclusive?
- * @returns {Suite}
- */
- create: function create(opts) {
- var suite = Suite.create(suites[0], opts.title);
- suite.pending = Boolean(opts.pending);
- suite.file = opts.file;
- suites.unshift(suite);
- if (opts.isOnly) {
- if (mocha.options.forbidOnly && shouldBeTested(suite)) {
- throw new Error('`.only` forbidden');
- }
-
- suite.parent.appendOnlySuite(suite);
- }
- if (suite.pending) {
- if (mocha.options.forbidPending && shouldBeTested(suite)) {
- throw new Error('Pending test forbidden');
- }
- }
- if (typeof opts.fn === 'function') {
- opts.fn.call(suite);
- suites.shift();
- } else if (typeof opts.fn === 'undefined' && !suite.pending) {
- throw createMissingArgumentError(
- 'Suite "' +
- suite.fullTitle() +
- '" was defined but no callback was supplied. ' +
- 'Supply a callback or explicitly skip the suite.',
- 'callback',
- 'function'
- );
- } else if (!opts.fn && suite.pending) {
- suites.shift();
- }
-
- return suite;
- }
- },
-
- test: {
- /**
- * Exclusive test-case.
- *
- * @param {Object} mocha
- * @param {Function} test
- * @returns {*}
- */
- only: function(mocha, test) {
- test.parent.appendOnlyTest(test);
- return test;
- },
-
- /**
- * Pending test case.
- *
- * @param {string} title
- */
- skip: function(title) {
- context.test(title);
- },
-
- /**
- * Number of retry attempts
- *
- * @param {number} n
- */
- retries: function(n) {
- context.retries(n);
- }
- }
- };
-};
-
-},{"../errors":6,"../suite":36}],10:[function(require,module,exports){
-'use strict';
-var Suite = require('../suite');
-var Test = require('../test');
-
-/**
- * Exports-style (as Node.js module) interface:
- *
- * exports.Array = {
- * '#indexOf()': {
- * 'should return -1 when the value is not present': function() {
- *
- * },
- *
- * 'should return the correct index when the value is present': function() {
- *
- * }
- * }
- * };
- *
- * @param {Suite} suite Root suite.
- */
-module.exports = function(suite) {
- var suites = [suite];
-
- suite.on(Suite.constants.EVENT_FILE_REQUIRE, visit);
-
- function visit(obj, file) {
- var suite;
- for (var key in obj) {
- if (typeof obj[key] === 'function') {
- var fn = obj[key];
- switch (key) {
- case 'before':
- suites[0].beforeAll(fn);
- break;
- case 'after':
- suites[0].afterAll(fn);
- break;
- case 'beforeEach':
- suites[0].beforeEach(fn);
- break;
- case 'afterEach':
- suites[0].afterEach(fn);
- break;
- default:
- var test = new Test(key, fn);
- test.file = file;
- suites[0].addTest(test);
- }
- } else {
- suite = Suite.create(suites[0], key);
- suites.unshift(suite);
- visit(obj[key], file);
- suites.shift();
- }
- }
- }
-};
-
-module.exports.description = 'Node.js module ("exports") style';
-
-},{"../suite":36,"../test":37}],11:[function(require,module,exports){
-'use strict';
-
-exports.bdd = require('./bdd');
-exports.tdd = require('./tdd');
-exports.qunit = require('./qunit');
-exports.exports = require('./exports');
-
-},{"./bdd":8,"./exports":10,"./qunit":12,"./tdd":13}],12:[function(require,module,exports){
-'use strict';
-
-var Test = require('../test');
-var EVENT_FILE_PRE_REQUIRE = require('../suite').constants
- .EVENT_FILE_PRE_REQUIRE;
-
-/**
- * QUnit-style interface:
- *
- * suite('Array');
- *
- * test('#length', function() {
- * var arr = [1,2,3];
- * ok(arr.length == 3);
- * });
- *
- * test('#indexOf()', function() {
- * var arr = [1,2,3];
- * ok(arr.indexOf(1) == 0);
- * ok(arr.indexOf(2) == 1);
- * ok(arr.indexOf(3) == 2);
- * });
- *
- * suite('String');
- *
- * test('#length', function() {
- * ok('foo'.length == 3);
- * });
- *
- * @param {Suite} suite Root suite.
- */
-module.exports = function qUnitInterface(suite) {
- var suites = [suite];
-
- suite.on(EVENT_FILE_PRE_REQUIRE, function(context, file, mocha) {
- var common = require('./common')(suites, context, mocha);
-
- context.before = common.before;
- context.after = common.after;
- context.beforeEach = common.beforeEach;
- context.afterEach = common.afterEach;
- context.run = mocha.options.delay && common.runWithSuite(suite);
- /**
- * Describe a "suite" with the given `title`.
- */
-
- context.suite = function(title) {
- if (suites.length > 1) {
- suites.shift();
- }
- return common.suite.create({
- title: title,
- file: file,
- fn: false
- });
- };
-
- /**
- * Exclusive Suite.
- */
-
- context.suite.only = function(title) {
- if (suites.length > 1) {
- suites.shift();
- }
- return common.suite.only({
- title: title,
- file: file,
- fn: false
- });
- };
-
- /**
- * Describe a specification or test-case
- * with the given `title` and callback `fn`
- * acting as a thunk.
- */
-
- context.test = function(title, fn) {
- var test = new Test(title, fn);
- test.file = file;
- suites[0].addTest(test);
- return test;
- };
-
- /**
- * Exclusive test-case.
- */
-
- context.test.only = function(title, fn) {
- return common.test.only(mocha, context.test(title, fn));
- };
-
- context.test.skip = common.test.skip;
- context.test.retries = common.test.retries;
- });
-};
-
-module.exports.description = 'QUnit style';
-
-},{"../suite":36,"../test":37,"./common":9}],13:[function(require,module,exports){
-'use strict';
-
-var Test = require('../test');
-var EVENT_FILE_PRE_REQUIRE = require('../suite').constants
- .EVENT_FILE_PRE_REQUIRE;
-
-/**
- * TDD-style interface:
- *
- * suite('Array', function() {
- * suite('#indexOf()', function() {
- * suiteSetup(function() {
- *
- * });
- *
- * test('should return -1 when not present', function() {
- *
- * });
- *
- * test('should return the index when present', function() {
- *
- * });
- *
- * suiteTeardown(function() {
- *
- * });
- * });
- * });
- *
- * @param {Suite} suite Root suite.
- */
-module.exports = function(suite) {
- var suites = [suite];
-
- suite.on(EVENT_FILE_PRE_REQUIRE, function(context, file, mocha) {
- var common = require('./common')(suites, context, mocha);
-
- context.setup = common.beforeEach;
- context.teardown = common.afterEach;
- context.suiteSetup = common.before;
- context.suiteTeardown = common.after;
- context.run = mocha.options.delay && common.runWithSuite(suite);
-
- /**
- * Describe a "suite" with the given `title` and callback `fn` containing
- * nested suites and/or tests.
- */
- context.suite = function(title, fn) {
- return common.suite.create({
- title: title,
- file: file,
- fn: fn
- });
- };
-
- /**
- * Pending suite.
- */
- context.suite.skip = function(title, fn) {
- return common.suite.skip({
- title: title,
- file: file,
- fn: fn
- });
- };
-
- /**
- * Exclusive test-case.
- */
- context.suite.only = function(title, fn) {
- return common.suite.only({
- title: title,
- file: file,
- fn: fn
- });
- };
-
- /**
- * Describe a specification or test-case with the given `title` and
- * callback `fn` acting as a thunk.
- */
- context.test = function(title, fn) {
- var suite = suites[0];
- if (suite.isPending()) {
- fn = null;
- }
- var test = new Test(title, fn);
- test.file = file;
- suite.addTest(test);
- return test;
- };
-
- /**
- * Exclusive test-case.
- */
-
- context.test.only = function(title, fn) {
- return common.test.only(mocha, context.test(title, fn));
- };
-
- context.test.skip = common.test.skip;
- context.test.retries = common.test.retries;
- });
-};
-
-module.exports.description =
- 'traditional "suite"/"test" instead of BDD\'s "describe"/"it"';
-
-},{"../suite":36,"../test":37,"./common":9}],14:[function(require,module,exports){
-(function (process,global){
-'use strict';
-
-/*!
- * mocha
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-var escapeRe = require('escape-string-regexp');
-var path = require('path');
-var builtinReporters = require('./reporters');
-var growl = require('./growl');
-var utils = require('./utils');
-var mocharc = require('./mocharc.json');
-var errors = require('./errors');
-var Suite = require('./suite');
-var createStatsCollector = require('./stats-collector');
-var createInvalidReporterError = errors.createInvalidReporterError;
-var createInvalidInterfaceError = errors.createInvalidInterfaceError;
-var EVENT_FILE_PRE_REQUIRE = Suite.constants.EVENT_FILE_PRE_REQUIRE;
-var EVENT_FILE_POST_REQUIRE = Suite.constants.EVENT_FILE_POST_REQUIRE;
-var EVENT_FILE_REQUIRE = Suite.constants.EVENT_FILE_REQUIRE;
-var sQuote = utils.sQuote;
-
-exports = module.exports = Mocha;
-
-/**
- * To require local UIs and reporters when running in node.
- */
-
-if (!process.browser) {
- var cwd = process.cwd();
- module.paths.push(cwd, path.join(cwd, 'node_modules'));
-}
-
-/**
- * Expose internals.
- */
-
-/**
- * @public
- * @class utils
- * @memberof Mocha
- */
-exports.utils = utils;
-exports.interfaces = require('./interfaces');
-/**
- * @public
- * @memberof Mocha
- */
-exports.reporters = builtinReporters;
-exports.Runnable = require('./runnable');
-exports.Context = require('./context');
-/**
- *
- * @memberof Mocha
- */
-exports.Runner = require('./runner');
-exports.Suite = Suite;
-exports.Hook = require('./hook');
-exports.Test = require('./test');
-
-/**
- * Constructs a new Mocha instance with `options`.
- *
- * @public
- * @class Mocha
- * @param {Object} [options] - Settings object.
- * @param {boolean} [options.allowUncaught] - Propagate uncaught errors?
- * @param {boolean} [options.asyncOnly] - Force `done` callback or promise?
- * @param {boolean} [options.bail] - Bail after first test failure?
- * @param {boolean} [options.checkLeaks] - If true, check leaks.
- * @param {boolean} [options.delay] - Delay root suite execution?
- * @param {boolean} [options.enableTimeouts] - Enable timeouts?
- * @param {string} [options.fgrep] - Test filter given string.
- * @param {boolean} [options.forbidOnly] - Tests marked `only` fail the suite?
- * @param {boolean} [options.forbidPending] - Pending tests fail the suite?
- * @param {boolean} [options.fullStackTrace] - Full stacktrace upon failure?
- * @param {string[]} [options.global] - Variables expected in global scope.
- * @param {RegExp|string} [options.grep] - Test filter given regular expression.
- * @param {boolean} [options.growl] - Enable desktop notifications?
- * @param {boolean} [options.hideDiff] - Suppress diffs from failures?
- * @param {boolean} [options.ignoreLeaks] - Ignore global leaks?
- * @param {boolean} [options.invert] - Invert test filter matches?
- * @param {boolean} [options.noHighlighting] - Disable syntax highlighting?
- * @param {string} [options.reporter] - Reporter name.
- * @param {Object} [options.reporterOption] - Reporter settings object.
- * @param {number} [options.retries] - Number of times to retry failed tests.
- * @param {number} [options.slow] - Slow threshold value.
- * @param {number|string} [options.timeout] - Timeout threshold value.
- * @param {string} [options.ui] - Interface name.
- * @param {boolean} [options.color] - Color TTY output from reporter?
- * @param {boolean} [options.useInlineDiffs] - Use inline diffs?
- */
-function Mocha(options) {
- options = utils.assign({}, mocharc, options || {});
- this.files = [];
- this.options = options;
- // root suite
- this.suite = new exports.Suite('', new exports.Context(), true);
-
- if ('useColors' in options) {
- utils.deprecate(
- 'useColors is DEPRECATED and will be removed from a future version of Mocha. Instead, use the "color" option'
- );
- options.color = 'color' in options ? options.color : options.useColors;
- }
-
- this.grep(options.grep)
- .fgrep(options.fgrep)
- .ui(options.ui)
- .bail(options.bail)
- .reporter(options.reporter, options.reporterOptions)
- .useColors(options.color)
- .slow(options.slow)
- .useInlineDiffs(options.inlineDiffs)
- .globals(options.globals);
-
- if ('enableTimeouts' in options) {
- utils.deprecate(
- 'enableTimeouts is DEPRECATED and will be removed from a future version of Mocha. Instead, use "timeout: false" to disable timeouts.'
- );
- if (options.enableTimeouts === false) {
- this.timeout(0);
- }
- }
-
- // this guard exists because Suite#timeout does not consider `undefined` to be valid input
- if (typeof options.timeout !== 'undefined') {
- this.timeout(options.timeout === false ? 0 : options.timeout);
- }
-
- if ('retries' in options) {
- this.retries(options.retries);
- }
-
- if ('diff' in options) {
- this.hideDiff(!options.diff);
- }
-
- [
- 'allowUncaught',
- 'asyncOnly',
- 'checkLeaks',
- 'delay',
- 'forbidOnly',
- 'forbidPending',
- 'fullTrace',
- 'growl',
- 'invert'
- ].forEach(function(opt) {
- if (options[opt]) {
- this[opt]();
- }
- }, this);
-}
-
-/**
- * Enables or disables bailing on the first failure.
- *
- * @public
- * @see {@link https://mochajs.org/#-b---bail|CLI option}
- * @param {boolean} [bail=true] - Whether to bail on first error.
- * @returns {Mocha} this
- * @chainable
- */
-Mocha.prototype.bail = function(bail) {
- if (!arguments.length) {
- bail = true;
- }
- this.suite.bail(bail);
- return this;
-};
-
-/**
- * @summary
- * Adds `file` to be loaded for execution.
- *
- * @description
- * Useful for generic setup code that must be included within test suite.
- *
- * @public
- * @see {@link https://mochajs.org/#--file-file|CLI option}
- * @param {string} file - Pathname of file to be loaded.
- * @returns {Mocha} this
- * @chainable
- */
-Mocha.prototype.addFile = function(file) {
- this.files.push(file);
- return this;
-};
-
-/**
- * Sets reporter to `reporter`, defaults to "spec".
- *
- * @public
- * @see {@link https://mochajs.org/#-r---reporter-name|CLI option}
- * @see {@link https://mochajs.org/#reporters|Reporters}
- * @param {String|Function} reporter - Reporter name or constructor.
- * @param {Object} [reporterOptions] - Options used to configure the reporter.
- * @returns {Mocha} this
- * @chainable
- * @throws {Error} if requested reporter cannot be loaded
- * @example
- *
- * // Use XUnit reporter and direct its output to file
- * mocha.reporter('xunit', { output: '/path/to/testspec.xunit.xml' });
- */
-Mocha.prototype.reporter = function(reporter, reporterOptions) {
- if (typeof reporter === 'function') {
- this._reporter = reporter;
- } else {
- reporter = reporter || 'spec';
- var _reporter;
- // Try to load a built-in reporter.
- if (builtinReporters[reporter]) {
- _reporter = builtinReporters[reporter];
- }
- // Try to load reporters from process.cwd() and node_modules
- if (!_reporter) {
- try {
- _reporter = require(reporter);
- } catch (err) {
- if (
- err.code !== 'MODULE_NOT_FOUND' ||
- err.message.indexOf('Cannot find module') !== -1
- ) {
- // Try to load reporters from a path (absolute or relative)
- try {
- _reporter = require(path.resolve(process.cwd(), reporter));
- } catch (_err) {
- _err.code !== 'MODULE_NOT_FOUND' ||
- _err.message.indexOf('Cannot find module') !== -1
- ? console.warn(sQuote(reporter) + ' reporter not found')
- : console.warn(
- sQuote(reporter) +
- ' reporter blew up with error:\n' +
- err.stack
- );
- }
- } else {
- console.warn(
- sQuote(reporter) + ' reporter blew up with error:\n' + err.stack
- );
- }
- }
- }
- if (!_reporter) {
- throw createInvalidReporterError(
- 'invalid reporter ' + sQuote(reporter),
- reporter
- );
- }
- this._reporter = _reporter;
- }
- this.options.reporterOptions = reporterOptions;
- return this;
-};
-
-/**
- * Sets test UI `name`, defaults to "bdd".
- *
- * @public
- * @see {@link https://mochajs.org/#-u---ui-name|CLI option}
- * @see {@link https://mochajs.org/#interfaces|Interface DSLs}
- * @param {string|Function} [ui=bdd] - Interface name or class.
- * @returns {Mocha} this
- * @chainable
- * @throws {Error} if requested interface cannot be loaded
- */
-Mocha.prototype.ui = function(ui) {
- var bindInterface;
- if (typeof ui === 'function') {
- bindInterface = ui;
- } else {
- ui = ui || 'bdd';
- bindInterface = exports.interfaces[ui];
- if (!bindInterface) {
- try {
- bindInterface = require(ui);
- } catch (err) {
- throw createInvalidInterfaceError(
- 'invalid interface ' + sQuote(ui),
- ui
- );
- }
- }
- }
- bindInterface(this.suite);
-
- this.suite.on(EVENT_FILE_PRE_REQUIRE, function(context) {
- exports.afterEach = context.afterEach || context.teardown;
- exports.after = context.after || context.suiteTeardown;
- exports.beforeEach = context.beforeEach || context.setup;
- exports.before = context.before || context.suiteSetup;
- exports.describe = context.describe || context.suite;
- exports.it = context.it || context.test;
- exports.xit = context.xit || (context.test && context.test.skip);
- exports.setup = context.setup || context.beforeEach;
- exports.suiteSetup = context.suiteSetup || context.before;
- exports.suiteTeardown = context.suiteTeardown || context.after;
- exports.suite = context.suite || context.describe;
- exports.teardown = context.teardown || context.afterEach;
- exports.test = context.test || context.it;
- exports.run = context.run;
- });
-
- return this;
-};
-
-/**
- * Loads `files` prior to execution.
- *
- * @description
- * The implementation relies on Node's `require` to execute
- * the test interface functions and will be subject to its cache.
- *
- * @private
- * @see {@link Mocha#addFile}
- * @see {@link Mocha#run}
- * @see {@link Mocha#unloadFiles}
- * @param {Function} [fn] - Callback invoked upon completion.
- */
-Mocha.prototype.loadFiles = function(fn) {
- var self = this;
- var suite = this.suite;
- this.files.forEach(function(file) {
- file = path.resolve(file);
- suite.emit(EVENT_FILE_PRE_REQUIRE, global, file, self);
- suite.emit(EVENT_FILE_REQUIRE, require(file), file, self);
- suite.emit(EVENT_FILE_POST_REQUIRE, global, file, self);
- });
- fn && fn();
-};
-
-/**
- * Removes a previously loaded file from Node's `require` cache.
- *
- * @private
- * @static
- * @see {@link Mocha#unloadFiles}
- * @param {string} file - Pathname of file to be unloaded.
- */
-Mocha.unloadFile = function(file) {
- delete require.cache[require.resolve(file)];
-};
-
-/**
- * Unloads `files` from Node's `require` cache.
- *
- * @description
- * This allows files to be "freshly" reloaded, providing the ability
- * to reuse a Mocha instance programmatically.
- *
- * Intended for consumers — not used internally
- *
- * @public
- * @see {@link Mocha.unloadFile}
- * @see {@link Mocha#loadFiles}
- * @see {@link Mocha#run}
- * @returns {Mocha} this
- * @chainable
- */
-Mocha.prototype.unloadFiles = function() {
- this.files.forEach(Mocha.unloadFile);
- return this;
-};
-
-/**
- * Sets `grep` filter after escaping RegExp special characters.
- *
- * @public
- * @see {@link Mocha#grep}
- * @param {string} str - Value to be converted to a regexp.
- * @returns {Mocha} this
- * @chainable
- * @example
- *
- * // Select tests whose full title begins with `"foo"` followed by a period
- * mocha.fgrep('foo.');
- */
-Mocha.prototype.fgrep = function(str) {
- if (!str) {
- return this;
- }
- return this.grep(new RegExp(escapeRe(str)));
-};
-
-/**
- * @summary
- * Sets `grep` filter used to select specific tests for execution.
- *
- * @description
- * If `re` is a regexp-like string, it will be converted to regexp.
- * The regexp is tested against the full title of each test (i.e., the
- * name of the test preceded by titles of each its ancestral suites).
- * As such, using an exact-match fixed pattern against the
- * test name itself will not yield any matches.
- *
- * Previous filter value will be overwritten on each call!
- *
- * @public
- * @see {@link https://mochajs.org/#-g---grep-pattern|CLI option}
- * @see {@link Mocha#fgrep}
- * @see {@link Mocha#invert}
- * @param {RegExp|String} re - Regular expression used to select tests.
- * @return {Mocha} this
- * @chainable
- * @example
- *
- * // Select tests whose full title contains `"match"`, ignoring case
- * mocha.grep(/match/i);
- * @example
- *
- * // Same as above but with regexp-like string argument
- * mocha.grep('/match/i');
- * @example
- *
- * // ## Anti-example
- * // Given embedded test `it('only-this-test')`...
- * mocha.grep('/^only-this-test$/'); // NO! Use `.only()` to do this!
- */
-Mocha.prototype.grep = function(re) {
- if (utils.isString(re)) {
- // extract args if it's regex-like, i.e: [string, pattern, flag]
- var arg = re.match(/^\/(.*)\/(g|i|)$|.*/);
- this.options.grep = new RegExp(arg[1] || arg[0], arg[2]);
- } else {
- this.options.grep = re;
- }
- return this;
-};
-
-/**
- * Inverts `grep` matches.
- *
- * @public
- * @see {@link Mocha#grep}
- * @return {Mocha} this
- * @chainable
- * @example
- *
- * // Select tests whose full title does *not* contain `"match"`, ignoring case
- * mocha.grep(/match/i).invert();
- */
-Mocha.prototype.invert = function() {
- this.options.invert = true;
- return this;
-};
-
-/**
- * Enables or disables ignoring global leaks.
- *
- * @public
- * @see {@link Mocha#checkLeaks}
- * @param {boolean} ignoreLeaks - Whether to ignore global leaks.
- * @return {Mocha} this
- * @chainable
- * @example
- *
- * // Ignore global leaks
- * mocha.ignoreLeaks(true);
- */
-Mocha.prototype.ignoreLeaks = function(ignoreLeaks) {
- this.options.ignoreLeaks = Boolean(ignoreLeaks);
- return this;
-};
-
-/**
- * Enables checking for global variables leaked while running tests.
- *
- * @public
- * @see {@link https://mochajs.org/#--check-leaks|CLI option}
- * @see {@link Mocha#ignoreLeaks}
- * @return {Mocha} this
- * @chainable
- */
-Mocha.prototype.checkLeaks = function() {
- this.options.ignoreLeaks = false;
- return this;
-};
-
-/**
- * Displays full stack trace upon test failure.
- *
- * @public
- * @return {Mocha} this
- * @chainable
- */
-Mocha.prototype.fullTrace = function() {
- this.options.fullStackTrace = true;
- return this;
-};
-
-/**
- * Enables desktop notification support if prerequisite software installed.
- *
- * @public
- * @see {@link Mocha#isGrowlCapable}
- * @see {@link Mocha#_growl}
- * @return {Mocha} this
- * @chainable
- */
-Mocha.prototype.growl = function() {
- this.options.growl = this.isGrowlCapable();
- if (!this.options.growl) {
- var detail = process.browser
- ? 'notification support not available in this browser...'
- : 'notification support prerequisites not installed...';
- console.error(detail + ' cannot enable!');
- }
- return this;
-};
-
-/**
- * @summary
- * Determines if Growl support seems likely.
- *
- * @description
- * Not available when run in browser.
- *
- * @private
- * @see {@link Growl#isCapable}
- * @see {@link Mocha#growl}
- * @return {boolean} whether Growl support can be expected
- */
-Mocha.prototype.isGrowlCapable = growl.isCapable;
-
-/**
- * Implements desktop notifications using a pseudo-reporter.
- *
- * @private
- * @see {@link Mocha#growl}
- * @see {@link Growl#notify}
- * @param {Runner} runner - Runner instance.
- */
-Mocha.prototype._growl = growl.notify;
-
-/**
- * Specifies whitelist of variable names to be expected in global scope.
- *
- * @public
- * @see {@link https://mochajs.org/#--globals-names|CLI option}
- * @see {@link Mocha#checkLeaks}
- * @param {String[]|String} globals - Accepted global variable name(s).
- * @return {Mocha} this
- * @chainable
- * @example
- *
- * // Specify variables to be expected in global scope
- * mocha.globals(['jQuery', 'MyLib']);
- */
-Mocha.prototype.globals = function(globals) {
- this.options.globals = (this.options.globals || [])
- .concat(globals)
- .filter(Boolean);
- return this;
-};
-
-/**
- * Enables or disables TTY color output by screen-oriented reporters.
- *
- * @public
- * @param {boolean} colors - Whether to enable color output.
- * @return {Mocha} this
- * @chainable
- */
-Mocha.prototype.useColors = function(colors) {
- if (colors !== undefined) {
- this.options.useColors = colors;
- }
- return this;
-};
-
-/**
- * Determines if reporter should use inline diffs (rather than +/-)
- * in test failure output.
- *
- * @public
- * @param {boolean} inlineDiffs - Whether to use inline diffs.
- * @return {Mocha} this
- * @chainable
- */
-Mocha.prototype.useInlineDiffs = function(inlineDiffs) {
- this.options.useInlineDiffs = inlineDiffs !== undefined && inlineDiffs;
- return this;
-};
-
-/**
- * Determines if reporter should include diffs in test failure output.
- *
- * @public
- * @param {boolean} hideDiff - Whether to hide diffs.
- * @return {Mocha} this
- * @chainable
- */
-Mocha.prototype.hideDiff = function(hideDiff) {
- this.options.hideDiff = hideDiff !== undefined && hideDiff;
- return this;
-};
-
-/**
- * @summary
- * Sets timeout threshold value.
- *
- * @description
- * A string argument can use shorthand (such as "2s") and will be converted.
- * If the value is `0`, timeouts will be disabled.
- *
- * @public
- * @see {@link https://mochajs.org/#-t---timeout-ms|CLI option}
- * @see {@link https://mochajs.org/#--no-timeouts|CLI option}
- * @see {@link https://mochajs.org/#timeouts|Timeouts}
- * @see {@link Mocha#enableTimeouts}
- * @param {number|string} msecs - Timeout threshold value.
- * @return {Mocha} this
- * @chainable
- * @example
- *
- * // Sets timeout to one second
- * mocha.timeout(1000);
- * @example
- *
- * // Same as above but using string argument
- * mocha.timeout('1s');
- */
-Mocha.prototype.timeout = function(msecs) {
- this.suite.timeout(msecs);
- return this;
-};
-
-/**
- * Sets the number of times to retry failed tests.
- *
- * @public
- * @see {@link https://mochajs.org/#retry-tests|Retry Tests}
- * @param {number} retry - Number of times to retry failed tests.
- * @return {Mocha} this
- * @chainable
- * @example
- *
- * // Allow any failed test to retry one more time
- * mocha.retries(1);
- */
-Mocha.prototype.retries = function(n) {
- this.suite.retries(n);
- return this;
-};
-
-/**
- * Sets slowness threshold value.
- *
- * @public
- * @see {@link https://mochajs.org/#-s---slow-ms|CLI option}
- * @param {number} msecs - Slowness threshold value.
- * @return {Mocha} this
- * @chainable
- * @example
- *
- * // Sets "slow" threshold to half a second
- * mocha.slow(500);
- * @example
- *
- * // Same as above but using string argument
- * mocha.slow('0.5s');
- */
-Mocha.prototype.slow = function(msecs) {
- this.suite.slow(msecs);
- return this;
-};
-
-/**
- * Enables or disables timeouts.
- *
- * @public
- * @see {@link https://mochajs.org/#-t---timeout-ms|CLI option}
- * @see {@link https://mochajs.org/#--no-timeouts|CLI option}
- * @param {boolean} enableTimeouts - Whether to enable timeouts.
- * @return {Mocha} this
- * @chainable
- */
-Mocha.prototype.enableTimeouts = function(enableTimeouts) {
- this.suite.enableTimeouts(
- arguments.length && enableTimeouts !== undefined ? enableTimeouts : true
- );
- return this;
-};
-
-/**
- * Forces all tests to either accept a `done` callback or return a promise.
- *
- * @public
- * @return {Mocha} this
- * @chainable
- */
-Mocha.prototype.asyncOnly = function() {
- this.options.asyncOnly = true;
- return this;
-};
-
-/**
- * Disables syntax highlighting (in browser).
- *
- * @public
- * @return {Mocha} this
- * @chainable
- */
-Mocha.prototype.noHighlighting = function() {
- this.options.noHighlighting = true;
- return this;
-};
-
-/**
- * Enables uncaught errors to propagate (in browser).
- *
- * @public
- * @return {Mocha} this
- * @chainable
- */
-Mocha.prototype.allowUncaught = function() {
- this.options.allowUncaught = true;
- return this;
-};
-
-/**
- * @summary
- * Delays root suite execution.
- *
- * @description
- * Used to perform asynch operations before any suites are run.
- *
- * @public
- * @see {@link https://mochajs.org/#delayed-root-suite|delayed root suite}
- * @returns {Mocha} this
- * @chainable
- */
-Mocha.prototype.delay = function delay() {
- this.options.delay = true;
- return this;
-};
-
-/**
- * Causes tests marked `only` to fail the suite.
- *
- * @public
- * @returns {Mocha} this
- * @chainable
- */
-Mocha.prototype.forbidOnly = function() {
- this.options.forbidOnly = true;
- return this;
-};
-
-/**
- * Causes pending tests and tests marked `skip` to fail the suite.
- *
- * @public
- * @returns {Mocha} this
- * @chainable
- */
-Mocha.prototype.forbidPending = function() {
- this.options.forbidPending = true;
- return this;
-};
-
-/**
- * Mocha version as specified by "package.json".
- *
- * @name Mocha#version
- * @type string
- * @readonly
- */
-Object.defineProperty(Mocha.prototype, 'version', {
- value: require('../package.json').version,
- configurable: false,
- enumerable: true,
- writable: false
-});
-
-/**
- * Callback to be invoked when test execution is complete.
- *
- * @callback DoneCB
- * @param {number} failures - Number of failures that occurred.
- */
-
-/**
- * Runs root suite and invokes `fn()` when complete.
- *
- * @description
- * To run tests multiple times (or to run tests in files that are
- * already in the `require` cache), make sure to clear them from
- * the cache first!
- *
- * @public
- * @see {@link Mocha#loadFiles}
- * @see {@link Mocha#unloadFiles}
- * @see {@link Runner#run}
- * @param {DoneCB} [fn] - Callback invoked when test execution completed.
- * @return {Runner} runner instance
- */
-Mocha.prototype.run = function(fn) {
- if (this.files.length) {
- this.loadFiles();
- }
- var suite = this.suite;
- var options = this.options;
- options.files = this.files;
- var runner = new exports.Runner(suite, options.delay);
- createStatsCollector(runner);
- var reporter = new this._reporter(runner, options);
- runner.ignoreLeaks = options.ignoreLeaks !== false;
- runner.fullStackTrace = options.fullStackTrace;
- runner.asyncOnly = options.asyncOnly;
- runner.allowUncaught = options.allowUncaught;
- runner.forbidOnly = options.forbidOnly;
- runner.forbidPending = options.forbidPending;
- if (options.grep) {
- runner.grep(options.grep, options.invert);
- }
- if (options.globals) {
- runner.globals(options.globals);
- }
- if (options.growl) {
- this._growl(runner);
- }
- if (options.useColors !== undefined) {
- exports.reporters.Base.useColors = options.useColors;
- }
- exports.reporters.Base.inlineDiffs = options.useInlineDiffs;
- exports.reporters.Base.hideDiff = options.hideDiff;
-
- function done(failures) {
- fn = fn || utils.noop;
- if (reporter.done) {
- reporter.done(failures, fn);
- } else {
- fn(failures);
- }
- }
-
- return runner.run(done);
-};
-
-}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"../package.json":90,"./context":5,"./errors":6,"./growl":2,"./hook":7,"./interfaces":11,"./mocharc.json":15,"./reporters":21,"./runnable":33,"./runner":34,"./stats-collector":35,"./suite":36,"./test":37,"./utils":38,"_process":69,"escape-string-regexp":49,"path":42}],15:[function(require,module,exports){
-module.exports={
- "diff": true,
- "extension": ["js"],
- "opts": "./test/mocha.opts",
- "package": "./package.json",
- "reporter": "spec",
- "slow": 75,
- "timeout": 2000,
- "ui": "bdd"
-}
-
-},{}],16:[function(require,module,exports){
-'use strict';
-
-module.exports = Pending;
-
-/**
- * Initialize a new `Pending` error with the given message.
- *
- * @param {string} message
- */
-function Pending(message) {
- this.message = message;
-}
-
-},{}],17:[function(require,module,exports){
-(function (process){
-'use strict';
-/**
- * @module Base
- */
-/**
- * Module dependencies.
- */
-
-var tty = require('tty');
-var diff = require('diff');
-var milliseconds = require('ms');
-var utils = require('../utils');
-var supportsColor = process.browser ? null : require('supports-color');
-var constants = require('../runner').constants;
-var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
-var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
-
-/**
- * Expose `Base`.
- */
-
-exports = module.exports = Base;
-
-/**
- * Check if both stdio streams are associated with a tty.
- */
-
-var isatty = tty.isatty(1) && tty.isatty(2);
-
-/**
- * Enable coloring by default, except in the browser interface.
- */
-
-exports.useColors =
- !process.browser &&
- (supportsColor.stdout || process.env.MOCHA_COLORS !== undefined);
-
-/**
- * Inline diffs instead of +/-
- */
-
-exports.inlineDiffs = false;
-
-/**
- * Default color map.
- */
-
-exports.colors = {
- pass: 90,
- fail: 31,
- 'bright pass': 92,
- 'bright fail': 91,
- 'bright yellow': 93,
- pending: 36,
- suite: 0,
- 'error title': 0,
- 'error message': 31,
- 'error stack': 90,
- checkmark: 32,
- fast: 90,
- medium: 33,
- slow: 31,
- green: 32,
- light: 90,
- 'diff gutter': 90,
- 'diff added': 32,
- 'diff removed': 31
-};
-
-/**
- * Default symbol map.
- */
-
-exports.symbols = {
- ok: '✓',
- err: '✖',
- dot: '․',
- comma: ',',
- bang: '!'
-};
-
-// With node.js on Windows: use symbols available in terminal default fonts
-if (process.platform === 'win32') {
- exports.symbols.ok = '\u221A';
- exports.symbols.err = '\u00D7';
- exports.symbols.dot = '.';
-}
-
-/**
- * Color `str` with the given `type`,
- * allowing colors to be disabled,
- * as well as user-defined color
- * schemes.
- *
- * @private
- * @param {string} type
- * @param {string} str
- * @return {string}
- */
-var color = (exports.color = function(type, str) {
- if (!exports.useColors) {
- return String(str);
- }
- return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
-});
-
-/**
- * Expose term window size, with some defaults for when stderr is not a tty.
- */
-
-exports.window = {
- width: 75
-};
-
-if (isatty) {
- exports.window.width = process.stdout.getWindowSize
- ? process.stdout.getWindowSize(1)[0]
- : tty.getWindowSize()[1];
-}
-
-/**
- * Expose some basic cursor interactions that are common among reporters.
- */
-
-exports.cursor = {
- hide: function() {
- isatty && process.stdout.write('\u001b[?25l');
- },
-
- show: function() {
- isatty && process.stdout.write('\u001b[?25h');
- },
-
- deleteLine: function() {
- isatty && process.stdout.write('\u001b[2K');
- },
-
- beginningOfLine: function() {
- isatty && process.stdout.write('\u001b[0G');
- },
-
- CR: function() {
- if (isatty) {
- exports.cursor.deleteLine();
- exports.cursor.beginningOfLine();
- } else {
- process.stdout.write('\r');
- }
- }
-};
-
-function showDiff(err) {
- return (
- err &&
- err.showDiff !== false &&
- sameType(err.actual, err.expected) &&
- err.expected !== undefined
- );
-}
-
-function stringifyDiffObjs(err) {
- if (!utils.isString(err.actual) || !utils.isString(err.expected)) {
- err.actual = utils.stringify(err.actual);
- err.expected = utils.stringify(err.expected);
- }
-}
-
-/**
- * Returns a diff between 2 strings with coloured ANSI output.
- *
- * @description
- * The diff will be either inline or unified dependent on the value
- * of `Base.inlineDiff`.
- *
- * @param {string} actual
- * @param {string} expected
- * @return {string} Diff
- */
-var generateDiff = (exports.generateDiff = function(actual, expected) {
- return exports.inlineDiffs
- ? inlineDiff(actual, expected)
- : unifiedDiff(actual, expected);
-});
-
-/**
- * Outputs the given `failures` as a list.
- *
- * @public
- * @memberof Mocha.reporters.Base
- * @variation 1
- * @param {Object[]} failures - Each is Test instance with corresponding
- * Error property
- */
-exports.list = function(failures) {
- console.log();
- failures.forEach(function(test, i) {
- // format
- var fmt =
- color('error title', ' %s) %s:\n') +
- color('error message', ' %s') +
- color('error stack', '\n%s\n');
-
- // msg
- var msg;
- var err = test.err;
- var message;
- if (err.message && typeof err.message.toString === 'function') {
- message = err.message + '';
- } else if (typeof err.inspect === 'function') {
- message = err.inspect() + '';
- } else {
- message = '';
- }
- var stack = err.stack || message;
- var index = message ? stack.indexOf(message) : -1;
-
- if (index === -1) {
- msg = message;
- } else {
- index += message.length;
- msg = stack.slice(0, index);
- // remove msg from stack
- stack = stack.slice(index + 1);
- }
-
- // uncaught
- if (err.uncaught) {
- msg = 'Uncaught ' + msg;
- }
- // explicitly show diff
- if (!exports.hideDiff && showDiff(err)) {
- stringifyDiffObjs(err);
- fmt =
- color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n');
- var match = message.match(/^([^:]+): expected/);
- msg = '\n ' + color('error message', match ? match[1] : msg);
-
- msg += generateDiff(err.actual, err.expected);
- }
-
- // indent stack trace
- stack = stack.replace(/^/gm, ' ');
-
- // indented test title
- var testTitle = '';
- test.titlePath().forEach(function(str, index) {
- if (index !== 0) {
- testTitle += '\n ';
- }
- for (var i = 0; i < index; i++) {
- testTitle += ' ';
- }
- testTitle += str;
- });
-
- console.log(fmt, i + 1, testTitle, msg, stack);
- });
-};
-
-/**
- * Constructs a new `Base` reporter instance.
- *
- * @description
- * All other reporters generally inherit from this reporter.
- *
- * @public
- * @class
- * @memberof Mocha.reporters
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function Base(runner, options) {
- var failures = (this.failures = []);
-
- if (!runner) {
- throw new TypeError('Missing runner argument');
- }
- this.options = options || {};
- this.runner = runner;
- this.stats = runner.stats; // assigned so Reporters keep a closer reference
-
- runner.on(EVENT_TEST_PASS, function(test) {
- if (test.duration > test.slow()) {
- test.speed = 'slow';
- } else if (test.duration > test.slow() / 2) {
- test.speed = 'medium';
- } else {
- test.speed = 'fast';
- }
- });
-
- runner.on(EVENT_TEST_FAIL, function(test, err) {
- if (showDiff(err)) {
- stringifyDiffObjs(err);
- }
- test.err = err;
- failures.push(test);
- });
-}
-
-/**
- * Outputs common epilogue used by many of the bundled reporters.
- *
- * @public
- * @memberof Mocha.reporters.Base
- */
-Base.prototype.epilogue = function() {
- var stats = this.stats;
- var fmt;
-
- console.log();
-
- // passes
- fmt =
- color('bright pass', ' ') +
- color('green', ' %d passing') +
- color('light', ' (%s)');
-
- console.log(fmt, stats.passes || 0, milliseconds(stats.duration));
-
- // pending
- if (stats.pending) {
- fmt = color('pending', ' ') + color('pending', ' %d pending');
-
- console.log(fmt, stats.pending);
- }
-
- // failures
- if (stats.failures) {
- fmt = color('fail', ' %d failing');
-
- console.log(fmt, stats.failures);
-
- Base.list(this.failures);
- console.log();
- }
-
- console.log();
-};
-
-/**
- * Pads the given `str` to `len`.
- *
- * @private
- * @param {string} str
- * @param {string} len
- * @return {string}
- */
-function pad(str, len) {
- str = String(str);
- return Array(len - str.length + 1).join(' ') + str;
-}
-
-/**
- * Returns inline diff between 2 strings with coloured ANSI output.
- *
- * @private
- * @param {String} actual
- * @param {String} expected
- * @return {string} Diff
- */
-function inlineDiff(actual, expected) {
- var msg = errorDiff(actual, expected);
-
- // linenos
- var lines = msg.split('\n');
- if (lines.length > 4) {
- var width = String(lines.length).length;
- msg = lines
- .map(function(str, i) {
- return pad(++i, width) + ' |' + ' ' + str;
- })
- .join('\n');
- }
-
- // legend
- msg =
- '\n' +
- color('diff removed', 'actual') +
- ' ' +
- color('diff added', 'expected') +
- '\n\n' +
- msg +
- '\n';
-
- // indent
- msg = msg.replace(/^/gm, ' ');
- return msg;
-}
-
-/**
- * Returns unified diff between two strings with coloured ANSI output.
- *
- * @private
- * @param {String} actual
- * @param {String} expected
- * @return {string} The diff.
- */
-function unifiedDiff(actual, expected) {
- var indent = ' ';
- function cleanUp(line) {
- if (line[0] === '+') {
- return indent + colorLines('diff added', line);
- }
- if (line[0] === '-') {
- return indent + colorLines('diff removed', line);
- }
- if (line.match(/@@/)) {
- return '--';
- }
- if (line.match(/\\ No newline/)) {
- return null;
- }
- return indent + line;
- }
- function notBlank(line) {
- return typeof line !== 'undefined' && line !== null;
- }
- var msg = diff.createPatch('string', actual, expected);
- var lines = msg.split('\n').splice(5);
- return (
- '\n ' +
- colorLines('diff added', '+ expected') +
- ' ' +
- colorLines('diff removed', '- actual') +
- '\n\n' +
- lines
- .map(cleanUp)
- .filter(notBlank)
- .join('\n')
- );
-}
-
-/**
- * Returns character diff for `err`.
- *
- * @private
- * @param {String} actual
- * @param {String} expected
- * @return {string} the diff
- */
-function errorDiff(actual, expected) {
- return diff
- .diffWordsWithSpace(actual, expected)
- .map(function(str) {
- if (str.added) {
- return colorLines('diff added', str.value);
- }
- if (str.removed) {
- return colorLines('diff removed', str.value);
- }
- return str.value;
- })
- .join('');
-}
-
-/**
- * Colors lines for `str`, using the color `name`.
- *
- * @private
- * @param {string} name
- * @param {string} str
- * @return {string}
- */
-function colorLines(name, str) {
- return str
- .split('\n')
- .map(function(str) {
- return color(name, str);
- })
- .join('\n');
-}
-
-/**
- * Object#toString reference.
- */
-var objToString = Object.prototype.toString;
-
-/**
- * Checks that a / b have the same type.
- *
- * @private
- * @param {Object} a
- * @param {Object} b
- * @return {boolean}
- */
-function sameType(a, b) {
- return objToString.call(a) === objToString.call(b);
-}
-
-Base.abstract = true;
-
-}).call(this,require('_process'))
-},{"../runner":34,"../utils":38,"_process":69,"diff":48,"ms":60,"supports-color":42,"tty":4}],18:[function(require,module,exports){
-'use strict';
-/**
- * @module Doc
- */
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-var utils = require('../utils');
-var constants = require('../runner').constants;
-var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
-var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
-var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
-var EVENT_SUITE_END = constants.EVENT_SUITE_END;
-
-/**
- * Expose `Doc`.
- */
-
-exports = module.exports = Doc;
-
-/**
- * Constructs a new `Doc` reporter instance.
- *
- * @public
- * @class
- * @memberof Mocha.reporters
- * @extends Mocha.reporters.Base
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function Doc(runner, options) {
- Base.call(this, runner, options);
-
- var indents = 2;
-
- function indent() {
- return Array(indents).join(' ');
- }
-
- runner.on(EVENT_SUITE_BEGIN, function(suite) {
- if (suite.root) {
- return;
- }
- ++indents;
- console.log('%s', indent());
- ++indents;
- console.log('%s%s ', indent(), utils.escape(suite.title));
- console.log('%s', indent());
- });
-
- runner.on(EVENT_SUITE_END, function(suite) {
- if (suite.root) {
- return;
- }
- console.log('%s ', indent());
- --indents;
- console.log('%s ', indent());
- --indents;
- });
-
- runner.on(EVENT_TEST_PASS, function(test) {
- console.log('%s %s ', indent(), utils.escape(test.title));
- var code = utils.escape(utils.clean(test.body));
- console.log('%s %s
', indent(), code);
- });
-
- runner.on(EVENT_TEST_FAIL, function(test, err) {
- console.log(
- '%s %s ',
- indent(),
- utils.escape(test.title)
- );
- var code = utils.escape(utils.clean(test.body));
- console.log(
- '%s %s
',
- indent(),
- code
- );
- console.log('%s %s ', indent(), utils.escape(err));
- });
-}
-
-Doc.description = 'HTML documentation';
-
-},{"../runner":34,"../utils":38,"./base":17}],19:[function(require,module,exports){
-(function (process){
-'use strict';
-/**
- * @module Dot
- */
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-var inherits = require('../utils').inherits;
-var constants = require('../runner').constants;
-var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
-var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
-var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
-var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
-var EVENT_RUN_END = constants.EVENT_RUN_END;
-
-/**
- * Expose `Dot`.
- */
-
-exports = module.exports = Dot;
-
-/**
- * Constructs a new `Dot` reporter instance.
- *
- * @public
- * @class
- * @memberof Mocha.reporters
- * @extends Mocha.reporters.Base
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function Dot(runner, options) {
- Base.call(this, runner, options);
-
- var self = this;
- var width = (Base.window.width * 0.75) | 0;
- var n = -1;
-
- runner.on(EVENT_RUN_BEGIN, function() {
- process.stdout.write('\n');
- });
-
- runner.on(EVENT_TEST_PENDING, function() {
- if (++n % width === 0) {
- process.stdout.write('\n ');
- }
- process.stdout.write(Base.color('pending', Base.symbols.comma));
- });
-
- runner.on(EVENT_TEST_PASS, function(test) {
- if (++n % width === 0) {
- process.stdout.write('\n ');
- }
- if (test.speed === 'slow') {
- process.stdout.write(Base.color('bright yellow', Base.symbols.dot));
- } else {
- process.stdout.write(Base.color(test.speed, Base.symbols.dot));
- }
- });
-
- runner.on(EVENT_TEST_FAIL, function() {
- if (++n % width === 0) {
- process.stdout.write('\n ');
- }
- process.stdout.write(Base.color('fail', Base.symbols.bang));
- });
-
- runner.once(EVENT_RUN_END, function() {
- console.log();
- self.epilogue();
- });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-inherits(Dot, Base);
-
-Dot.description = 'dot matrix representation';
-
-}).call(this,require('_process'))
-},{"../runner":34,"../utils":38,"./base":17,"_process":69}],20:[function(require,module,exports){
-(function (global){
-'use strict';
-
-/* eslint-env browser */
-/**
- * @module HTML
- */
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-var utils = require('../utils');
-var Progress = require('../browser/progress');
-var escapeRe = require('escape-string-regexp');
-var constants = require('../runner').constants;
-var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
-var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
-var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
-var EVENT_SUITE_END = constants.EVENT_SUITE_END;
-var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
-var escape = utils.escape;
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date;
-
-/**
- * Expose `HTML`.
- */
-
-exports = module.exports = HTML;
-
-/**
- * Stats template.
- */
-
-var statsTemplate =
- '';
-
-var playIcon = '‣';
-
-/**
- * Constructs a new `HTML` reporter instance.
- *
- * @public
- * @class
- * @memberof Mocha.reporters
- * @extends Mocha.reporters.Base
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function HTML(runner, options) {
- Base.call(this, runner, options);
-
- var self = this;
- var stats = this.stats;
- var stat = fragment(statsTemplate);
- var items = stat.getElementsByTagName('li');
- var passes = items[1].getElementsByTagName('em')[0];
- var passesLink = items[1].getElementsByTagName('a')[0];
- var failures = items[2].getElementsByTagName('em')[0];
- var failuresLink = items[2].getElementsByTagName('a')[0];
- var duration = items[3].getElementsByTagName('em')[0];
- var canvas = stat.getElementsByTagName('canvas')[0];
- var report = fragment('');
- var stack = [report];
- var progress;
- var ctx;
- var root = document.getElementById('mocha');
-
- if (canvas.getContext) {
- var ratio = window.devicePixelRatio || 1;
- canvas.style.width = canvas.width;
- canvas.style.height = canvas.height;
- canvas.width *= ratio;
- canvas.height *= ratio;
- ctx = canvas.getContext('2d');
- ctx.scale(ratio, ratio);
- progress = new Progress();
- }
-
- if (!root) {
- return error('#mocha div missing, add it to your document');
- }
-
- // pass toggle
- on(passesLink, 'click', function(evt) {
- evt.preventDefault();
- unhide();
- var name = /pass/.test(report.className) ? '' : ' pass';
- report.className = report.className.replace(/fail|pass/g, '') + name;
- if (report.className.trim()) {
- hideSuitesWithout('test pass');
- }
- });
-
- // failure toggle
- on(failuresLink, 'click', function(evt) {
- evt.preventDefault();
- unhide();
- var name = /fail/.test(report.className) ? '' : ' fail';
- report.className = report.className.replace(/fail|pass/g, '') + name;
- if (report.className.trim()) {
- hideSuitesWithout('test fail');
- }
- });
-
- root.appendChild(stat);
- root.appendChild(report);
-
- if (progress) {
- progress.size(40);
- }
-
- runner.on(EVENT_SUITE_BEGIN, function(suite) {
- if (suite.root) {
- return;
- }
-
- // suite
- var url = self.suiteURL(suite);
- var el = fragment(
- ' ',
- url,
- escape(suite.title)
- );
-
- // container
- stack[0].appendChild(el);
- stack.unshift(document.createElement('ul'));
- el.appendChild(stack[0]);
- });
-
- runner.on(EVENT_SUITE_END, function(suite) {
- if (suite.root) {
- updateStats();
- return;
- }
- stack.shift();
- });
-
- runner.on(EVENT_TEST_PASS, function(test) {
- var url = self.testURL(test);
- var markup =
- ' ';
- var el = fragment(markup, test.speed, test.title, test.duration, url);
- self.addCodeToggle(el, test.body);
- appendToStack(el);
- updateStats();
- });
-
- runner.on(EVENT_TEST_FAIL, function(test) {
- var el = fragment(
- ' ',
- test.title,
- self.testURL(test)
- );
- var stackString; // Note: Includes leading newline
- var message = test.err.toString();
-
- // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
- // check for the result of the stringifying.
- if (message === '[object Error]') {
- message = test.err.message;
- }
-
- if (test.err.stack) {
- var indexOfMessage = test.err.stack.indexOf(test.err.message);
- if (indexOfMessage === -1) {
- stackString = test.err.stack;
- } else {
- stackString = test.err.stack.substr(
- test.err.message.length + indexOfMessage
- );
- }
- } else if (test.err.sourceURL && test.err.line !== undefined) {
- // Safari doesn't give you a stack. Let's at least provide a source line.
- stackString = '\n(' + test.err.sourceURL + ':' + test.err.line + ')';
- }
-
- stackString = stackString || '';
-
- if (test.err.htmlMessage && stackString) {
- el.appendChild(
- fragment(
- '',
- test.err.htmlMessage,
- stackString
- )
- );
- } else if (test.err.htmlMessage) {
- el.appendChild(
- fragment('%s
', test.err.htmlMessage)
- );
- } else {
- el.appendChild(
- fragment('%e%e ', message, stackString)
- );
- }
-
- self.addCodeToggle(el, test.body);
- appendToStack(el);
- updateStats();
- });
-
- runner.on(EVENT_TEST_PENDING, function(test) {
- var el = fragment(
- '%e ',
- test.title
- );
- appendToStack(el);
- updateStats();
- });
-
- function appendToStack(el) {
- // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
- if (stack[0]) {
- stack[0].appendChild(el);
- }
- }
-
- function updateStats() {
- // TODO: add to stats
- var percent = ((stats.tests / runner.total) * 100) | 0;
- if (progress) {
- progress.update(percent).draw(ctx);
- }
-
- // update stats
- var ms = new Date() - stats.start;
- text(passes, stats.passes);
- text(failures, stats.failures);
- text(duration, (ms / 1000).toFixed(2));
- }
-}
-
-/**
- * Makes a URL, preserving querystring ("search") parameters.
- *
- * @param {string} s
- * @return {string} A new URL.
- */
-function makeUrl(s) {
- var search = window.location.search;
-
- // Remove previous grep query parameter if present
- if (search) {
- search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?');
- }
-
- return (
- window.location.pathname +
- (search ? search + '&' : '?') +
- 'grep=' +
- encodeURIComponent(escapeRe(s))
- );
-}
-
-/**
- * Provide suite URL.
- *
- * @param {Object} [suite]
- */
-HTML.prototype.suiteURL = function(suite) {
- return makeUrl(suite.fullTitle());
-};
-
-/**
- * Provide test URL.
- *
- * @param {Object} [test]
- */
-HTML.prototype.testURL = function(test) {
- return makeUrl(test.fullTitle());
-};
-
-/**
- * Adds code toggle functionality for the provided test's list element.
- *
- * @param {HTMLLIElement} el
- * @param {string} contents
- */
-HTML.prototype.addCodeToggle = function(el, contents) {
- var h2 = el.getElementsByTagName('h2')[0];
-
- on(h2, 'click', function() {
- pre.style.display = pre.style.display === 'none' ? 'block' : 'none';
- });
-
- var pre = fragment('%e
', utils.clean(contents));
- el.appendChild(pre);
- pre.style.display = 'none';
-};
-
-/**
- * Display error `msg`.
- *
- * @param {string} msg
- */
-function error(msg) {
- document.body.appendChild(fragment('%s
', msg));
-}
-
-/**
- * Return a DOM fragment from `html`.
- *
- * @param {string} html
- */
-function fragment(html) {
- var args = arguments;
- var div = document.createElement('div');
- var i = 1;
-
- div.innerHTML = html.replace(/%([se])/g, function(_, type) {
- switch (type) {
- case 's':
- return String(args[i++]);
- case 'e':
- return escape(args[i++]);
- // no default
- }
- });
-
- return div.firstChild;
-}
-
-/**
- * Check for suites that do not have elements
- * with `classname`, and hide them.
- *
- * @param {text} classname
- */
-function hideSuitesWithout(classname) {
- var suites = document.getElementsByClassName('suite');
- for (var i = 0; i < suites.length; i++) {
- var els = suites[i].getElementsByClassName(classname);
- if (!els.length) {
- suites[i].className += ' hidden';
- }
- }
-}
-
-/**
- * Unhide .hidden suites.
- */
-function unhide() {
- var els = document.getElementsByClassName('suite hidden');
- for (var i = 0; i < els.length; ++i) {
- els[i].className = els[i].className.replace('suite hidden', 'suite');
- }
-}
-
-/**
- * Set an element's text contents.
- *
- * @param {HTMLElement} el
- * @param {string} contents
- */
-function text(el, contents) {
- if (el.textContent) {
- el.textContent = contents;
- } else {
- el.innerText = contents;
- }
-}
-
-/**
- * Listen on `event` with callback `fn`.
- */
-function on(el, event, fn) {
- if (el.addEventListener) {
- el.addEventListener(event, fn, false);
- } else {
- el.attachEvent('on' + event, fn);
- }
-}
-
-HTML.browserOnly = true;
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"../browser/progress":3,"../runner":34,"../utils":38,"./base":17,"escape-string-regexp":49}],21:[function(require,module,exports){
-'use strict';
-
-// Alias exports to a their normalized format Mocha#reporter to prevent a need
-// for dynamic (try/catch) requires, which Browserify doesn't handle.
-exports.Base = exports.base = require('./base');
-exports.Dot = exports.dot = require('./dot');
-exports.Doc = exports.doc = require('./doc');
-exports.TAP = exports.tap = require('./tap');
-exports.JSON = exports.json = require('./json');
-exports.HTML = exports.html = require('./html');
-exports.List = exports.list = require('./list');
-exports.Min = exports.min = require('./min');
-exports.Spec = exports.spec = require('./spec');
-exports.Nyan = exports.nyan = require('./nyan');
-exports.XUnit = exports.xunit = require('./xunit');
-exports.Markdown = exports.markdown = require('./markdown');
-exports.Progress = exports.progress = require('./progress');
-exports.Landing = exports.landing = require('./landing');
-exports.JSONStream = exports['json-stream'] = require('./json-stream');
-
-},{"./base":17,"./doc":18,"./dot":19,"./html":20,"./json":23,"./json-stream":22,"./landing":24,"./list":25,"./markdown":26,"./min":27,"./nyan":28,"./progress":29,"./spec":30,"./tap":31,"./xunit":32}],22:[function(require,module,exports){
-(function (process){
-'use strict';
-/**
- * @module JSONStream
- */
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-var constants = require('../runner').constants;
-var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
-var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
-var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
-var EVENT_RUN_END = constants.EVENT_RUN_END;
-
-/**
- * Expose `JSONStream`.
- */
-
-exports = module.exports = JSONStream;
-
-/**
- * Constructs a new `JSONStream` reporter instance.
- *
- * @public
- * @class
- * @memberof Mocha.reporters
- * @extends Mocha.reporters.Base
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function JSONStream(runner, options) {
- Base.call(this, runner, options);
-
- var self = this;
- var total = runner.total;
-
- runner.once(EVENT_RUN_BEGIN, function() {
- writeEvent(['start', {total: total}]);
- });
-
- runner.on(EVENT_TEST_PASS, function(test) {
- writeEvent(['pass', clean(test)]);
- });
-
- runner.on(EVENT_TEST_FAIL, function(test, err) {
- test = clean(test);
- test.err = err.message;
- test.stack = err.stack || null;
- writeEvent(['fail', test]);
- });
-
- runner.once(EVENT_RUN_END, function() {
- writeEvent(['end', self.stats]);
- });
-}
-
-/**
- * Mocha event to be written to the output stream.
- * @typedef {Array} JSONStream~MochaEvent
- */
-
-/**
- * Writes Mocha event to reporter output stream.
- *
- * @private
- * @param {JSONStream~MochaEvent} event - Mocha event to be output.
- */
-function writeEvent(event) {
- process.stdout.write(JSON.stringify(event) + '\n');
-}
-
-/**
- * Returns an object literal representation of `test`
- * free of cyclic properties, etc.
- *
- * @private
- * @param {Test} test - Instance used as data source.
- * @return {Object} object containing pared-down test instance data
- */
-function clean(test) {
- return {
- title: test.title,
- fullTitle: test.fullTitle(),
- duration: test.duration,
- currentRetry: test.currentRetry()
- };
-}
-
-JSONStream.description = 'newline delimited JSON events';
-
-}).call(this,require('_process'))
-},{"../runner":34,"./base":17,"_process":69}],23:[function(require,module,exports){
-(function (process){
-'use strict';
-/**
- * @module JSON
- */
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-var constants = require('../runner').constants;
-var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
-var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
-var EVENT_TEST_END = constants.EVENT_TEST_END;
-var EVENT_RUN_END = constants.EVENT_RUN_END;
-var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
-
-/**
- * Expose `JSON`.
- */
-
-exports = module.exports = JSONReporter;
-
-/**
- * Constructs a new `JSON` reporter instance.
- *
- * @public
- * @class JSON
- * @memberof Mocha.reporters
- * @extends Mocha.reporters.Base
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function JSONReporter(runner, options) {
- Base.call(this, runner, options);
-
- var self = this;
- var tests = [];
- var pending = [];
- var failures = [];
- var passes = [];
-
- runner.on(EVENT_TEST_END, function(test) {
- tests.push(test);
- });
-
- runner.on(EVENT_TEST_PASS, function(test) {
- passes.push(test);
- });
-
- runner.on(EVENT_TEST_FAIL, function(test) {
- failures.push(test);
- });
-
- runner.on(EVENT_TEST_PENDING, function(test) {
- pending.push(test);
- });
-
- runner.once(EVENT_RUN_END, function() {
- var obj = {
- stats: self.stats,
- tests: tests.map(clean),
- pending: pending.map(clean),
- failures: failures.map(clean),
- passes: passes.map(clean)
- };
-
- runner.testResults = obj;
-
- process.stdout.write(JSON.stringify(obj, null, 2));
- });
-}
-
-/**
- * Return a plain-object representation of `test`
- * free of cyclic properties etc.
- *
- * @private
- * @param {Object} test
- * @return {Object}
- */
-function clean(test) {
- var err = test.err || {};
- if (err instanceof Error) {
- err = errorJSON(err);
- }
-
- return {
- title: test.title,
- fullTitle: test.fullTitle(),
- duration: test.duration,
- currentRetry: test.currentRetry(),
- err: cleanCycles(err)
- };
-}
-
-/**
- * Replaces any circular references inside `obj` with '[object Object]'
- *
- * @private
- * @param {Object} obj
- * @return {Object}
- */
-function cleanCycles(obj) {
- var cache = [];
- return JSON.parse(
- JSON.stringify(obj, function(key, value) {
- if (typeof value === 'object' && value !== null) {
- if (cache.indexOf(value) !== -1) {
- // Instead of going in a circle, we'll print [object Object]
- return '' + value;
- }
- cache.push(value);
- }
-
- return value;
- })
- );
-}
-
-/**
- * Transform an Error object into a JSON object.
- *
- * @private
- * @param {Error} err
- * @return {Object}
- */
-function errorJSON(err) {
- var res = {};
- Object.getOwnPropertyNames(err).forEach(function(key) {
- res[key] = err[key];
- }, err);
- return res;
-}
-
-JSONReporter.description = 'single JSON object';
-
-}).call(this,require('_process'))
-},{"../runner":34,"./base":17,"_process":69}],24:[function(require,module,exports){
-(function (process){
-'use strict';
-/**
- * @module Landing
- */
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-var inherits = require('../utils').inherits;
-var constants = require('../runner').constants;
-var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
-var EVENT_RUN_END = constants.EVENT_RUN_END;
-var EVENT_TEST_END = constants.EVENT_TEST_END;
-var STATE_FAILED = require('../runnable').constants.STATE_FAILED;
-
-var cursor = Base.cursor;
-var color = Base.color;
-
-/**
- * Expose `Landing`.
- */
-
-exports = module.exports = Landing;
-
-/**
- * Airplane color.
- */
-
-Base.colors.plane = 0;
-
-/**
- * Airplane crash color.
- */
-
-Base.colors['plane crash'] = 31;
-
-/**
- * Runway color.
- */
-
-Base.colors.runway = 90;
-
-/**
- * Constructs a new `Landing` reporter instance.
- *
- * @public
- * @class
- * @memberof Mocha.reporters
- * @extends Mocha.reporters.Base
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function Landing(runner, options) {
- Base.call(this, runner, options);
-
- var self = this;
- var width = (Base.window.width * 0.75) | 0;
- var total = runner.total;
- var stream = process.stdout;
- var plane = color('plane', '✈');
- var crashed = -1;
- var n = 0;
-
- function runway() {
- var buf = Array(width).join('-');
- return ' ' + color('runway', buf);
- }
-
- runner.on(EVENT_RUN_BEGIN, function() {
- stream.write('\n\n\n ');
- cursor.hide();
- });
-
- runner.on(EVENT_TEST_END, function(test) {
- // check if the plane crashed
- var col = crashed === -1 ? ((width * ++n) / total) | 0 : crashed;
-
- // show the crash
- if (test.state === STATE_FAILED) {
- plane = color('plane crash', '✈');
- crashed = col;
- }
-
- // render landing strip
- stream.write('\u001b[' + (width + 1) + 'D\u001b[2A');
- stream.write(runway());
- stream.write('\n ');
- stream.write(color('runway', Array(col).join('⋅')));
- stream.write(plane);
- stream.write(color('runway', Array(width - col).join('⋅') + '\n'));
- stream.write(runway());
- stream.write('\u001b[0m');
- });
-
- runner.once(EVENT_RUN_END, function() {
- cursor.show();
- console.log();
- self.epilogue();
- });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-inherits(Landing, Base);
-
-Landing.description = 'Unicode landing strip';
-
-}).call(this,require('_process'))
-},{"../runnable":33,"../runner":34,"../utils":38,"./base":17,"_process":69}],25:[function(require,module,exports){
-(function (process){
-'use strict';
-/**
- * @module List
- */
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-var inherits = require('../utils').inherits;
-var constants = require('../runner').constants;
-var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
-var EVENT_RUN_END = constants.EVENT_RUN_END;
-var EVENT_TEST_BEGIN = constants.EVENT_TEST_BEGIN;
-var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
-var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
-var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
-var color = Base.color;
-var cursor = Base.cursor;
-
-/**
- * Expose `List`.
- */
-
-exports = module.exports = List;
-
-/**
- * Constructs a new `List` reporter instance.
- *
- * @public
- * @class
- * @memberof Mocha.reporters
- * @extends Mocha.reporters.Base
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function List(runner, options) {
- Base.call(this, runner, options);
-
- var self = this;
- var n = 0;
-
- runner.on(EVENT_RUN_BEGIN, function() {
- console.log();
- });
-
- runner.on(EVENT_TEST_BEGIN, function(test) {
- process.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));
- });
-
- runner.on(EVENT_TEST_PENDING, function(test) {
- var fmt = color('checkmark', ' -') + color('pending', ' %s');
- console.log(fmt, test.fullTitle());
- });
-
- runner.on(EVENT_TEST_PASS, function(test) {
- var fmt =
- color('checkmark', ' ' + Base.symbols.ok) +
- color('pass', ' %s: ') +
- color(test.speed, '%dms');
- cursor.CR();
- console.log(fmt, test.fullTitle(), test.duration);
- });
-
- runner.on(EVENT_TEST_FAIL, function(test) {
- cursor.CR();
- console.log(color('fail', ' %d) %s'), ++n, test.fullTitle());
- });
-
- runner.once(EVENT_RUN_END, self.epilogue.bind(self));
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-inherits(List, Base);
-
-List.description = 'like "spec" reporter but flat';
-
-}).call(this,require('_process'))
-},{"../runner":34,"../utils":38,"./base":17,"_process":69}],26:[function(require,module,exports){
-(function (process){
-'use strict';
-/**
- * @module Markdown
- */
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-var utils = require('../utils');
-var constants = require('../runner').constants;
-var EVENT_RUN_END = constants.EVENT_RUN_END;
-var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
-var EVENT_SUITE_END = constants.EVENT_SUITE_END;
-var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
-
-/**
- * Constants
- */
-
-var SUITE_PREFIX = '$';
-
-/**
- * Expose `Markdown`.
- */
-
-exports = module.exports = Markdown;
-
-/**
- * Constructs a new `Markdown` reporter instance.
- *
- * @public
- * @class
- * @memberof Mocha.reporters
- * @extends Mocha.reporters.Base
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function Markdown(runner, options) {
- Base.call(this, runner, options);
-
- var level = 0;
- var buf = '';
-
- function title(str) {
- return Array(level).join('#') + ' ' + str;
- }
-
- function mapTOC(suite, obj) {
- var ret = obj;
- var key = SUITE_PREFIX + suite.title;
-
- obj = obj[key] = obj[key] || {suite: suite};
- suite.suites.forEach(function(suite) {
- mapTOC(suite, obj);
- });
-
- return ret;
- }
-
- function stringifyTOC(obj, level) {
- ++level;
- var buf = '';
- var link;
- for (var key in obj) {
- if (key === 'suite') {
- continue;
- }
- if (key !== SUITE_PREFIX) {
- link = ' - [' + key.substring(1) + ']';
- link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
- buf += Array(level).join(' ') + link;
- }
- buf += stringifyTOC(obj[key], level);
- }
- return buf;
- }
-
- function generateTOC(suite) {
- var obj = mapTOC(suite, {});
- return stringifyTOC(obj, 0);
- }
-
- generateTOC(runner.suite);
-
- runner.on(EVENT_SUITE_BEGIN, function(suite) {
- ++level;
- var slug = utils.slug(suite.fullTitle());
- buf += ' ' + '\n';
- buf += title(suite.title) + '\n';
- });
-
- runner.on(EVENT_SUITE_END, function() {
- --level;
- });
-
- runner.on(EVENT_TEST_PASS, function(test) {
- var code = utils.clean(test.body);
- buf += test.title + '.\n';
- buf += '\n```js\n';
- buf += code + '\n';
- buf += '```\n\n';
- });
-
- runner.once(EVENT_RUN_END, function() {
- process.stdout.write('# TOC\n');
- process.stdout.write(generateTOC(runner.suite));
- process.stdout.write(buf);
- });
-}
-
-Markdown.description = 'GitHub Flavored Markdown';
-
-}).call(this,require('_process'))
-},{"../runner":34,"../utils":38,"./base":17,"_process":69}],27:[function(require,module,exports){
-(function (process){
-'use strict';
-/**
- * @module Min
- */
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-var inherits = require('../utils').inherits;
-var constants = require('../runner').constants;
-var EVENT_RUN_END = constants.EVENT_RUN_END;
-var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
-
-/**
- * Expose `Min`.
- */
-
-exports = module.exports = Min;
-
-/**
- * Constructs a new `Min` reporter instance.
- *
- * @description
- * This minimal test reporter is best used with '--watch'.
- *
- * @public
- * @class
- * @memberof Mocha.reporters
- * @extends Mocha.reporters.Base
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function Min(runner, options) {
- Base.call(this, runner, options);
-
- runner.on(EVENT_RUN_BEGIN, function() {
- // clear screen
- process.stdout.write('\u001b[2J');
- // set cursor position
- process.stdout.write('\u001b[1;3H');
- });
-
- runner.once(EVENT_RUN_END, this.epilogue.bind(this));
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-inherits(Min, Base);
-
-Min.description = 'essentially just a summary';
-
-}).call(this,require('_process'))
-},{"../runner":34,"../utils":38,"./base":17,"_process":69}],28:[function(require,module,exports){
-(function (process){
-'use strict';
-/**
- * @module Nyan
- */
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-var constants = require('../runner').constants;
-var inherits = require('../utils').inherits;
-var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
-var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
-var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
-var EVENT_RUN_END = constants.EVENT_RUN_END;
-var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
-
-/**
- * Expose `Dot`.
- */
-
-exports = module.exports = NyanCat;
-
-/**
- * Constructs a new `Nyan` reporter instance.
- *
- * @public
- * @class Nyan
- * @memberof Mocha.reporters
- * @extends Mocha.reporters.Base
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function NyanCat(runner, options) {
- Base.call(this, runner, options);
-
- var self = this;
- var width = (Base.window.width * 0.75) | 0;
- var nyanCatWidth = (this.nyanCatWidth = 11);
-
- this.colorIndex = 0;
- this.numberOfLines = 4;
- this.rainbowColors = self.generateColors();
- this.scoreboardWidth = 5;
- this.tick = 0;
- this.trajectories = [[], [], [], []];
- this.trajectoryWidthMax = width - nyanCatWidth;
-
- runner.on(EVENT_RUN_BEGIN, function() {
- Base.cursor.hide();
- self.draw();
- });
-
- runner.on(EVENT_TEST_PENDING, function() {
- self.draw();
- });
-
- runner.on(EVENT_TEST_PASS, function() {
- self.draw();
- });
-
- runner.on(EVENT_TEST_FAIL, function() {
- self.draw();
- });
-
- runner.once(EVENT_RUN_END, function() {
- Base.cursor.show();
- for (var i = 0; i < self.numberOfLines; i++) {
- write('\n');
- }
- self.epilogue();
- });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-inherits(NyanCat, Base);
-
-/**
- * Draw the nyan cat
- *
- * @private
- */
-
-NyanCat.prototype.draw = function() {
- this.appendRainbow();
- this.drawScoreboard();
- this.drawRainbow();
- this.drawNyanCat();
- this.tick = !this.tick;
-};
-
-/**
- * Draw the "scoreboard" showing the number
- * of passes, failures and pending tests.
- *
- * @private
- */
-
-NyanCat.prototype.drawScoreboard = function() {
- var stats = this.stats;
-
- function draw(type, n) {
- write(' ');
- write(Base.color(type, n));
- write('\n');
- }
-
- draw('green', stats.passes);
- draw('fail', stats.failures);
- draw('pending', stats.pending);
- write('\n');
-
- this.cursorUp(this.numberOfLines);
-};
-
-/**
- * Append the rainbow.
- *
- * @private
- */
-
-NyanCat.prototype.appendRainbow = function() {
- var segment = this.tick ? '_' : '-';
- var rainbowified = this.rainbowify(segment);
-
- for (var index = 0; index < this.numberOfLines; index++) {
- var trajectory = this.trajectories[index];
- if (trajectory.length >= this.trajectoryWidthMax) {
- trajectory.shift();
- }
- trajectory.push(rainbowified);
- }
-};
-
-/**
- * Draw the rainbow.
- *
- * @private
- */
-
-NyanCat.prototype.drawRainbow = function() {
- var self = this;
-
- this.trajectories.forEach(function(line) {
- write('\u001b[' + self.scoreboardWidth + 'C');
- write(line.join(''));
- write('\n');
- });
-
- this.cursorUp(this.numberOfLines);
-};
-
-/**
- * Draw the nyan cat
- *
- * @private
- */
-NyanCat.prototype.drawNyanCat = function() {
- var self = this;
- var startWidth = this.scoreboardWidth + this.trajectories[0].length;
- var dist = '\u001b[' + startWidth + 'C';
- var padding = '';
-
- write(dist);
- write('_,------,');
- write('\n');
-
- write(dist);
- padding = self.tick ? ' ' : ' ';
- write('_|' + padding + '/\\_/\\ ');
- write('\n');
-
- write(dist);
- padding = self.tick ? '_' : '__';
- var tail = self.tick ? '~' : '^';
- write(tail + '|' + padding + this.face() + ' ');
- write('\n');
-
- write(dist);
- padding = self.tick ? ' ' : ' ';
- write(padding + '"" "" ');
- write('\n');
-
- this.cursorUp(this.numberOfLines);
-};
-
-/**
- * Draw nyan cat face.
- *
- * @private
- * @return {string}
- */
-
-NyanCat.prototype.face = function() {
- var stats = this.stats;
- if (stats.failures) {
- return '( x .x)';
- } else if (stats.pending) {
- return '( o .o)';
- } else if (stats.passes) {
- return '( ^ .^)';
- }
- return '( - .-)';
-};
-
-/**
- * Move cursor up `n`.
- *
- * @private
- * @param {number} n
- */
-
-NyanCat.prototype.cursorUp = function(n) {
- write('\u001b[' + n + 'A');
-};
-
-/**
- * Move cursor down `n`.
- *
- * @private
- * @param {number} n
- */
-
-NyanCat.prototype.cursorDown = function(n) {
- write('\u001b[' + n + 'B');
-};
-
-/**
- * Generate rainbow colors.
- *
- * @private
- * @return {Array}
- */
-NyanCat.prototype.generateColors = function() {
- var colors = [];
-
- for (var i = 0; i < 6 * 7; i++) {
- var pi3 = Math.floor(Math.PI / 3);
- var n = i * (1.0 / 6);
- var r = Math.floor(3 * Math.sin(n) + 3);
- var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
- var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
- colors.push(36 * r + 6 * g + b + 16);
- }
-
- return colors;
-};
-
-/**
- * Apply rainbow to the given `str`.
- *
- * @private
- * @param {string} str
- * @return {string}
- */
-NyanCat.prototype.rainbowify = function(str) {
- if (!Base.useColors) {
- return str;
- }
- var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
- this.colorIndex += 1;
- return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
-};
-
-/**
- * Stdout helper.
- *
- * @param {string} string A message to write to stdout.
- */
-function write(string) {
- process.stdout.write(string);
-}
-
-NyanCat.description = '"nyan cat"';
-
-}).call(this,require('_process'))
-},{"../runner":34,"../utils":38,"./base":17,"_process":69}],29:[function(require,module,exports){
-(function (process){
-'use strict';
-/**
- * @module Progress
- */
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-var constants = require('../runner').constants;
-var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
-var EVENT_TEST_END = constants.EVENT_TEST_END;
-var EVENT_RUN_END = constants.EVENT_RUN_END;
-var inherits = require('../utils').inherits;
-var color = Base.color;
-var cursor = Base.cursor;
-
-/**
- * Expose `Progress`.
- */
-
-exports = module.exports = Progress;
-
-/**
- * General progress bar color.
- */
-
-Base.colors.progress = 90;
-
-/**
- * Constructs a new `Progress` reporter instance.
- *
- * @public
- * @class
- * @memberof Mocha.reporters
- * @extends Mocha.reporters.Base
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function Progress(runner, options) {
- Base.call(this, runner, options);
-
- var self = this;
- var width = (Base.window.width * 0.5) | 0;
- var total = runner.total;
- var complete = 0;
- var lastN = -1;
-
- // default chars
- options = options || {};
- var reporterOptions = options.reporterOptions || {};
-
- options.open = reporterOptions.open || '[';
- options.complete = reporterOptions.complete || '▬';
- options.incomplete = reporterOptions.incomplete || Base.symbols.dot;
- options.close = reporterOptions.close || ']';
- options.verbose = reporterOptions.verbose || false;
-
- // tests started
- runner.on(EVENT_RUN_BEGIN, function() {
- console.log();
- cursor.hide();
- });
-
- // tests complete
- runner.on(EVENT_TEST_END, function() {
- complete++;
-
- var percent = complete / total;
- var n = (width * percent) | 0;
- var i = width - n;
-
- if (n === lastN && !options.verbose) {
- // Don't re-render the line if it hasn't changed
- return;
- }
- lastN = n;
-
- cursor.CR();
- process.stdout.write('\u001b[J');
- process.stdout.write(color('progress', ' ' + options.open));
- process.stdout.write(Array(n).join(options.complete));
- process.stdout.write(Array(i).join(options.incomplete));
- process.stdout.write(color('progress', options.close));
- if (options.verbose) {
- process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
- }
- });
-
- // tests are complete, output some stats
- // and the failures if any
- runner.once(EVENT_RUN_END, function() {
- cursor.show();
- console.log();
- self.epilogue();
- });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-inherits(Progress, Base);
-
-Progress.description = 'a progress bar';
-
-}).call(this,require('_process'))
-},{"../runner":34,"../utils":38,"./base":17,"_process":69}],30:[function(require,module,exports){
-'use strict';
-/**
- * @module Spec
- */
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-var constants = require('../runner').constants;
-var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
-var EVENT_RUN_END = constants.EVENT_RUN_END;
-var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
-var EVENT_SUITE_END = constants.EVENT_SUITE_END;
-var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
-var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
-var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
-var inherits = require('../utils').inherits;
-var color = Base.color;
-
-/**
- * Expose `Spec`.
- */
-
-exports = module.exports = Spec;
-
-/**
- * Constructs a new `Spec` reporter instance.
- *
- * @public
- * @class
- * @memberof Mocha.reporters
- * @extends Mocha.reporters.Base
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function Spec(runner, options) {
- Base.call(this, runner, options);
-
- var self = this;
- var indents = 0;
- var n = 0;
-
- function indent() {
- return Array(indents).join(' ');
- }
-
- runner.on(EVENT_RUN_BEGIN, function() {
- console.log();
- });
-
- runner.on(EVENT_SUITE_BEGIN, function(suite) {
- ++indents;
- console.log(color('suite', '%s%s'), indent(), suite.title);
- });
-
- runner.on(EVENT_SUITE_END, function() {
- --indents;
- if (indents === 1) {
- console.log();
- }
- });
-
- runner.on(EVENT_TEST_PENDING, function(test) {
- var fmt = indent() + color('pending', ' - %s');
- console.log(fmt, test.title);
- });
-
- runner.on(EVENT_TEST_PASS, function(test) {
- var fmt;
- if (test.speed === 'fast') {
- fmt =
- indent() +
- color('checkmark', ' ' + Base.symbols.ok) +
- color('pass', ' %s');
- console.log(fmt, test.title);
- } else {
- fmt =
- indent() +
- color('checkmark', ' ' + Base.symbols.ok) +
- color('pass', ' %s') +
- color(test.speed, ' (%dms)');
- console.log(fmt, test.title, test.duration);
- }
- });
-
- runner.on(EVENT_TEST_FAIL, function(test) {
- console.log(indent() + color('fail', ' %d) %s'), ++n, test.title);
- });
-
- runner.once(EVENT_RUN_END, self.epilogue.bind(self));
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-inherits(Spec, Base);
-
-Spec.description = 'hierarchical & verbose [default]';
-
-},{"../runner":34,"../utils":38,"./base":17}],31:[function(require,module,exports){
-(function (process){
-'use strict';
-/**
- * @module TAP
- */
-/**
- * Module dependencies.
- */
-
-var util = require('util');
-var Base = require('./base');
-var constants = require('../runner').constants;
-var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
-var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
-var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
-var EVENT_RUN_END = constants.EVENT_RUN_END;
-var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
-var EVENT_TEST_END = constants.EVENT_TEST_END;
-var inherits = require('../utils').inherits;
-var sprintf = util.format;
-
-/**
- * Expose `TAP`.
- */
-
-exports = module.exports = TAP;
-
-/**
- * Constructs a new `TAP` reporter instance.
- *
- * @public
- * @class
- * @memberof Mocha.reporters
- * @extends Mocha.reporters.Base
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function TAP(runner, options) {
- Base.call(this, runner, options);
-
- var self = this;
- var n = 1;
-
- var tapVersion = '12';
- if (options && options.reporterOptions) {
- if (options.reporterOptions.tapVersion) {
- tapVersion = options.reporterOptions.tapVersion.toString();
- }
- }
-
- this._producer = createProducer(tapVersion);
-
- runner.once(EVENT_RUN_BEGIN, function() {
- var ntests = runner.grepTotal(runner.suite);
- self._producer.writeVersion();
- self._producer.writePlan(ntests);
- });
-
- runner.on(EVENT_TEST_END, function() {
- ++n;
- });
-
- runner.on(EVENT_TEST_PENDING, function(test) {
- self._producer.writePending(n, test);
- });
-
- runner.on(EVENT_TEST_PASS, function(test) {
- self._producer.writePass(n, test);
- });
-
- runner.on(EVENT_TEST_FAIL, function(test, err) {
- self._producer.writeFail(n, test, err);
- });
-
- runner.once(EVENT_RUN_END, function() {
- self._producer.writeEpilogue(runner.stats);
- });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-inherits(TAP, Base);
-
-/**
- * Returns a TAP-safe title of `test`.
- *
- * @private
- * @param {Test} test - Test instance.
- * @return {String} title with any hash character removed
- */
-function title(test) {
- return test.fullTitle().replace(/#/g, '');
-}
-
-/**
- * Writes newline-terminated formatted string to reporter output stream.
- *
- * @private
- * @param {string} format - `printf`-like format string
- * @param {...*} [varArgs] - Format string arguments
- */
-function println(format, varArgs) {
- var vargs = Array.from(arguments);
- vargs[0] += '\n';
- process.stdout.write(sprintf.apply(null, vargs));
-}
-
-/**
- * Returns a `tapVersion`-appropriate TAP producer instance, if possible.
- *
- * @private
- * @param {string} tapVersion - Version of TAP specification to produce.
- * @returns {TAPProducer} specification-appropriate instance
- * @throws {Error} if specification version has no associated producer.
- */
-function createProducer(tapVersion) {
- var producers = {
- '12': new TAP12Producer(),
- '13': new TAP13Producer()
- };
- var producer = producers[tapVersion];
-
- if (!producer) {
- throw new Error(
- 'invalid or unsupported TAP version: ' + JSON.stringify(tapVersion)
- );
- }
-
- return producer;
-}
-
-/**
- * @summary
- * Constructs a new TAPProducer.
- *
- * @description
- * Only to be used as an abstract base class.
- *
- * @private
- * @constructor
- */
-function TAPProducer() {}
-
-/**
- * Writes the TAP version to reporter output stream.
- *
- * @abstract
- */
-TAPProducer.prototype.writeVersion = function() {};
-
-/**
- * Writes the plan to reporter output stream.
- *
- * @abstract
- * @param {number} ntests - Number of tests that are planned to run.
- */
-TAPProducer.prototype.writePlan = function(ntests) {
- println('%d..%d', 1, ntests);
-};
-
-/**
- * Writes that test passed to reporter output stream.
- *
- * @abstract
- * @param {number} n - Index of test that passed.
- * @param {Test} test - Instance containing test information.
- */
-TAPProducer.prototype.writePass = function(n, test) {
- println('ok %d %s', n, title(test));
-};
-
-/**
- * Writes that test was skipped to reporter output stream.
- *
- * @abstract
- * @param {number} n - Index of test that was skipped.
- * @param {Test} test - Instance containing test information.
- */
-TAPProducer.prototype.writePending = function(n, test) {
- println('ok %d %s # SKIP -', n, title(test));
-};
-
-/**
- * Writes that test failed to reporter output stream.
- *
- * @abstract
- * @param {number} n - Index of test that failed.
- * @param {Test} test - Instance containing test information.
- * @param {Error} err - Reason the test failed.
- */
-TAPProducer.prototype.writeFail = function(n, test, err) {
- println('not ok %d %s', n, title(test));
-};
-
-/**
- * Writes the summary epilogue to reporter output stream.
- *
- * @abstract
- * @param {Object} stats - Object containing run statistics.
- */
-TAPProducer.prototype.writeEpilogue = function(stats) {
- // :TBD: Why is this not counting pending tests?
- println('# tests ' + (stats.passes + stats.failures));
- println('# pass ' + stats.passes);
- // :TBD: Why are we not showing pending results?
- println('# fail ' + stats.failures);
-};
-
-/**
- * @summary
- * Constructs a new TAP12Producer.
- *
- * @description
- * Produces output conforming to the TAP12 specification.
- *
- * @private
- * @constructor
- * @extends TAPProducer
- * @see {@link https://testanything.org/tap-specification.html|Specification}
- */
-function TAP12Producer() {
- /**
- * Writes that test failed to reporter output stream, with error formatting.
- * @override
- */
- this.writeFail = function(n, test, err) {
- TAPProducer.prototype.writeFail.call(this, n, test, err);
- if (err.message) {
- println(err.message.replace(/^/gm, ' '));
- }
- if (err.stack) {
- println(err.stack.replace(/^/gm, ' '));
- }
- };
-}
-
-/**
- * Inherit from `TAPProducer.prototype`.
- */
-inherits(TAP12Producer, TAPProducer);
-
-/**
- * @summary
- * Constructs a new TAP13Producer.
- *
- * @description
- * Produces output conforming to the TAP13 specification.
- *
- * @private
- * @constructor
- * @extends TAPProducer
- * @see {@link https://testanything.org/tap-version-13-specification.html|Specification}
- */
-function TAP13Producer() {
- /**
- * Writes the TAP version to reporter output stream.
- * @override
- */
- this.writeVersion = function() {
- println('TAP version 13');
- };
-
- /**
- * Writes that test failed to reporter output stream, with error formatting.
- * @override
- */
- this.writeFail = function(n, test, err) {
- TAPProducer.prototype.writeFail.call(this, n, test, err);
- var emitYamlBlock = err.message != null || err.stack != null;
- if (emitYamlBlock) {
- println(indent(1) + '---');
- if (err.message) {
- println(indent(2) + 'message: |-');
- println(err.message.replace(/^/gm, indent(3)));
- }
- if (err.stack) {
- println(indent(2) + 'stack: |-');
- println(err.stack.replace(/^/gm, indent(3)));
- }
- println(indent(1) + '...');
- }
- };
-
- function indent(level) {
- return Array(level + 1).join(' ');
- }
-}
-
-/**
- * Inherit from `TAPProducer.prototype`.
- */
-inherits(TAP13Producer, TAPProducer);
-
-TAP.description = 'TAP-compatible output';
-
-}).call(this,require('_process'))
-},{"../runner":34,"../utils":38,"./base":17,"_process":69,"util":89}],32:[function(require,module,exports){
-(function (process,global){
-'use strict';
-/**
- * @module XUnit
- */
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-var utils = require('../utils');
-var fs = require('fs');
-var mkdirp = require('mkdirp');
-var path = require('path');
-var errors = require('../errors');
-var createUnsupportedError = errors.createUnsupportedError;
-var constants = require('../runner').constants;
-var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
-var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
-var EVENT_RUN_END = constants.EVENT_RUN_END;
-var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
-var STATE_FAILED = require('../runnable').constants.STATE_FAILED;
-var inherits = utils.inherits;
-var escape = utils.escape;
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-var Date = global.Date;
-
-/**
- * Expose `XUnit`.
- */
-
-exports = module.exports = XUnit;
-
-/**
- * Constructs a new `XUnit` reporter instance.
- *
- * @public
- * @class
- * @memberof Mocha.reporters
- * @extends Mocha.reporters.Base
- * @param {Runner} runner - Instance triggers reporter actions.
- * @param {Object} [options] - runner options
- */
-function XUnit(runner, options) {
- Base.call(this, runner, options);
-
- var stats = this.stats;
- var tests = [];
- var self = this;
-
- // the name of the test suite, as it will appear in the resulting XML file
- var suiteName;
-
- // the default name of the test suite if none is provided
- var DEFAULT_SUITE_NAME = 'Mocha Tests';
-
- if (options && options.reporterOptions) {
- if (options.reporterOptions.output) {
- if (!fs.createWriteStream) {
- throw createUnsupportedError('file output not supported in browser');
- }
-
- mkdirp.sync(path.dirname(options.reporterOptions.output));
- self.fileStream = fs.createWriteStream(options.reporterOptions.output);
- }
-
- // get the suite name from the reporter options (if provided)
- suiteName = options.reporterOptions.suiteName;
- }
-
- // fall back to the default suite name
- suiteName = suiteName || DEFAULT_SUITE_NAME;
-
- runner.on(EVENT_TEST_PENDING, function(test) {
- tests.push(test);
- });
-
- runner.on(EVENT_TEST_PASS, function(test) {
- tests.push(test);
- });
-
- runner.on(EVENT_TEST_FAIL, function(test) {
- tests.push(test);
- });
-
- runner.once(EVENT_RUN_END, function() {
- self.write(
- tag(
- 'testsuite',
- {
- name: suiteName,
- tests: stats.tests,
- failures: 0,
- errors: stats.failures,
- skipped: stats.tests - stats.failures - stats.passes,
- timestamp: new Date().toUTCString(),
- time: stats.duration / 1000 || 0
- },
- false
- )
- );
-
- tests.forEach(function(t) {
- self.test(t);
- });
-
- self.write('');
- });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-inherits(XUnit, Base);
-
-/**
- * Override done to close the stream (if it's a file).
- *
- * @param failures
- * @param {Function} fn
- */
-XUnit.prototype.done = function(failures, fn) {
- if (this.fileStream) {
- this.fileStream.end(function() {
- fn(failures);
- });
- } else {
- fn(failures);
- }
-};
-
-/**
- * Write out the given line.
- *
- * @param {string} line
- */
-XUnit.prototype.write = function(line) {
- if (this.fileStream) {
- this.fileStream.write(line + '\n');
- } else if (typeof process === 'object' && process.stdout) {
- process.stdout.write(line + '\n');
- } else {
- console.log(line);
- }
-};
-
-/**
- * Output tag for the given `test.`
- *
- * @param {Test} test
- */
-XUnit.prototype.test = function(test) {
- Base.useColors = false;
-
- var attrs = {
- classname: test.parent.fullTitle(),
- name: test.title,
- time: test.duration / 1000 || 0
- };
-
- if (test.state === STATE_FAILED) {
- var err = test.err;
- var diff =
- Base.hideDiff || !err.actual || !err.expected
- ? ''
- : '\n' + Base.generateDiff(err.actual, err.expected);
- this.write(
- tag(
- 'testcase',
- attrs,
- false,
- tag(
- 'failure',
- {},
- false,
- escape(err.message) + escape(diff) + '\n' + escape(err.stack)
- )
- )
- );
- } else if (test.isPending()) {
- this.write(tag('testcase', attrs, false, tag('skipped', {}, true)));
- } else {
- this.write(tag('testcase', attrs, true));
- }
-};
-
-/**
- * HTML tag helper.
- *
- * @param name
- * @param attrs
- * @param close
- * @param content
- * @return {string}
- */
-function tag(name, attrs, close, content) {
- var end = close ? '/>' : '>';
- var pairs = [];
- var tag;
-
- for (var key in attrs) {
- if (Object.prototype.hasOwnProperty.call(attrs, key)) {
- pairs.push(key + '="' + escape(attrs[key]) + '"');
- }
- }
-
- tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
- if (content) {
- tag += content + '' + name + end;
- }
- return tag;
-}
-
-XUnit.description = 'XUnit-compatible XML output';
-
-}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"../errors":6,"../runnable":33,"../runner":34,"../utils":38,"./base":17,"_process":69,"fs":42,"mkdirp":59,"path":42}],33:[function(require,module,exports){
-(function (global){
-'use strict';
-
-var EventEmitter = require('events').EventEmitter;
-var Pending = require('./pending');
-var debug = require('debug')('mocha:runnable');
-var milliseconds = require('ms');
-var utils = require('./utils');
-var createInvalidExceptionError = require('./errors')
- .createInvalidExceptionError;
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-var Date = global.Date;
-var setTimeout = global.setTimeout;
-var clearTimeout = global.clearTimeout;
-var toString = Object.prototype.toString;
-
-module.exports = Runnable;
-
-/**
- * Initialize a new `Runnable` with the given `title` and callback `fn`.
- *
- * @class
- * @extends external:EventEmitter
- * @public
- * @param {String} title
- * @param {Function} fn
- */
-function Runnable(title, fn) {
- this.title = title;
- this.fn = fn;
- this.body = (fn || '').toString();
- this.async = fn && fn.length;
- this.sync = !this.async;
- this._timeout = 2000;
- this._slow = 75;
- this._enableTimeouts = true;
- this.timedOut = false;
- this._retries = -1;
- this._currentRetry = 0;
- this.pending = false;
-}
-
-/**
- * Inherit from `EventEmitter.prototype`.
- */
-utils.inherits(Runnable, EventEmitter);
-
-/**
- * Get current timeout value in msecs.
- *
- * @private
- * @returns {number} current timeout threshold value
- */
-/**
- * @summary
- * Set timeout threshold value (msecs).
- *
- * @description
- * A string argument can use shorthand (e.g., "2s") and will be converted.
- * The value will be clamped to range [0
, 2^31 -1
].
- * If clamped value matches either range endpoint, timeouts will be disabled.
- *
- * @private
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Maximum_delay_value}
- * @param {number|string} ms - Timeout threshold value.
- * @returns {Runnable} this
- * @chainable
- */
-Runnable.prototype.timeout = function(ms) {
- if (!arguments.length) {
- return this._timeout;
- }
- if (typeof ms === 'string') {
- ms = milliseconds(ms);
- }
-
- // Clamp to range
- var INT_MAX = Math.pow(2, 31) - 1;
- var range = [0, INT_MAX];
- ms = utils.clamp(ms, range);
-
- // see #1652 for reasoning
- if (ms === range[0] || ms === range[1]) {
- this._enableTimeouts = false;
- }
- debug('timeout %d', ms);
- this._timeout = ms;
- if (this.timer) {
- this.resetTimeout();
- }
- return this;
-};
-
-/**
- * Set or get slow `ms`.
- *
- * @private
- * @param {number|string} ms
- * @return {Runnable|number} ms or Runnable instance.
- */
-Runnable.prototype.slow = function(ms) {
- if (!arguments.length || typeof ms === 'undefined') {
- return this._slow;
- }
- if (typeof ms === 'string') {
- ms = milliseconds(ms);
- }
- debug('slow %d', ms);
- this._slow = ms;
- return this;
-};
-
-/**
- * Set and get whether timeout is `enabled`.
- *
- * @private
- * @param {boolean} enabled
- * @return {Runnable|boolean} enabled or Runnable instance.
- */
-Runnable.prototype.enableTimeouts = function(enabled) {
- if (!arguments.length) {
- return this._enableTimeouts;
- }
- debug('enableTimeouts %s', enabled);
- this._enableTimeouts = enabled;
- return this;
-};
-
-/**
- * Halt and mark as pending.
- *
- * @memberof Mocha.Runnable
- * @public
- */
-Runnable.prototype.skip = function() {
- throw new Pending('sync skip');
-};
-
-/**
- * Check if this runnable or its parent suite is marked as pending.
- *
- * @private
- */
-Runnable.prototype.isPending = function() {
- return this.pending || (this.parent && this.parent.isPending());
-};
-
-/**
- * Return `true` if this Runnable has failed.
- * @return {boolean}
- * @private
- */
-Runnable.prototype.isFailed = function() {
- return !this.isPending() && this.state === constants.STATE_FAILED;
-};
-
-/**
- * Return `true` if this Runnable has passed.
- * @return {boolean}
- * @private
- */
-Runnable.prototype.isPassed = function() {
- return !this.isPending() && this.state === constants.STATE_PASSED;
-};
-
-/**
- * Set or get number of retries.
- *
- * @private
- */
-Runnable.prototype.retries = function(n) {
- if (!arguments.length) {
- return this._retries;
- }
- this._retries = n;
-};
-
-/**
- * Set or get current retry
- *
- * @private
- */
-Runnable.prototype.currentRetry = function(n) {
- if (!arguments.length) {
- return this._currentRetry;
- }
- this._currentRetry = n;
-};
-
-/**
- * Return the full title generated by recursively concatenating the parent's
- * full title.
- *
- * @memberof Mocha.Runnable
- * @public
- * @return {string}
- */
-Runnable.prototype.fullTitle = function() {
- return this.titlePath().join(' ');
-};
-
-/**
- * Return the title path generated by concatenating the parent's title path with the title.
- *
- * @memberof Mocha.Runnable
- * @public
- * @return {string}
- */
-Runnable.prototype.titlePath = function() {
- return this.parent.titlePath().concat([this.title]);
-};
-
-/**
- * Clear the timeout.
- *
- * @private
- */
-Runnable.prototype.clearTimeout = function() {
- clearTimeout(this.timer);
-};
-
-/**
- * Inspect the runnable void of private properties.
- *
- * @private
- * @return {string}
- */
-Runnable.prototype.inspect = function() {
- return JSON.stringify(
- this,
- function(key, val) {
- if (key[0] === '_') {
- return;
- }
- if (key === 'parent') {
- return '#';
- }
- if (key === 'ctx') {
- return '#';
- }
- return val;
- },
- 2
- );
-};
-
-/**
- * Reset the timeout.
- *
- * @private
- */
-Runnable.prototype.resetTimeout = function() {
- var self = this;
- var ms = this.timeout() || 1e9;
-
- if (!this._enableTimeouts) {
- return;
- }
- this.clearTimeout();
- this.timer = setTimeout(function() {
- if (!self._enableTimeouts) {
- return;
- }
- self.callback(self._timeoutError(ms));
- self.timedOut = true;
- }, ms);
-};
-
-/**
- * Set or get a list of whitelisted globals for this test run.
- *
- * @private
- * @param {string[]} globals
- */
-Runnable.prototype.globals = function(globals) {
- if (!arguments.length) {
- return this._allowedGlobals;
- }
- this._allowedGlobals = globals;
-};
-
-/**
- * Run the test and invoke `fn(err)`.
- *
- * @param {Function} fn
- * @private
- */
-Runnable.prototype.run = function(fn) {
- var self = this;
- var start = new Date();
- var ctx = this.ctx;
- var finished;
- var emitted;
-
- // Sometimes the ctx exists, but it is not runnable
- if (ctx && ctx.runnable) {
- ctx.runnable(this);
- }
-
- // called multiple times
- function multiple(err) {
- if (emitted) {
- return;
- }
- emitted = true;
- var msg = 'done() called multiple times';
- if (err && err.message) {
- err.message += " (and Mocha's " + msg + ')';
- self.emit('error', err);
- } else {
- self.emit('error', new Error(msg));
- }
- }
-
- // finished
- function done(err) {
- var ms = self.timeout();
- if (self.timedOut) {
- return;
- }
-
- if (finished) {
- return multiple(err);
- }
-
- self.clearTimeout();
- self.duration = new Date() - start;
- finished = true;
- if (!err && self.duration > ms && self._enableTimeouts) {
- err = self._timeoutError(ms);
- }
- fn(err);
- }
-
- // for .resetTimeout()
- this.callback = done;
-
- // explicit async with `done` argument
- if (this.async) {
- this.resetTimeout();
-
- // allows skip() to be used in an explicit async context
- this.skip = function asyncSkip() {
- done(new Pending('async skip call'));
- // halt execution. the Runnable will be marked pending
- // by the previous call, and the uncaught handler will ignore
- // the failure.
- throw new Pending('async skip; aborting execution');
- };
-
- if (this.allowUncaught) {
- return callFnAsync(this.fn);
- }
- try {
- callFnAsync(this.fn);
- } catch (err) {
- emitted = true;
- done(Runnable.toValueOrError(err));
- }
- return;
- }
-
- if (this.allowUncaught) {
- if (this.isPending()) {
- done();
- } else {
- callFn(this.fn);
- }
- return;
- }
-
- // sync or promise-returning
- try {
- if (this.isPending()) {
- done();
- } else {
- callFn(this.fn);
- }
- } catch (err) {
- emitted = true;
- done(Runnable.toValueOrError(err));
- }
-
- function callFn(fn) {
- var result = fn.call(ctx);
- if (result && typeof result.then === 'function') {
- self.resetTimeout();
- result.then(
- function() {
- done();
- // Return null so libraries like bluebird do not warn about
- // subsequently constructed Promises.
- return null;
- },
- function(reason) {
- done(reason || new Error('Promise rejected with no or falsy reason'));
- }
- );
- } else {
- if (self.asyncOnly) {
- return done(
- new Error(
- '--async-only option in use without declaring `done()` or returning a promise'
- )
- );
- }
-
- done();
- }
- }
-
- function callFnAsync(fn) {
- var result = fn.call(ctx, function(err) {
- if (err instanceof Error || toString.call(err) === '[object Error]') {
- return done(err);
- }
- if (err) {
- if (Object.prototype.toString.call(err) === '[object Object]') {
- return done(
- new Error('done() invoked with non-Error: ' + JSON.stringify(err))
- );
- }
- return done(new Error('done() invoked with non-Error: ' + err));
- }
- if (result && utils.isPromise(result)) {
- return done(
- new Error(
- 'Resolution method is overspecified. Specify a callback *or* return a Promise; not both.'
- )
- );
- }
-
- done();
- });
- }
-};
-
-/**
- * Instantiates a "timeout" error
- *
- * @param {number} ms - Timeout (in milliseconds)
- * @returns {Error} a "timeout" error
- * @private
- */
-Runnable.prototype._timeoutError = function(ms) {
- var msg =
- 'Timeout of ' +
- ms +
- 'ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.';
- if (this.file) {
- msg += ' (' + this.file + ')';
- }
- return new Error(msg);
-};
-
-var constants = utils.defineConstants(
- /**
- * {@link Runnable}-related constants.
- * @public
- * @memberof Runnable
- * @readonly
- * @static
- * @alias constants
- * @enum {string}
- */
- {
- /**
- * Value of `state` prop when a `Runnable` has failed
- */
- STATE_FAILED: 'failed',
- /**
- * Value of `state` prop when a `Runnable` has passed
- */
- STATE_PASSED: 'passed'
- }
-);
-
-/**
- * Given `value`, return identity if truthy, otherwise create an "invalid exception" error and return that.
- * @param {*} [value] - Value to return, if present
- * @returns {*|Error} `value`, otherwise an `Error`
- * @private
- */
-Runnable.toValueOrError = function(value) {
- return (
- value ||
- createInvalidExceptionError(
- 'Runnable failed with falsy or undefined exception. Please throw an Error instead.',
- value
- )
- );
-};
-
-Runnable.constants = constants;
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"./errors":6,"./pending":16,"./utils":38,"debug":45,"events":50,"ms":60}],34:[function(require,module,exports){
-(function (process,global){
-'use strict';
-
-/**
- * Module dependencies.
- */
-var util = require('util');
-var EventEmitter = require('events').EventEmitter;
-var Pending = require('./pending');
-var utils = require('./utils');
-var inherits = utils.inherits;
-var debug = require('debug')('mocha:runner');
-var Runnable = require('./runnable');
-var Suite = require('./suite');
-var HOOK_TYPE_BEFORE_EACH = Suite.constants.HOOK_TYPE_BEFORE_EACH;
-var HOOK_TYPE_AFTER_EACH = Suite.constants.HOOK_TYPE_AFTER_EACH;
-var HOOK_TYPE_AFTER_ALL = Suite.constants.HOOK_TYPE_AFTER_ALL;
-var HOOK_TYPE_BEFORE_ALL = Suite.constants.HOOK_TYPE_BEFORE_ALL;
-var EVENT_ROOT_SUITE_RUN = Suite.constants.EVENT_ROOT_SUITE_RUN;
-var STATE_FAILED = Runnable.constants.STATE_FAILED;
-var STATE_PASSED = Runnable.constants.STATE_PASSED;
-var dQuote = utils.dQuote;
-var ngettext = utils.ngettext;
-var sQuote = utils.sQuote;
-var stackFilter = utils.stackTraceFilter();
-var stringify = utils.stringify;
-var type = utils.type;
-var createInvalidExceptionError = require('./errors')
- .createInvalidExceptionError;
-
-/**
- * Non-enumerable globals.
- * @readonly
- */
-var globals = [
- 'setTimeout',
- 'clearTimeout',
- 'setInterval',
- 'clearInterval',
- 'XMLHttpRequest',
- 'Date',
- 'setImmediate',
- 'clearImmediate'
-];
-
-var constants = utils.defineConstants(
- /**
- * {@link Runner}-related constants.
- * @public
- * @memberof Runner
- * @readonly
- * @alias constants
- * @static
- * @enum {string}
- */
- {
- /**
- * Emitted when {@link Hook} execution begins
- */
- EVENT_HOOK_BEGIN: 'hook',
- /**
- * Emitted when {@link Hook} execution ends
- */
- EVENT_HOOK_END: 'hook end',
- /**
- * Emitted when Root {@link Suite} execution begins (all files have been parsed and hooks/tests are ready for execution)
- */
- EVENT_RUN_BEGIN: 'start',
- /**
- * Emitted when Root {@link Suite} execution has been delayed via `delay` option
- */
- EVENT_DELAY_BEGIN: 'waiting',
- /**
- * Emitted when delayed Root {@link Suite} execution is triggered by user via `global.run()`
- */
- EVENT_DELAY_END: 'ready',
- /**
- * Emitted when Root {@link Suite} execution ends
- */
- EVENT_RUN_END: 'end',
- /**
- * Emitted when {@link Suite} execution begins
- */
- EVENT_SUITE_BEGIN: 'suite',
- /**
- * Emitted when {@link Suite} execution ends
- */
- EVENT_SUITE_END: 'suite end',
- /**
- * Emitted when {@link Test} execution begins
- */
- EVENT_TEST_BEGIN: 'test',
- /**
- * Emitted when {@link Test} execution ends
- */
- EVENT_TEST_END: 'test end',
- /**
- * Emitted when {@link Test} execution fails
- */
- EVENT_TEST_FAIL: 'fail',
- /**
- * Emitted when {@link Test} execution succeeds
- */
- EVENT_TEST_PASS: 'pass',
- /**
- * Emitted when {@link Test} becomes pending
- */
- EVENT_TEST_PENDING: 'pending',
- /**
- * Emitted when {@link Test} execution has failed, but will retry
- */
- EVENT_TEST_RETRY: 'retry'
- }
-);
-
-module.exports = Runner;
-
-/**
- * Initialize a `Runner` at the Root {@link Suite}, which represents a hierarchy of {@link Suite|Suites} and {@link Test|Tests}.
- *
- * @extends external:EventEmitter
- * @public
- * @class
- * @param {Suite} suite Root suite
- * @param {boolean} [delay] Whether or not to delay execution of root suite
- * until ready.
- */
-function Runner(suite, delay) {
- var self = this;
- this._globals = [];
- this._abort = false;
- this._delay = delay;
- this.suite = suite;
- this.started = false;
- this.total = suite.total();
- this.failures = 0;
- this.on(constants.EVENT_TEST_END, function(test) {
- self.checkGlobals(test);
- });
- this.on(constants.EVENT_HOOK_END, function(hook) {
- self.checkGlobals(hook);
- });
- this._defaultGrep = /.*/;
- this.grep(this._defaultGrep);
- this.globals(this.globalProps().concat(extraGlobals()));
-}
-
-/**
- * Wrapper for setImmediate, process.nextTick, or browser polyfill.
- *
- * @param {Function} fn
- * @private
- */
-Runner.immediately = global.setImmediate || process.nextTick;
-
-/**
- * Inherit from `EventEmitter.prototype`.
- */
-inherits(Runner, EventEmitter);
-
-/**
- * Run tests with full titles matching `re`. Updates runner.total
- * with number of tests matched.
- *
- * @public
- * @memberof Runner
- * @param {RegExp} re
- * @param {boolean} invert
- * @return {Runner} Runner instance.
- */
-Runner.prototype.grep = function(re, invert) {
- debug('grep %s', re);
- this._grep = re;
- this._invert = invert;
- this.total = this.grepTotal(this.suite);
- return this;
-};
-
-/**
- * Returns the number of tests matching the grep search for the
- * given suite.
- *
- * @memberof Runner
- * @public
- * @param {Suite} suite
- * @return {number}
- */
-Runner.prototype.grepTotal = function(suite) {
- var self = this;
- var total = 0;
-
- suite.eachTest(function(test) {
- var match = self._grep.test(test.fullTitle());
- if (self._invert) {
- match = !match;
- }
- if (match) {
- total++;
- }
- });
-
- return total;
-};
-
-/**
- * Return a list of global properties.
- *
- * @return {Array}
- * @private
- */
-Runner.prototype.globalProps = function() {
- var props = Object.keys(global);
-
- // non-enumerables
- for (var i = 0; i < globals.length; ++i) {
- if (~props.indexOf(globals[i])) {
- continue;
- }
- props.push(globals[i]);
- }
-
- return props;
-};
-
-/**
- * Allow the given `arr` of globals.
- *
- * @public
- * @memberof Runner
- * @param {Array} arr
- * @return {Runner} Runner instance.
- */
-Runner.prototype.globals = function(arr) {
- if (!arguments.length) {
- return this._globals;
- }
- debug('globals %j', arr);
- this._globals = this._globals.concat(arr);
- return this;
-};
-
-/**
- * Check for global variable leaks.
- *
- * @private
- */
-Runner.prototype.checkGlobals = function(test) {
- if (this.ignoreLeaks) {
- return;
- }
- var ok = this._globals;
-
- var globals = this.globalProps();
- var leaks;
-
- if (test) {
- ok = ok.concat(test._allowedGlobals || []);
- }
-
- if (this.prevGlobalsLength === globals.length) {
- return;
- }
- this.prevGlobalsLength = globals.length;
-
- leaks = filterLeaks(ok, globals);
- this._globals = this._globals.concat(leaks);
-
- if (leaks.length) {
- var format = ngettext(
- leaks.length,
- 'global leak detected: %s',
- 'global leaks detected: %s'
- );
- var error = new Error(util.format(format, leaks.map(sQuote).join(', ')));
- this.fail(test, error);
- }
-};
-
-/**
- * Fail the given `test`.
- *
- * @private
- * @param {Test} test
- * @param {Error} err
- */
-Runner.prototype.fail = function(test, err) {
- if (test.isPending()) {
- return;
- }
-
- ++this.failures;
- test.state = STATE_FAILED;
-
- if (!isError(err)) {
- err = thrown2Error(err);
- }
-
- try {
- err.stack =
- this.fullStackTrace || !err.stack ? err.stack : stackFilter(err.stack);
- } catch (ignore) {
- // some environments do not take kindly to monkeying with the stack
- }
-
- this.emit(constants.EVENT_TEST_FAIL, test, err);
-};
-
-/**
- * Fail the given `hook` with `err`.
- *
- * Hook failures work in the following pattern:
- * - If bail, run corresponding `after each` and `after` hooks,
- * then exit
- * - Failed `before` hook skips all tests in a suite and subsuites,
- * but jumps to corresponding `after` hook
- * - Failed `before each` hook skips remaining tests in a
- * suite and jumps to corresponding `after each` hook,
- * which is run only once
- * - Failed `after` hook does not alter
- * execution order
- * - Failed `after each` hook skips remaining tests in a
- * suite and subsuites, but executes other `after each`
- * hooks
- *
- * @private
- * @param {Hook} hook
- * @param {Error} err
- */
-Runner.prototype.failHook = function(hook, err) {
- hook.originalTitle = hook.originalTitle || hook.title;
- if (hook.ctx && hook.ctx.currentTest) {
- hook.title =
- hook.originalTitle + ' for ' + dQuote(hook.ctx.currentTest.title);
- } else {
- var parentTitle;
- if (hook.parent.title) {
- parentTitle = hook.parent.title;
- } else {
- parentTitle = hook.parent.root ? '{root}' : '';
- }
- hook.title = hook.originalTitle + ' in ' + dQuote(parentTitle);
- }
-
- this.fail(hook, err);
-};
-
-/**
- * Run hook `name` callbacks and then invoke `fn()`.
- *
- * @private
- * @param {string} name
- * @param {Function} fn
- */
-
-Runner.prototype.hook = function(name, fn) {
- var suite = this.suite;
- var hooks = suite.getHooks(name);
- var self = this;
-
- function next(i) {
- var hook = hooks[i];
- if (!hook) {
- return fn();
- }
- self.currentRunnable = hook;
-
- if (name === HOOK_TYPE_BEFORE_ALL) {
- hook.ctx.currentTest = hook.parent.tests[0];
- } else if (name === HOOK_TYPE_AFTER_ALL) {
- hook.ctx.currentTest = hook.parent.tests[hook.parent.tests.length - 1];
- } else {
- hook.ctx.currentTest = self.test;
- }
-
- hook.allowUncaught = self.allowUncaught;
-
- self.emit(constants.EVENT_HOOK_BEGIN, hook);
-
- if (!hook.listeners('error').length) {
- hook.on('error', function(err) {
- self.failHook(hook, err);
- });
- }
-
- hook.run(function(err) {
- var testError = hook.error();
- if (testError) {
- self.fail(self.test, testError);
- }
- if (err) {
- if (err instanceof Pending) {
- if (name === HOOK_TYPE_AFTER_ALL) {
- utils.deprecate(
- 'Skipping a test within an "after all" hook is DEPRECATED and will throw an exception in a future version of Mocha. ' +
- 'Use a return statement or other means to abort hook execution.'
- );
- }
- if (name === HOOK_TYPE_BEFORE_EACH || name === HOOK_TYPE_AFTER_EACH) {
- if (self.test) {
- self.test.pending = true;
- }
- } else {
- suite.tests.forEach(function(test) {
- test.pending = true;
- });
- suite.suites.forEach(function(suite) {
- suite.pending = true;
- });
- // a pending hook won't be executed twice.
- hook.pending = true;
- }
- } else {
- self.failHook(hook, err);
-
- // stop executing hooks, notify callee of hook err
- return fn(err);
- }
- }
- self.emit(constants.EVENT_HOOK_END, hook);
- delete hook.ctx.currentTest;
- next(++i);
- });
- }
-
- Runner.immediately(function() {
- next(0);
- });
-};
-
-/**
- * Run hook `name` for the given array of `suites`
- * in order, and callback `fn(err, errSuite)`.
- *
- * @private
- * @param {string} name
- * @param {Array} suites
- * @param {Function} fn
- */
-Runner.prototype.hooks = function(name, suites, fn) {
- var self = this;
- var orig = this.suite;
-
- function next(suite) {
- self.suite = suite;
-
- if (!suite) {
- self.suite = orig;
- return fn();
- }
-
- self.hook(name, function(err) {
- if (err) {
- var errSuite = self.suite;
- self.suite = orig;
- return fn(err, errSuite);
- }
-
- next(suites.pop());
- });
- }
-
- next(suites.pop());
-};
-
-/**
- * Run hooks from the top level down.
- *
- * @param {String} name
- * @param {Function} fn
- * @private
- */
-Runner.prototype.hookUp = function(name, fn) {
- var suites = [this.suite].concat(this.parents()).reverse();
- this.hooks(name, suites, fn);
-};
-
-/**
- * Run hooks from the bottom up.
- *
- * @param {String} name
- * @param {Function} fn
- * @private
- */
-Runner.prototype.hookDown = function(name, fn) {
- var suites = [this.suite].concat(this.parents());
- this.hooks(name, suites, fn);
-};
-
-/**
- * Return an array of parent Suites from
- * closest to furthest.
- *
- * @return {Array}
- * @private
- */
-Runner.prototype.parents = function() {
- var suite = this.suite;
- var suites = [];
- while (suite.parent) {
- suite = suite.parent;
- suites.push(suite);
- }
- return suites;
-};
-
-/**
- * Run the current test and callback `fn(err)`.
- *
- * @param {Function} fn
- * @private
- */
-Runner.prototype.runTest = function(fn) {
- var self = this;
- var test = this.test;
-
- if (!test) {
- return;
- }
-
- var suite = this.parents().reverse()[0] || this.suite;
- if (this.forbidOnly && suite.hasOnly()) {
- fn(new Error('`.only` forbidden'));
- return;
- }
- if (this.asyncOnly) {
- test.asyncOnly = true;
- }
- test.on('error', function(err) {
- self.fail(test, err);
- });
- if (this.allowUncaught) {
- test.allowUncaught = true;
- return test.run(fn);
- }
- try {
- test.run(fn);
- } catch (err) {
- fn(err);
- }
-};
-
-/**
- * Run tests in the given `suite` and invoke the callback `fn()` when complete.
- *
- * @private
- * @param {Suite} suite
- * @param {Function} fn
- */
-Runner.prototype.runTests = function(suite, fn) {
- var self = this;
- var tests = suite.tests.slice();
- var test;
-
- function hookErr(_, errSuite, after) {
- // before/after Each hook for errSuite failed:
- var orig = self.suite;
-
- // for failed 'after each' hook start from errSuite parent,
- // otherwise start from errSuite itself
- self.suite = after ? errSuite.parent : errSuite;
-
- if (self.suite) {
- // call hookUp afterEach
- self.hookUp(HOOK_TYPE_AFTER_EACH, function(err2, errSuite2) {
- self.suite = orig;
- // some hooks may fail even now
- if (err2) {
- return hookErr(err2, errSuite2, true);
- }
- // report error suite
- fn(errSuite);
- });
- } else {
- // there is no need calling other 'after each' hooks
- self.suite = orig;
- fn(errSuite);
- }
- }
-
- function next(err, errSuite) {
- // if we bail after first err
- if (self.failures && suite._bail) {
- tests = [];
- }
-
- if (self._abort) {
- return fn();
- }
-
- if (err) {
- return hookErr(err, errSuite, true);
- }
-
- // next test
- test = tests.shift();
-
- // all done
- if (!test) {
- return fn();
- }
-
- // grep
- var match = self._grep.test(test.fullTitle());
- if (self._invert) {
- match = !match;
- }
- if (!match) {
- // Run immediately only if we have defined a grep. When we
- // define a grep — It can cause maximum callstack error if
- // the grep is doing a large recursive loop by neglecting
- // all tests. The run immediately function also comes with
- // a performance cost. So we don't want to run immediately
- // if we run the whole test suite, because running the whole
- // test suite don't do any immediate recursive loops. Thus,
- // allowing a JS runtime to breathe.
- if (self._grep !== self._defaultGrep) {
- Runner.immediately(next);
- } else {
- next();
- }
- return;
- }
-
- if (test.isPending()) {
- if (self.forbidPending) {
- test.isPending = alwaysFalse;
- self.fail(test, new Error('Pending test forbidden'));
- delete test.isPending;
- } else {
- self.emit(constants.EVENT_TEST_PENDING, test);
- }
- self.emit(constants.EVENT_TEST_END, test);
- return next();
- }
-
- // execute test and hook(s)
- self.emit(constants.EVENT_TEST_BEGIN, (self.test = test));
- self.hookDown(HOOK_TYPE_BEFORE_EACH, function(err, errSuite) {
- if (test.isPending()) {
- if (self.forbidPending) {
- test.isPending = alwaysFalse;
- self.fail(test, new Error('Pending test forbidden'));
- delete test.isPending;
- } else {
- self.emit(constants.EVENT_TEST_PENDING, test);
- }
- self.emit(constants.EVENT_TEST_END, test);
- return next();
- }
- if (err) {
- return hookErr(err, errSuite, false);
- }
- self.currentRunnable = self.test;
- self.runTest(function(err) {
- test = self.test;
- if (err) {
- var retry = test.currentRetry();
- if (err instanceof Pending && self.forbidPending) {
- self.fail(test, new Error('Pending test forbidden'));
- } else if (err instanceof Pending) {
- test.pending = true;
- self.emit(constants.EVENT_TEST_PENDING, test);
- } else if (retry < test.retries()) {
- var clonedTest = test.clone();
- clonedTest.currentRetry(retry + 1);
- tests.unshift(clonedTest);
-
- self.emit(constants.EVENT_TEST_RETRY, test, err);
-
- // Early return + hook trigger so that it doesn't
- // increment the count wrong
- return self.hookUp(HOOK_TYPE_AFTER_EACH, next);
- } else {
- self.fail(test, err);
- }
- self.emit(constants.EVENT_TEST_END, test);
-
- if (err instanceof Pending) {
- return next();
- }
-
- return self.hookUp(HOOK_TYPE_AFTER_EACH, next);
- }
-
- test.state = STATE_PASSED;
- self.emit(constants.EVENT_TEST_PASS, test);
- self.emit(constants.EVENT_TEST_END, test);
- self.hookUp(HOOK_TYPE_AFTER_EACH, next);
- });
- });
- }
-
- this.next = next;
- this.hookErr = hookErr;
- next();
-};
-
-function alwaysFalse() {
- return false;
-}
-
-/**
- * Run the given `suite` and invoke the callback `fn()` when complete.
- *
- * @private
- * @param {Suite} suite
- * @param {Function} fn
- */
-Runner.prototype.runSuite = function(suite, fn) {
- var i = 0;
- var self = this;
- var total = this.grepTotal(suite);
- var afterAllHookCalled = false;
-
- debug('run suite %s', suite.fullTitle());
-
- if (!total || (self.failures && suite._bail)) {
- return fn();
- }
-
- this.emit(constants.EVENT_SUITE_BEGIN, (this.suite = suite));
-
- function next(errSuite) {
- if (errSuite) {
- // current suite failed on a hook from errSuite
- if (errSuite === suite) {
- // if errSuite is current suite
- // continue to the next sibling suite
- return done();
- }
- // errSuite is among the parents of current suite
- // stop execution of errSuite and all sub-suites
- return done(errSuite);
- }
-
- if (self._abort) {
- return done();
- }
-
- var curr = suite.suites[i++];
- if (!curr) {
- return done();
- }
-
- // Avoid grep neglecting large number of tests causing a
- // huge recursive loop and thus a maximum call stack error.
- // See comment in `this.runTests()` for more information.
- if (self._grep !== self._defaultGrep) {
- Runner.immediately(function() {
- self.runSuite(curr, next);
- });
- } else {
- self.runSuite(curr, next);
- }
- }
-
- function done(errSuite) {
- self.suite = suite;
- self.nextSuite = next;
-
- if (afterAllHookCalled) {
- fn(errSuite);
- } else {
- // mark that the afterAll block has been called once
- // and so can be skipped if there is an error in it.
- afterAllHookCalled = true;
-
- // remove reference to test
- delete self.test;
-
- self.hook(HOOK_TYPE_AFTER_ALL, function() {
- self.emit(constants.EVENT_SUITE_END, suite);
- fn(errSuite);
- });
- }
- }
-
- this.nextSuite = next;
-
- this.hook(HOOK_TYPE_BEFORE_ALL, function(err) {
- if (err) {
- return done();
- }
- self.runTests(suite, next);
- });
-};
-
-/**
- * Handle uncaught exceptions.
- *
- * @param {Error} err
- * @private
- */
-Runner.prototype.uncaught = function(err) {
- if (err instanceof Pending) {
- return;
- }
- if (err) {
- debug('uncaught exception %O', err);
- } else {
- debug('uncaught undefined/falsy exception');
- err = createInvalidExceptionError(
- 'Caught falsy/undefined exception which would otherwise be uncaught. No stack trace found; try a debugger',
- err
- );
- }
-
- if (!isError(err)) {
- err = thrown2Error(err);
- }
- err.uncaught = true;
-
- var runnable = this.currentRunnable;
-
- if (!runnable) {
- runnable = new Runnable('Uncaught error outside test suite');
- runnable.parent = this.suite;
-
- if (this.started) {
- this.fail(runnable, err);
- } else {
- // Can't recover from this failure
- this.emit(constants.EVENT_RUN_BEGIN);
- this.fail(runnable, err);
- this.emit(constants.EVENT_RUN_END);
- }
-
- return;
- }
-
- runnable.clearTimeout();
-
- // Ignore errors if already failed or pending
- // See #3226
- if (runnable.isFailed() || runnable.isPending()) {
- return;
- }
- // we cannot recover gracefully if a Runnable has already passed
- // then fails asynchronously
- var alreadyPassed = runnable.isPassed();
- // this will change the state to "failed" regardless of the current value
- this.fail(runnable, err);
- if (!alreadyPassed) {
- // recover from test
- if (runnable.type === constants.EVENT_TEST_BEGIN) {
- this.emit(constants.EVENT_TEST_END, runnable);
- this.hookUp(HOOK_TYPE_AFTER_EACH, this.next);
- return;
- }
- debug(runnable);
-
- // recover from hooks
- var errSuite = this.suite;
-
- // XXX how about a less awful way to determine this?
- // if hook failure is in afterEach block
- if (runnable.fullTitle().indexOf('after each') > -1) {
- return this.hookErr(err, errSuite, true);
- }
- // if hook failure is in beforeEach block
- if (runnable.fullTitle().indexOf('before each') > -1) {
- return this.hookErr(err, errSuite, false);
- }
- // if hook failure is in after or before blocks
- return this.nextSuite(errSuite);
- }
-
- // bail
- this.emit(constants.EVENT_RUN_END);
-};
-
-/**
- * Run the root suite and invoke `fn(failures)`
- * on completion.
- *
- * @public
- * @memberof Runner
- * @param {Function} fn
- * @return {Runner} Runner instance.
- */
-Runner.prototype.run = function(fn) {
- var self = this;
- var rootSuite = this.suite;
-
- fn = fn || function() {};
-
- function uncaught(err) {
- self.uncaught(err);
- }
-
- function start() {
- // If there is an `only` filter
- if (rootSuite.hasOnly()) {
- rootSuite.filterOnly();
- }
- self.started = true;
- if (self._delay) {
- self.emit(constants.EVENT_DELAY_END);
- }
- self.emit(constants.EVENT_RUN_BEGIN);
-
- self.runSuite(rootSuite, function() {
- debug('finished running');
- self.emit(constants.EVENT_RUN_END);
- });
- }
-
- debug(constants.EVENT_RUN_BEGIN);
-
- // references cleanup to avoid memory leaks
- this.on(constants.EVENT_SUITE_END, function(suite) {
- suite.cleanReferences();
- });
-
- // callback
- this.on(constants.EVENT_RUN_END, function() {
- debug(constants.EVENT_RUN_END);
- process.removeListener('uncaughtException', uncaught);
- fn(self.failures);
- });
-
- // uncaught exception
- process.on('uncaughtException', uncaught);
-
- if (this._delay) {
- // for reporters, I guess.
- // might be nice to debounce some dots while we wait.
- this.emit(constants.EVENT_DELAY_BEGIN, rootSuite);
- rootSuite.once(EVENT_ROOT_SUITE_RUN, start);
- } else {
- start();
- }
-
- return this;
-};
-
-/**
- * Cleanly abort execution.
- *
- * @memberof Runner
- * @public
- * @return {Runner} Runner instance.
- */
-Runner.prototype.abort = function() {
- debug('aborting');
- this._abort = true;
-
- return this;
-};
-
-/**
- * Filter leaks with the given globals flagged as `ok`.
- *
- * @private
- * @param {Array} ok
- * @param {Array} globals
- * @return {Array}
- */
-function filterLeaks(ok, globals) {
- return globals.filter(function(key) {
- // Firefox and Chrome exposes iframes as index inside the window object
- if (/^\d+/.test(key)) {
- return false;
- }
-
- // in firefox
- // if runner runs in an iframe, this iframe's window.getInterface method
- // not init at first it is assigned in some seconds
- if (global.navigator && /^getInterface/.test(key)) {
- return false;
- }
-
- // an iframe could be approached by window[iframeIndex]
- // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak
- if (global.navigator && /^\d+/.test(key)) {
- return false;
- }
-
- // Opera and IE expose global variables for HTML element IDs (issue #243)
- if (/^mocha-/.test(key)) {
- return false;
- }
-
- var matched = ok.filter(function(ok) {
- if (~ok.indexOf('*')) {
- return key.indexOf(ok.split('*')[0]) === 0;
- }
- return key === ok;
- });
- return !matched.length && (!global.navigator || key !== 'onerror');
- });
-}
-
-/**
- * Check if argument is an instance of Error object or a duck-typed equivalent.
- *
- * @private
- * @param {Object} err - object to check
- * @param {string} err.message - error message
- * @returns {boolean}
- */
-function isError(err) {
- return err instanceof Error || (err && typeof err.message === 'string');
-}
-
-/**
- *
- * Converts thrown non-extensible type into proper Error.
- *
- * @private
- * @param {*} thrown - Non-extensible type thrown by code
- * @return {Error}
- */
-function thrown2Error(err) {
- return new Error(
- 'the ' + type(err) + ' ' + stringify(err) + ' was thrown, throw an Error :)'
- );
-}
-
-/**
- * Array of globals dependent on the environment.
- *
- * @return {Array}
- * @deprecated
- * @todo remove; long since unsupported
- * @private
- */
-function extraGlobals() {
- if (typeof process === 'object' && typeof process.version === 'string') {
- var parts = process.version.split('.');
- var nodeVersion = parts.reduce(function(a, v) {
- return (a << 8) | v;
- });
-
- // 'errno' was renamed to process._errno in v0.9.11.
- if (nodeVersion < 0x00090b) {
- return ['errno'];
- }
- }
-
- return [];
-}
-
-Runner.constants = constants;
-
-/**
- * Node.js' `EventEmitter`
- * @external EventEmitter
- * @see {@link https://nodejs.org/api/events.html#events_class_eventemitter}
- */
-
-}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"./errors":6,"./pending":16,"./runnable":33,"./suite":36,"./utils":38,"_process":69,"debug":45,"events":50,"util":89}],35:[function(require,module,exports){
-(function (global){
-'use strict';
-
-/**
- * Provides a factory function for a {@link StatsCollector} object.
- * @module
- */
-
-var constants = require('./runner').constants;
-var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
-var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
-var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
-var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
-var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
-var EVENT_RUN_END = constants.EVENT_RUN_END;
-var EVENT_TEST_END = constants.EVENT_TEST_END;
-
-/**
- * Test statistics collector.
- *
- * @public
- * @typedef {Object} StatsCollector
- * @property {number} suites - integer count of suites run.
- * @property {number} tests - integer count of tests run.
- * @property {number} passes - integer count of passing tests.
- * @property {number} pending - integer count of pending tests.
- * @property {number} failures - integer count of failed tests.
- * @property {Date} start - time when testing began.
- * @property {Date} end - time when testing concluded.
- * @property {number} duration - number of msecs that testing took.
- */
-
-var Date = global.Date;
-
-/**
- * Provides stats such as test duration, number of tests passed / failed etc., by listening for events emitted by `runner`.
- *
- * @private
- * @param {Runner} runner - Runner instance
- * @throws {TypeError} If falsy `runner`
- */
-function createStatsCollector(runner) {
- /**
- * @type StatsCollector
- */
- var stats = {
- suites: 0,
- tests: 0,
- passes: 0,
- pending: 0,
- failures: 0
- };
-
- if (!runner) {
- throw new TypeError('Missing runner argument');
- }
-
- runner.stats = stats;
-
- runner.once(EVENT_RUN_BEGIN, function() {
- stats.start = new Date();
- });
- runner.on(EVENT_SUITE_BEGIN, function(suite) {
- suite.root || stats.suites++;
- });
- runner.on(EVENT_TEST_PASS, function() {
- stats.passes++;
- });
- runner.on(EVENT_TEST_FAIL, function() {
- stats.failures++;
- });
- runner.on(EVENT_TEST_PENDING, function() {
- stats.pending++;
- });
- runner.on(EVENT_TEST_END, function() {
- stats.tests++;
- });
- runner.once(EVENT_RUN_END, function() {
- stats.end = new Date();
- stats.duration = stats.end - stats.start;
- });
-}
-
-module.exports = createStatsCollector;
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"./runner":34}],36:[function(require,module,exports){
-'use strict';
-
-/**
- * Module dependencies.
- */
-var EventEmitter = require('events').EventEmitter;
-var Hook = require('./hook');
-var utils = require('./utils');
-var inherits = utils.inherits;
-var debug = require('debug')('mocha:suite');
-var milliseconds = require('ms');
-var errors = require('./errors');
-var createInvalidArgumentTypeError = errors.createInvalidArgumentTypeError;
-
-/**
- * Expose `Suite`.
- */
-
-exports = module.exports = Suite;
-
-/**
- * Create a new `Suite` with the given `title` and parent `Suite`.
- *
- * @public
- * @param {Suite} parent - Parent suite (required!)
- * @param {string} title - Title
- * @return {Suite}
- */
-Suite.create = function(parent, title) {
- var suite = new Suite(title, parent.ctx);
- suite.parent = parent;
- title = suite.fullTitle();
- parent.addSuite(suite);
- return suite;
-};
-
-/**
- * Constructs a new `Suite` instance with the given `title`, `ctx`, and `isRoot`.
- *
- * @public
- * @class
- * @extends EventEmitter
- * @see {@link https://nodejs.org/api/events.html#events_class_eventemitter|EventEmitter}
- * @param {string} title - Suite title.
- * @param {Context} parentContext - Parent context instance.
- * @param {boolean} [isRoot=false] - Whether this is the root suite.
- */
-function Suite(title, parentContext, isRoot) {
- if (!utils.isString(title)) {
- throw createInvalidArgumentTypeError(
- 'Suite argument "title" must be a string. Received type "' +
- typeof title +
- '"',
- 'title',
- 'string'
- );
- }
- this.title = title;
- function Context() {}
- Context.prototype = parentContext;
- this.ctx = new Context();
- this.suites = [];
- this.tests = [];
- this.pending = false;
- this._beforeEach = [];
- this._beforeAll = [];
- this._afterEach = [];
- this._afterAll = [];
- this.root = isRoot === true;
- this._timeout = 2000;
- this._enableTimeouts = true;
- this._slow = 75;
- this._bail = false;
- this._retries = -1;
- this._onlyTests = [];
- this._onlySuites = [];
- this.delayed = false;
-
- this.on('newListener', function(event) {
- if (deprecatedEvents[event]) {
- utils.deprecate(
- 'Event "' +
- event +
- '" is deprecated. Please let the Mocha team know about your use case: https://git.io/v6Lwm'
- );
- }
- });
-}
-
-/**
- * Inherit from `EventEmitter.prototype`.
- */
-inherits(Suite, EventEmitter);
-
-/**
- * Return a clone of this `Suite`.
- *
- * @private
- * @return {Suite}
- */
-Suite.prototype.clone = function() {
- var suite = new Suite(this.title);
- debug('clone');
- suite.ctx = this.ctx;
- suite.root = this.root;
- suite.timeout(this.timeout());
- suite.retries(this.retries());
- suite.enableTimeouts(this.enableTimeouts());
- suite.slow(this.slow());
- suite.bail(this.bail());
- return suite;
-};
-
-/**
- * Set or get timeout `ms` or short-hand such as "2s".
- *
- * @private
- * @todo Do not attempt to set value if `ms` is undefined
- * @param {number|string} ms
- * @return {Suite|number} for chaining
- */
-Suite.prototype.timeout = function(ms) {
- if (!arguments.length) {
- return this._timeout;
- }
- if (ms.toString() === '0') {
- this._enableTimeouts = false;
- }
- if (typeof ms === 'string') {
- ms = milliseconds(ms);
- }
- debug('timeout %d', ms);
- this._timeout = parseInt(ms, 10);
- return this;
-};
-
-/**
- * Set or get number of times to retry a failed test.
- *
- * @private
- * @param {number|string} n
- * @return {Suite|number} for chaining
- */
-Suite.prototype.retries = function(n) {
- if (!arguments.length) {
- return this._retries;
- }
- debug('retries %d', n);
- this._retries = parseInt(n, 10) || 0;
- return this;
-};
-
-/**
- * Set or get timeout to `enabled`.
- *
- * @private
- * @param {boolean} enabled
- * @return {Suite|boolean} self or enabled
- */
-Suite.prototype.enableTimeouts = function(enabled) {
- if (!arguments.length) {
- return this._enableTimeouts;
- }
- debug('enableTimeouts %s', enabled);
- this._enableTimeouts = enabled;
- return this;
-};
-
-/**
- * Set or get slow `ms` or short-hand such as "2s".
- *
- * @private
- * @param {number|string} ms
- * @return {Suite|number} for chaining
- */
-Suite.prototype.slow = function(ms) {
- if (!arguments.length) {
- return this._slow;
- }
- if (typeof ms === 'string') {
- ms = milliseconds(ms);
- }
- debug('slow %d', ms);
- this._slow = ms;
- return this;
-};
-
-/**
- * Set or get whether to bail after first error.
- *
- * @private
- * @param {boolean} bail
- * @return {Suite|number} for chaining
- */
-Suite.prototype.bail = function(bail) {
- if (!arguments.length) {
- return this._bail;
- }
- debug('bail %s', bail);
- this._bail = bail;
- return this;
-};
-
-/**
- * Check if this suite or its parent suite is marked as pending.
- *
- * @private
- */
-Suite.prototype.isPending = function() {
- return this.pending || (this.parent && this.parent.isPending());
-};
-
-/**
- * Generic hook-creator.
- * @private
- * @param {string} title - Title of hook
- * @param {Function} fn - Hook callback
- * @returns {Hook} A new hook
- */
-Suite.prototype._createHook = function(title, fn) {
- var hook = new Hook(title, fn);
- hook.parent = this;
- hook.timeout(this.timeout());
- hook.retries(this.retries());
- hook.enableTimeouts(this.enableTimeouts());
- hook.slow(this.slow());
- hook.ctx = this.ctx;
- hook.file = this.file;
- return hook;
-};
-
-/**
- * Run `fn(test[, done])` before running tests.
- *
- * @private
- * @param {string} title
- * @param {Function} fn
- * @return {Suite} for chaining
- */
-Suite.prototype.beforeAll = function(title, fn) {
- if (this.isPending()) {
- return this;
- }
- if (typeof title === 'function') {
- fn = title;
- title = fn.name;
- }
- title = '"before all" hook' + (title ? ': ' + title : '');
-
- var hook = this._createHook(title, fn);
- this._beforeAll.push(hook);
- this.emit(constants.EVENT_SUITE_ADD_HOOK_BEFORE_ALL, hook);
- return this;
-};
-
-/**
- * Run `fn(test[, done])` after running tests.
- *
- * @private
- * @param {string} title
- * @param {Function} fn
- * @return {Suite} for chaining
- */
-Suite.prototype.afterAll = function(title, fn) {
- if (this.isPending()) {
- return this;
- }
- if (typeof title === 'function') {
- fn = title;
- title = fn.name;
- }
- title = '"after all" hook' + (title ? ': ' + title : '');
-
- var hook = this._createHook(title, fn);
- this._afterAll.push(hook);
- this.emit(constants.EVENT_SUITE_ADD_HOOK_AFTER_ALL, hook);
- return this;
-};
-
-/**
- * Run `fn(test[, done])` before each test case.
- *
- * @private
- * @param {string} title
- * @param {Function} fn
- * @return {Suite} for chaining
- */
-Suite.prototype.beforeEach = function(title, fn) {
- if (this.isPending()) {
- return this;
- }
- if (typeof title === 'function') {
- fn = title;
- title = fn.name;
- }
- title = '"before each" hook' + (title ? ': ' + title : '');
-
- var hook = this._createHook(title, fn);
- this._beforeEach.push(hook);
- this.emit(constants.EVENT_SUITE_ADD_HOOK_BEFORE_EACH, hook);
- return this;
-};
-
-/**
- * Run `fn(test[, done])` after each test case.
- *
- * @private
- * @param {string} title
- * @param {Function} fn
- * @return {Suite} for chaining
- */
-Suite.prototype.afterEach = function(title, fn) {
- if (this.isPending()) {
- return this;
- }
- if (typeof title === 'function') {
- fn = title;
- title = fn.name;
- }
- title = '"after each" hook' + (title ? ': ' + title : '');
-
- var hook = this._createHook(title, fn);
- this._afterEach.push(hook);
- this.emit(constants.EVENT_SUITE_ADD_HOOK_AFTER_EACH, hook);
- return this;
-};
-
-/**
- * Add a test `suite`.
- *
- * @private
- * @param {Suite} suite
- * @return {Suite} for chaining
- */
-Suite.prototype.addSuite = function(suite) {
- suite.parent = this;
- suite.root = false;
- suite.timeout(this.timeout());
- suite.retries(this.retries());
- suite.enableTimeouts(this.enableTimeouts());
- suite.slow(this.slow());
- suite.bail(this.bail());
- this.suites.push(suite);
- this.emit(constants.EVENT_SUITE_ADD_SUITE, suite);
- return this;
-};
-
-/**
- * Add a `test` to this suite.
- *
- * @private
- * @param {Test} test
- * @return {Suite} for chaining
- */
-Suite.prototype.addTest = function(test) {
- test.parent = this;
- test.timeout(this.timeout());
- test.retries(this.retries());
- test.enableTimeouts(this.enableTimeouts());
- test.slow(this.slow());
- test.ctx = this.ctx;
- this.tests.push(test);
- this.emit(constants.EVENT_SUITE_ADD_TEST, test);
- return this;
-};
-
-/**
- * Return the full title generated by recursively concatenating the parent's
- * full title.
- *
- * @memberof Suite
- * @public
- * @return {string}
- */
-Suite.prototype.fullTitle = function() {
- return this.titlePath().join(' ');
-};
-
-/**
- * Return the title path generated by recursively concatenating the parent's
- * title path.
- *
- * @memberof Suite
- * @public
- * @return {string}
- */
-Suite.prototype.titlePath = function() {
- var result = [];
- if (this.parent) {
- result = result.concat(this.parent.titlePath());
- }
- if (!this.root) {
- result.push(this.title);
- }
- return result;
-};
-
-/**
- * Return the total number of tests.
- *
- * @memberof Suite
- * @public
- * @return {number}
- */
-Suite.prototype.total = function() {
- return (
- this.suites.reduce(function(sum, suite) {
- return sum + suite.total();
- }, 0) + this.tests.length
- );
-};
-
-/**
- * Iterates through each suite recursively to find all tests. Applies a
- * function in the format `fn(test)`.
- *
- * @private
- * @param {Function} fn
- * @return {Suite}
- */
-Suite.prototype.eachTest = function(fn) {
- this.tests.forEach(fn);
- this.suites.forEach(function(suite) {
- suite.eachTest(fn);
- });
- return this;
-};
-
-/**
- * This will run the root suite if we happen to be running in delayed mode.
- * @private
- */
-Suite.prototype.run = function run() {
- if (this.root) {
- this.emit(constants.EVENT_ROOT_SUITE_RUN);
- }
-};
-
-/**
- * Determines whether a suite has an `only` test or suite as a descendant.
- *
- * @private
- * @returns {Boolean}
- */
-Suite.prototype.hasOnly = function hasOnly() {
- return (
- this._onlyTests.length > 0 ||
- this._onlySuites.length > 0 ||
- this.suites.some(function(suite) {
- return suite.hasOnly();
- })
- );
-};
-
-/**
- * Filter suites based on `isOnly` logic.
- *
- * @private
- * @returns {Boolean}
- */
-Suite.prototype.filterOnly = function filterOnly() {
- if (this._onlyTests.length) {
- // If the suite contains `only` tests, run those and ignore any nested suites.
- this.tests = this._onlyTests;
- this.suites = [];
- } else {
- // Otherwise, do not run any of the tests in this suite.
- this.tests = [];
- this._onlySuites.forEach(function(onlySuite) {
- // If there are other `only` tests/suites nested in the current `only` suite, then filter that `only` suite.
- // Otherwise, all of the tests on this `only` suite should be run, so don't filter it.
- if (onlySuite.hasOnly()) {
- onlySuite.filterOnly();
- }
- });
- // Run the `only` suites, as well as any other suites that have `only` tests/suites as descendants.
- var onlySuites = this._onlySuites;
- this.suites = this.suites.filter(function(childSuite) {
- return onlySuites.indexOf(childSuite) !== -1 || childSuite.filterOnly();
- });
- }
- // Keep the suite only if there is something to run
- return this.tests.length > 0 || this.suites.length > 0;
-};
-
-/**
- * Adds a suite to the list of subsuites marked `only`.
- *
- * @private
- * @param {Suite} suite
- */
-Suite.prototype.appendOnlySuite = function(suite) {
- this._onlySuites.push(suite);
-};
-
-/**
- * Adds a test to the list of tests marked `only`.
- *
- * @private
- * @param {Test} test
- */
-Suite.prototype.appendOnlyTest = function(test) {
- this._onlyTests.push(test);
-};
-
-/**
- * Returns the array of hooks by hook name; see `HOOK_TYPE_*` constants.
- * @private
- */
-Suite.prototype.getHooks = function getHooks(name) {
- return this['_' + name];
-};
-
-/**
- * Cleans up the references to all the deferred functions
- * (before/after/beforeEach/afterEach) and tests of a Suite.
- * These must be deleted otherwise a memory leak can happen,
- * as those functions may reference variables from closures,
- * thus those variables can never be garbage collected as long
- * as the deferred functions exist.
- *
- * @private
- */
-Suite.prototype.cleanReferences = function cleanReferences() {
- function cleanArrReferences(arr) {
- for (var i = 0; i < arr.length; i++) {
- delete arr[i].fn;
- }
- }
-
- if (Array.isArray(this._beforeAll)) {
- cleanArrReferences(this._beforeAll);
- }
-
- if (Array.isArray(this._beforeEach)) {
- cleanArrReferences(this._beforeEach);
- }
-
- if (Array.isArray(this._afterAll)) {
- cleanArrReferences(this._afterAll);
- }
-
- if (Array.isArray(this._afterEach)) {
- cleanArrReferences(this._afterEach);
- }
-
- for (var i = 0; i < this.tests.length; i++) {
- delete this.tests[i].fn;
- }
-};
-
-var constants = utils.defineConstants(
- /**
- * {@link Suite}-related constants.
- * @public
- * @memberof Suite
- * @alias constants
- * @readonly
- * @static
- * @enum {string}
- */
- {
- /**
- * Event emitted after a test file has been loaded Not emitted in browser.
- */
- EVENT_FILE_POST_REQUIRE: 'post-require',
- /**
- * Event emitted before a test file has been loaded. In browser, this is emitted once an interface has been selected.
- */
- EVENT_FILE_PRE_REQUIRE: 'pre-require',
- /**
- * Event emitted immediately after a test file has been loaded. Not emitted in browser.
- */
- EVENT_FILE_REQUIRE: 'require',
- /**
- * Event emitted when `global.run()` is called (use with `delay` option)
- */
- EVENT_ROOT_SUITE_RUN: 'run',
-
- /**
- * Namespace for collection of a `Suite`'s "after all" hooks
- */
- HOOK_TYPE_AFTER_ALL: 'afterAll',
- /**
- * Namespace for collection of a `Suite`'s "after each" hooks
- */
- HOOK_TYPE_AFTER_EACH: 'afterEach',
- /**
- * Namespace for collection of a `Suite`'s "before all" hooks
- */
- HOOK_TYPE_BEFORE_ALL: 'beforeAll',
- /**
- * Namespace for collection of a `Suite`'s "before all" hooks
- */
- HOOK_TYPE_BEFORE_EACH: 'beforeEach',
-
- // the following events are all deprecated
-
- /**
- * Emitted after an "after all" `Hook` has been added to a `Suite`. Deprecated
- */
- EVENT_SUITE_ADD_HOOK_AFTER_ALL: 'afterAll',
- /**
- * Emitted after an "after each" `Hook` has been added to a `Suite` Deprecated
- */
- EVENT_SUITE_ADD_HOOK_AFTER_EACH: 'afterEach',
- /**
- * Emitted after an "before all" `Hook` has been added to a `Suite` Deprecated
- */
- EVENT_SUITE_ADD_HOOK_BEFORE_ALL: 'beforeAll',
- /**
- * Emitted after an "before each" `Hook` has been added to a `Suite` Deprecated
- */
- EVENT_SUITE_ADD_HOOK_BEFORE_EACH: 'beforeEach',
- /**
- * Emitted after a child `Suite` has been added to a `Suite`. Deprecated
- */
- EVENT_SUITE_ADD_SUITE: 'suite',
- /**
- * Emitted after a `Test` has been added to a `Suite`. Deprecated
- */
- EVENT_SUITE_ADD_TEST: 'test'
- }
-);
-
-/**
- * @summary There are no known use cases for these events.
- * @desc This is a `Set`-like object having all keys being the constant's string value and the value being `true`.
- * @todo Remove eventually
- * @type {Object}
- * @ignore
- */
-var deprecatedEvents = Object.keys(constants)
- .filter(function(constant) {
- return constant.substring(0, 15) === 'EVENT_SUITE_ADD';
- })
- .reduce(function(acc, constant) {
- acc[constants[constant]] = true;
- return acc;
- }, utils.createMap());
-
-Suite.constants = constants;
-
-},{"./errors":6,"./hook":7,"./utils":38,"debug":45,"events":50,"ms":60}],37:[function(require,module,exports){
-'use strict';
-var Runnable = require('./runnable');
-var utils = require('./utils');
-var errors = require('./errors');
-var createInvalidArgumentTypeError = errors.createInvalidArgumentTypeError;
-var isString = utils.isString;
-
-module.exports = Test;
-
-/**
- * Initialize a new `Test` with the given `title` and callback `fn`.
- *
- * @public
- * @class
- * @extends Runnable
- * @param {String} title - Test title (required)
- * @param {Function} [fn] - Test callback. If omitted, the Test is considered "pending"
- */
-function Test(title, fn) {
- if (!isString(title)) {
- throw createInvalidArgumentTypeError(
- 'Test argument "title" should be a string. Received type "' +
- typeof title +
- '"',
- 'title',
- 'string'
- );
- }
- Runnable.call(this, title, fn);
- this.pending = !fn;
- this.type = 'test';
-}
-
-/**
- * Inherit from `Runnable.prototype`.
- */
-utils.inherits(Test, Runnable);
-
-Test.prototype.clone = function() {
- var test = new Test(this.title, this.fn);
- test.timeout(this.timeout());
- test.slow(this.slow());
- test.enableTimeouts(this.enableTimeouts());
- test.retries(this.retries());
- test.currentRetry(this.currentRetry());
- test.globals(this.globals());
- test.parent = this.parent;
- test.file = this.file;
- test.ctx = this.ctx;
- return test;
-};
-
-},{"./errors":6,"./runnable":33,"./utils":38}],38:[function(require,module,exports){
-(function (process,Buffer){
-'use strict';
-
-/**
- * Various utility functions used throughout Mocha's codebase.
- * @module utils
- */
-
-/**
- * Module dependencies.
- */
-
-var fs = require('fs');
-var path = require('path');
-var util = require('util');
-var glob = require('glob');
-var he = require('he');
-var errors = require('./errors');
-var createNoFilesMatchPatternError = errors.createNoFilesMatchPatternError;
-var createMissingArgumentError = errors.createMissingArgumentError;
-
-var assign = (exports.assign = require('object.assign').getPolyfill());
-
-/**
- * Inherit the prototype methods from one constructor into another.
- *
- * @param {function} ctor - Constructor function which needs to inherit the
- * prototype.
- * @param {function} superCtor - Constructor function to inherit prototype from.
- * @throws {TypeError} if either constructor is null, or if super constructor
- * lacks a prototype.
- */
-exports.inherits = util.inherits;
-
-/**
- * Escape special characters in the given string of html.
- *
- * @private
- * @param {string} html
- * @return {string}
- */
-exports.escape = function(html) {
- return he.encode(String(html), {useNamedReferences: false});
-};
-
-/**
- * Test if the given obj is type of string.
- *
- * @private
- * @param {Object} obj
- * @return {boolean}
- */
-exports.isString = function(obj) {
- return typeof obj === 'string';
-};
-
-/**
- * Watch the given `files` for changes
- * and invoke `fn(file)` on modification.
- *
- * @private
- * @param {Array} files
- * @param {Function} fn
- */
-exports.watch = function(files, fn) {
- var options = {interval: 100};
- var debug = require('debug')('mocha:watch');
- files.forEach(function(file) {
- debug('file %s', file);
- fs.watchFile(file, options, function(curr, prev) {
- if (prev.mtime < curr.mtime) {
- fn(file);
- }
- });
- });
-};
-
-/**
- * Predicate to screen `pathname` for further consideration.
- *
- * @description
- * Returns false
for pathname referencing:
- *
- * 'npm' package installation directory
- * 'git' version control directory
- *
- *
- * @private
- * @param {string} pathname - File or directory name to screen
- * @return {boolean} whether pathname should be further considered
- * @example
- * ['node_modules', 'test.js'].filter(considerFurther); // => ['test.js']
- */
-function considerFurther(pathname) {
- var ignore = ['node_modules', '.git'];
-
- return !~ignore.indexOf(pathname);
-}
-
-/**
- * Lookup files in the given `dir`.
- *
- * @description
- * Filenames are returned in _traversal_ order by the OS/filesystem.
- * **Make no assumption that the names will be sorted in any fashion.**
- *
- * @private
- * @param {string} dir
- * @param {string[]} [exts=['js']]
- * @param {Array} [ret=[]]
- * @return {Array}
- */
-exports.files = function(dir, exts, ret) {
- ret = ret || [];
- exts = exts || ['js'];
-
- fs.readdirSync(dir)
- .filter(considerFurther)
- .forEach(function(dirent) {
- var pathname = path.join(dir, dirent);
- if (fs.lstatSync(pathname).isDirectory()) {
- exports.files(pathname, exts, ret);
- } else if (hasMatchingExtname(pathname, exts)) {
- ret.push(pathname);
- }
- });
-
- return ret;
-};
-
-/**
- * Compute a slug from the given `str`.
- *
- * @private
- * @param {string} str
- * @return {string}
- */
-exports.slug = function(str) {
- return str
- .toLowerCase()
- .replace(/ +/g, '-')
- .replace(/[^-\w]/g, '');
-};
-
-/**
- * Strip the function definition from `str`, and re-indent for pre whitespace.
- *
- * @param {string} str
- * @return {string}
- */
-exports.clean = function(str) {
- str = str
- .replace(/\r\n?|[\n\u2028\u2029]/g, '\n')
- .replace(/^\uFEFF/, '')
- // (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content
- .replace(
- /^function(?:\s*|\s+[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\s*\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\s*\}|((?:.|\n)*))$/,
- '$1$2$3'
- );
-
- var spaces = str.match(/^\n?( *)/)[1].length;
- var tabs = str.match(/^\n?(\t*)/)[1].length;
- var re = new RegExp(
- '^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs || spaces) + '}',
- 'gm'
- );
-
- str = str.replace(re, '');
-
- return str.trim();
-};
-
-/**
- * Parse the given `qs`.
- *
- * @private
- * @param {string} qs
- * @return {Object}
- */
-exports.parseQuery = function(qs) {
- return qs
- .replace('?', '')
- .split('&')
- .reduce(function(obj, pair) {
- var i = pair.indexOf('=');
- var key = pair.slice(0, i);
- var val = pair.slice(++i);
-
- // Due to how the URLSearchParams API treats spaces
- obj[key] = decodeURIComponent(val.replace(/\+/g, '%20'));
-
- return obj;
- }, {});
-};
-
-/**
- * Highlight the given string of `js`.
- *
- * @private
- * @param {string} js
- * @return {string}
- */
-function highlight(js) {
- return js
- .replace(//g, '>')
- .replace(/\/\/(.*)/gm, '')
- .replace(/('.*?')/gm, '$1 ')
- .replace(/(\d+\.\d+)/gm, '$1 ')
- .replace(/(\d+)/gm, '$1 ')
- .replace(
- /\bnew[ \t]+(\w+)/gm,
- 'new $1 '
- )
- .replace(
- /\b(function|new|throw|return|var|if|else)\b/gm,
- '$1 '
- );
-}
-
-/**
- * Highlight the contents of tag `name`.
- *
- * @private
- * @param {string} name
- */
-exports.highlightTags = function(name) {
- var code = document.getElementById('mocha').getElementsByTagName(name);
- for (var i = 0, len = code.length; i < len; ++i) {
- code[i].innerHTML = highlight(code[i].innerHTML);
- }
-};
-
-/**
- * If a value could have properties, and has none, this function is called,
- * which returns a string representation of the empty value.
- *
- * Functions w/ no properties return `'[Function]'`
- * Arrays w/ length === 0 return `'[]'`
- * Objects w/ no properties return `'{}'`
- * All else: return result of `value.toString()`
- *
- * @private
- * @param {*} value The value to inspect.
- * @param {string} typeHint The type of the value
- * @returns {string}
- */
-function emptyRepresentation(value, typeHint) {
- switch (typeHint) {
- case 'function':
- return '[Function]';
- case 'object':
- return '{}';
- case 'array':
- return '[]';
- default:
- return value.toString();
- }
-}
-
-/**
- * Takes some variable and asks `Object.prototype.toString()` what it thinks it
- * is.
- *
- * @private
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
- * @param {*} value The value to test.
- * @returns {string} Computed type
- * @example
- * type({}) // 'object'
- * type([]) // 'array'
- * type(1) // 'number'
- * type(false) // 'boolean'
- * type(Infinity) // 'number'
- * type(null) // 'null'
- * type(new Date()) // 'date'
- * type(/foo/) // 'regexp'
- * type('type') // 'string'
- * type(global) // 'global'
- * type(new String('foo') // 'object'
- */
-var type = (exports.type = function type(value) {
- if (value === undefined) {
- return 'undefined';
- } else if (value === null) {
- return 'null';
- } else if (Buffer.isBuffer(value)) {
- return 'buffer';
- }
- return Object.prototype.toString
- .call(value)
- .replace(/^\[.+\s(.+?)]$/, '$1')
- .toLowerCase();
-});
-
-/**
- * Stringify `value`. Different behavior depending on type of value:
- *
- * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively.
- * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes.
- * - If `value` is an *empty* object, function, or array, return result of function
- * {@link emptyRepresentation}.
- * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of
- * JSON.stringify().
- *
- * @private
- * @see exports.type
- * @param {*} value
- * @return {string}
- */
-exports.stringify = function(value) {
- var typeHint = type(value);
-
- if (!~['object', 'array', 'function'].indexOf(typeHint)) {
- if (typeHint === 'buffer') {
- var json = Buffer.prototype.toJSON.call(value);
- // Based on the toJSON result
- return jsonStringify(
- json.data && json.type ? json.data : json,
- 2
- ).replace(/,(\n|$)/g, '$1');
- }
-
- // IE7/IE8 has a bizarre String constructor; needs to be coerced
- // into an array and back to obj.
- if (typeHint === 'string' && typeof value === 'object') {
- value = value.split('').reduce(function(acc, char, idx) {
- acc[idx] = char;
- return acc;
- }, {});
- typeHint = 'object';
- } else {
- return jsonStringify(value);
- }
- }
-
- for (var prop in value) {
- if (Object.prototype.hasOwnProperty.call(value, prop)) {
- return jsonStringify(
- exports.canonicalize(value, null, typeHint),
- 2
- ).replace(/,(\n|$)/g, '$1');
- }
- }
-
- return emptyRepresentation(value, typeHint);
-};
-
-/**
- * like JSON.stringify but more sense.
- *
- * @private
- * @param {Object} object
- * @param {number=} spaces
- * @param {number=} depth
- * @returns {*}
- */
-function jsonStringify(object, spaces, depth) {
- if (typeof spaces === 'undefined') {
- // primitive types
- return _stringify(object);
- }
-
- depth = depth || 1;
- var space = spaces * depth;
- var str = Array.isArray(object) ? '[' : '{';
- var end = Array.isArray(object) ? ']' : '}';
- var length =
- typeof object.length === 'number'
- ? object.length
- : Object.keys(object).length;
- // `.repeat()` polyfill
- function repeat(s, n) {
- return new Array(n).join(s);
- }
-
- function _stringify(val) {
- switch (type(val)) {
- case 'null':
- case 'undefined':
- val = '[' + val + ']';
- break;
- case 'array':
- case 'object':
- val = jsonStringify(val, spaces, depth + 1);
- break;
- case 'boolean':
- case 'regexp':
- case 'symbol':
- case 'number':
- val =
- val === 0 && 1 / val === -Infinity // `-0`
- ? '-0'
- : val.toString();
- break;
- case 'date':
- var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString();
- val = '[Date: ' + sDate + ']';
- break;
- case 'buffer':
- var json = val.toJSON();
- // Based on the toJSON result
- json = json.data && json.type ? json.data : json;
- val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']';
- break;
- default:
- val =
- val === '[Function]' || val === '[Circular]'
- ? val
- : JSON.stringify(val); // string
- }
- return val;
- }
-
- for (var i in object) {
- if (!Object.prototype.hasOwnProperty.call(object, i)) {
- continue; // not my business
- }
- --length;
- str +=
- '\n ' +
- repeat(' ', space) +
- (Array.isArray(object) ? '' : '"' + i + '": ') + // key
- _stringify(object[i]) + // value
- (length ? ',' : ''); // comma
- }
-
- return (
- str +
- // [], {}
- (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end)
- );
-}
-
-/**
- * Return a new Thing that has the keys in sorted order. Recursive.
- *
- * If the Thing...
- * - has already been seen, return string `'[Circular]'`
- * - is `undefined`, return string `'[undefined]'`
- * - is `null`, return value `null`
- * - is some other primitive, return the value
- * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method
- * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again.
- * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()`
- *
- * @private
- * @see {@link exports.stringify}
- * @param {*} value Thing to inspect. May or may not have properties.
- * @param {Array} [stack=[]] Stack of seen values
- * @param {string} [typeHint] Type hint
- * @return {(Object|Array|Function|string|undefined)}
- */
-exports.canonicalize = function canonicalize(value, stack, typeHint) {
- var canonicalizedObj;
- /* eslint-disable no-unused-vars */
- var prop;
- /* eslint-enable no-unused-vars */
- typeHint = typeHint || type(value);
- function withStack(value, fn) {
- stack.push(value);
- fn();
- stack.pop();
- }
-
- stack = stack || [];
-
- if (stack.indexOf(value) !== -1) {
- return '[Circular]';
- }
-
- switch (typeHint) {
- case 'undefined':
- case 'buffer':
- case 'null':
- canonicalizedObj = value;
- break;
- case 'array':
- withStack(value, function() {
- canonicalizedObj = value.map(function(item) {
- return exports.canonicalize(item, stack);
- });
- });
- break;
- case 'function':
- /* eslint-disable guard-for-in */
- for (prop in value) {
- canonicalizedObj = {};
- break;
- }
- /* eslint-enable guard-for-in */
- if (!canonicalizedObj) {
- canonicalizedObj = emptyRepresentation(value, typeHint);
- break;
- }
- /* falls through */
- case 'object':
- canonicalizedObj = canonicalizedObj || {};
- withStack(value, function() {
- Object.keys(value)
- .sort()
- .forEach(function(key) {
- canonicalizedObj[key] = exports.canonicalize(value[key], stack);
- });
- });
- break;
- case 'date':
- case 'number':
- case 'regexp':
- case 'boolean':
- case 'symbol':
- canonicalizedObj = value;
- break;
- default:
- canonicalizedObj = value + '';
- }
-
- return canonicalizedObj;
-};
-
-/**
- * Determines if pathname has a matching file extension.
- *
- * @private
- * @param {string} pathname - Pathname to check for match.
- * @param {string[]} exts - List of file extensions (sans period).
- * @return {boolean} whether file extension matches.
- * @example
- * hasMatchingExtname('foo.html', ['js', 'css']); // => false
- */
-function hasMatchingExtname(pathname, exts) {
- var suffix = path.extname(pathname).slice(1);
- return exts.some(function(element) {
- return suffix === element;
- });
-}
-
-/**
- * Determines if pathname would be a "hidden" file (or directory) on UN*X.
- *
- * @description
- * On UN*X, pathnames beginning with a full stop (aka dot) are hidden during
- * typical usage. Dotfiles, plain-text configuration files, are prime examples.
- *
- * @see {@link http://xahlee.info/UnixResource_dir/writ/unix_origin_of_dot_filename.html|Origin of Dot File Names}
- *
- * @private
- * @param {string} pathname - Pathname to check for match.
- * @return {boolean} whether pathname would be considered a hidden file.
- * @example
- * isHiddenOnUnix('.profile'); // => true
- */
-function isHiddenOnUnix(pathname) {
- return path.basename(pathname)[0] === '.';
-}
-
-/**
- * Lookup file names at the given `path`.
- *
- * @description
- * Filenames are returned in _traversal_ order by the OS/filesystem.
- * **Make no assumption that the names will be sorted in any fashion.**
- *
- * @public
- * @memberof Mocha.utils
- * @todo Fix extension handling
- * @param {string} filepath - Base path to start searching from.
- * @param {string[]} extensions - File extensions to look for.
- * @param {boolean} recursive - Whether to recurse into subdirectories.
- * @return {string[]} An array of paths.
- * @throws {Error} if no files match pattern.
- * @throws {TypeError} if `filepath` is directory and `extensions` not provided.
- */
-exports.lookupFiles = function lookupFiles(filepath, extensions, recursive) {
- var files = [];
- var stat;
-
- if (!fs.existsSync(filepath)) {
- if (fs.existsSync(filepath + '.js')) {
- filepath += '.js';
- } else {
- // Handle glob
- files = glob.sync(filepath);
- if (!files.length) {
- throw createNoFilesMatchPatternError(
- 'Cannot find any files matching pattern ' + exports.dQuote(filepath),
- filepath
- );
- }
- return files;
- }
- }
-
- // Handle file
- try {
- stat = fs.statSync(filepath);
- if (stat.isFile()) {
- return filepath;
- }
- } catch (err) {
- // ignore error
- return;
- }
-
- // Handle directory
- fs.readdirSync(filepath).forEach(function(dirent) {
- var pathname = path.join(filepath, dirent);
- var stat;
-
- try {
- stat = fs.statSync(pathname);
- if (stat.isDirectory()) {
- if (recursive) {
- files = files.concat(lookupFiles(pathname, extensions, recursive));
- }
- return;
- }
- } catch (err) {
- // ignore error
- return;
- }
- if (!extensions) {
- throw createMissingArgumentError(
- util.format(
- 'Argument %s required when argument %s is a directory',
- exports.sQuote('extensions'),
- exports.sQuote('filepath')
- ),
- 'extensions',
- 'array'
- );
- }
-
- if (
- !stat.isFile() ||
- !hasMatchingExtname(pathname, extensions) ||
- isHiddenOnUnix(pathname)
- ) {
- return;
- }
- files.push(pathname);
- });
-
- return files;
-};
-
-/**
- * process.emitWarning or a polyfill
- * @see https://nodejs.org/api/process.html#process_process_emitwarning_warning_options
- * @ignore
- */
-function emitWarning(msg, type) {
- if (process.emitWarning) {
- process.emitWarning(msg, type);
- } else {
- process.nextTick(function() {
- console.warn(type + ': ' + msg);
- });
- }
-}
-
-/**
- * Show a deprecation warning. Each distinct message is only displayed once.
- * Ignores empty messages.
- *
- * @param {string} [msg] - Warning to print
- * @private
- */
-exports.deprecate = function deprecate(msg) {
- msg = String(msg);
- if (msg && !deprecate.cache[msg]) {
- deprecate.cache[msg] = true;
- emitWarning(msg, 'DeprecationWarning');
- }
-};
-exports.deprecate.cache = {};
-
-/**
- * Show a generic warning.
- * Ignores empty messages.
- *
- * @param {string} [msg] - Warning to print
- * @private
- */
-exports.warn = function warn(msg) {
- if (msg) {
- emitWarning(msg);
- }
-};
-
-/**
- * @summary
- * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`)
- * @description
- * When invoking this function you get a filter function that get the Error.stack as an input,
- * and return a prettify output.
- * (i.e: strip Mocha and internal node functions from stack trace).
- * @returns {Function}
- */
-exports.stackTraceFilter = function() {
- // TODO: Replace with `process.browser`
- var is = typeof document === 'undefined' ? {node: true} : {browser: true};
- var slash = path.sep;
- var cwd;
- if (is.node) {
- cwd = process.cwd() + slash;
- } else {
- cwd = (typeof location === 'undefined'
- ? window.location
- : location
- ).href.replace(/\/[^/]*$/, '/');
- slash = '/';
- }
-
- function isMochaInternal(line) {
- return (
- ~line.indexOf('node_modules' + slash + 'mocha' + slash) ||
- ~line.indexOf(slash + 'mocha.js')
- );
- }
-
- function isNodeInternal(line) {
- return (
- ~line.indexOf('(timers.js:') ||
- ~line.indexOf('(events.js:') ||
- ~line.indexOf('(node.js:') ||
- ~line.indexOf('(module.js:') ||
- ~line.indexOf('GeneratorFunctionPrototype.next (native)') ||
- false
- );
- }
-
- return function(stack) {
- stack = stack.split('\n');
-
- stack = stack.reduce(function(list, line) {
- if (isMochaInternal(line)) {
- return list;
- }
-
- if (is.node && isNodeInternal(line)) {
- return list;
- }
-
- // Clean up cwd(absolute)
- if (/:\d+:\d+\)?$/.test(line)) {
- line = line.replace('(' + cwd, '(');
- }
-
- list.push(line);
- return list;
- }, []);
-
- return stack.join('\n');
- };
-};
-
-/**
- * Crude, but effective.
- * @public
- * @param {*} value
- * @returns {boolean} Whether or not `value` is a Promise
- */
-exports.isPromise = function isPromise(value) {
- return (
- typeof value === 'object' &&
- value !== null &&
- typeof value.then === 'function'
- );
-};
-
-/**
- * Clamps a numeric value to an inclusive range.
- *
- * @param {number} value - Value to be clamped.
- * @param {numer[]} range - Two element array specifying [min, max] range.
- * @returns {number} clamped value
- */
-exports.clamp = function clamp(value, range) {
- return Math.min(Math.max(value, range[0]), range[1]);
-};
-
-/**
- * Single quote text by combining with undirectional ASCII quotation marks.
- *
- * @description
- * Provides a simple means of markup for quoting text to be used in output.
- * Use this to quote names of variables, methods, and packages.
- *
- * package 'foo' cannot be found
- *
- * @private
- * @param {string} str - Value to be quoted.
- * @returns {string} quoted value
- * @example
- * sQuote('n') // => 'n'
- */
-exports.sQuote = function(str) {
- return "'" + str + "'";
-};
-
-/**
- * Double quote text by combining with undirectional ASCII quotation marks.
- *
- * @description
- * Provides a simple means of markup for quoting text to be used in output.
- * Use this to quote names of datatypes, classes, pathnames, and strings.
- *
- * argument 'value' must be "string" or "number"
- *
- * @private
- * @param {string} str - Value to be quoted.
- * @returns {string} quoted value
- * @example
- * dQuote('number') // => "number"
- */
-exports.dQuote = function(str) {
- return '"' + str + '"';
-};
-
-/**
- * Provides simplistic message translation for dealing with plurality.
- *
- * @description
- * Use this to create messages which need to be singular or plural.
- * Some languages have several plural forms, so _complete_ message clauses
- * are preferable to generating the message on the fly.
- *
- * @private
- * @param {number} n - Non-negative integer
- * @param {string} msg1 - Message to be used in English for `n = 1`
- * @param {string} msg2 - Message to be used in English for `n = 0, 2, 3, ...`
- * @returns {string} message corresponding to value of `n`
- * @example
- * var sprintf = require('util').format;
- * var pkgs = ['one', 'two'];
- * var msg = sprintf(
- * ngettext(
- * pkgs.length,
- * 'cannot load package: %s',
- * 'cannot load packages: %s'
- * ),
- * pkgs.map(sQuote).join(', ')
- * );
- * console.log(msg); // => cannot load packages: 'one', 'two'
- */
-exports.ngettext = function(n, msg1, msg2) {
- if (typeof n === 'number' && n >= 0) {
- return n === 1 ? msg1 : msg2;
- }
-};
-
-/**
- * It's a noop.
- * @public
- */
-exports.noop = function() {};
-
-/**
- * Creates a map-like object.
- *
- * @description
- * A "map" is an object with no prototype, for our purposes. In some cases
- * this would be more appropriate than a `Map`, especially if your environment
- * doesn't support it. Recommended for use in Mocha's public APIs.
- *
- * @public
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map|MDN:Map}
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Custom_and_Null_objects|MDN:Object.create - Custom objects}
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign|MDN:Object.assign}
- * @param {...*} [obj] - Arguments to `Object.assign()`.
- * @returns {Object} An object with no prototype, having `...obj` properties
- */
-exports.createMap = function(obj) {
- return assign.apply(
- null,
- [Object.create(null)].concat(Array.prototype.slice.call(arguments))
- );
-};
-
-/**
- * Creates a read-only map-like object.
- *
- * @description
- * This differs from {@link module:utils.createMap createMap} only in that
- * the argument must be non-empty, because the result is frozen.
- *
- * @see {@link module:utils.createMap createMap}
- * @param {...*} [obj] - Arguments to `Object.assign()`.
- * @returns {Object} A frozen object with no prototype, having `...obj` properties
- * @throws {TypeError} if argument is not a non-empty object.
- */
-exports.defineConstants = function(obj) {
- if (type(obj) !== 'object' || !Object.keys(obj).length) {
- throw new TypeError('Invalid argument; expected a non-empty object');
- }
- return Object.freeze(exports.createMap(obj));
-};
-
-}).call(this,require('_process'),require("buffer").Buffer)
-},{"./errors":6,"_process":69,"buffer":43,"debug":45,"fs":42,"glob":42,"he":54,"object.assign":65,"path":42,"util":89}],39:[function(require,module,exports){
-'use strict'
-
-exports.byteLength = byteLength
-exports.toByteArray = toByteArray
-exports.fromByteArray = fromByteArray
-
-var lookup = []
-var revLookup = []
-var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
-
-var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
-for (var i = 0, len = code.length; i < len; ++i) {
- lookup[i] = code[i]
- revLookup[code.charCodeAt(i)] = i
-}
-
-// Support decoding URL-safe base64 strings, as Node.js does.
-// See: https://en.wikipedia.org/wiki/Base64#URL_applications
-revLookup['-'.charCodeAt(0)] = 62
-revLookup['_'.charCodeAt(0)] = 63
-
-function getLens (b64) {
- var len = b64.length
-
- if (len % 4 > 0) {
- throw new Error('Invalid string. Length must be a multiple of 4')
- }
-
- // Trim off extra bytes after placeholder bytes are found
- // See: https://github.com/beatgammit/base64-js/issues/42
- var validLen = b64.indexOf('=')
- if (validLen === -1) validLen = len
-
- var placeHoldersLen = validLen === len
- ? 0
- : 4 - (validLen % 4)
-
- return [validLen, placeHoldersLen]
-}
-
-// base64 is 4/3 + up to two characters of the original data
-function byteLength (b64) {
- var lens = getLens(b64)
- var validLen = lens[0]
- var placeHoldersLen = lens[1]
- return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
-}
-
-function _byteLength (b64, validLen, placeHoldersLen) {
- return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
-}
-
-function toByteArray (b64) {
- var tmp
- var lens = getLens(b64)
- var validLen = lens[0]
- var placeHoldersLen = lens[1]
-
- var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
-
- var curByte = 0
-
- // if there are placeholders, only get up to the last complete 4 chars
- var len = placeHoldersLen > 0
- ? validLen - 4
- : validLen
-
- for (var i = 0; i < len; i += 4) {
- tmp =
- (revLookup[b64.charCodeAt(i)] << 18) |
- (revLookup[b64.charCodeAt(i + 1)] << 12) |
- (revLookup[b64.charCodeAt(i + 2)] << 6) |
- revLookup[b64.charCodeAt(i + 3)]
- arr[curByte++] = (tmp >> 16) & 0xFF
- arr[curByte++] = (tmp >> 8) & 0xFF
- arr[curByte++] = tmp & 0xFF
- }
-
- if (placeHoldersLen === 2) {
- tmp =
- (revLookup[b64.charCodeAt(i)] << 2) |
- (revLookup[b64.charCodeAt(i + 1)] >> 4)
- arr[curByte++] = tmp & 0xFF
- }
-
- if (placeHoldersLen === 1) {
- tmp =
- (revLookup[b64.charCodeAt(i)] << 10) |
- (revLookup[b64.charCodeAt(i + 1)] << 4) |
- (revLookup[b64.charCodeAt(i + 2)] >> 2)
- arr[curByte++] = (tmp >> 8) & 0xFF
- arr[curByte++] = tmp & 0xFF
- }
-
- return arr
-}
-
-function tripletToBase64 (num) {
- return lookup[num >> 18 & 0x3F] +
- lookup[num >> 12 & 0x3F] +
- lookup[num >> 6 & 0x3F] +
- lookup[num & 0x3F]
-}
-
-function encodeChunk (uint8, start, end) {
- var tmp
- var output = []
- for (var i = start; i < end; i += 3) {
- tmp =
- ((uint8[i] << 16) & 0xFF0000) +
- ((uint8[i + 1] << 8) & 0xFF00) +
- (uint8[i + 2] & 0xFF)
- output.push(tripletToBase64(tmp))
- }
- return output.join('')
-}
-
-function fromByteArray (uint8) {
- var tmp
- var len = uint8.length
- var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
- var parts = []
- var maxChunkLength = 16383 // must be multiple of 3
-
- // go through the array every three bytes, we'll deal with trailing stuff later
- for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
- parts.push(encodeChunk(
- uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
- ))
- }
-
- // pad the end with zeros, but make sure to not forget the extra bytes
- if (extraBytes === 1) {
- tmp = uint8[len - 1]
- parts.push(
- lookup[tmp >> 2] +
- lookup[(tmp << 4) & 0x3F] +
- '=='
- )
- } else if (extraBytes === 2) {
- tmp = (uint8[len - 2] << 8) + uint8[len - 1]
- parts.push(
- lookup[tmp >> 10] +
- lookup[(tmp >> 4) & 0x3F] +
- lookup[(tmp << 2) & 0x3F] +
- '='
- )
- }
-
- return parts.join('')
-}
-
-},{}],40:[function(require,module,exports){
-
-},{}],41:[function(require,module,exports){
-(function (process){
-var WritableStream = require('stream').Writable
-var inherits = require('util').inherits
-
-module.exports = BrowserStdout
-
-
-inherits(BrowserStdout, WritableStream)
-
-function BrowserStdout(opts) {
- if (!(this instanceof BrowserStdout)) return new BrowserStdout(opts)
-
- opts = opts || {}
- WritableStream.call(this, opts)
- this.label = (opts.label !== undefined) ? opts.label : 'stdout'
-}
-
-BrowserStdout.prototype._write = function(chunks, encoding, cb) {
- var output = chunks.toString ? chunks.toString() : chunks
- if (this.label === false) {
- console.log(output)
- } else {
- console.log(this.label+':', output)
- }
- process.nextTick(cb)
-}
-
-}).call(this,require('_process'))
-},{"_process":69,"stream":84,"util":89}],42:[function(require,module,exports){
-arguments[4][40][0].apply(exports,arguments)
-},{"dup":40}],43:[function(require,module,exports){
-(function (Buffer){
-/*!
- * The buffer module from node.js, for the browser.
- *
- * @author Feross Aboukhadijeh
- * @license MIT
- */
-/* eslint-disable no-proto */
-
-'use strict'
-
-var base64 = require('base64-js')
-var ieee754 = require('ieee754')
-
-exports.Buffer = Buffer
-exports.SlowBuffer = SlowBuffer
-exports.INSPECT_MAX_BYTES = 50
-
-var K_MAX_LENGTH = 0x7fffffff
-exports.kMaxLength = K_MAX_LENGTH
-
-/**
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
- * === true Use Uint8Array implementation (fastest)
- * === false Print warning and recommend using `buffer` v4.x which has an Object
- * implementation (most compatible, even IE6)
- *
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
- * Opera 11.6+, iOS 4.2+.
- *
- * We report that the browser does not support typed arrays if the are not subclassable
- * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
- * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
- * for __proto__ and has a buggy typed array implementation.
- */
-Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
-
-if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
- typeof console.error === 'function') {
- console.error(
- 'This browser lacks typed array (Uint8Array) support which is required by ' +
- '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
- )
-}
-
-function typedArraySupport () {
- // Can typed array instances can be augmented?
- try {
- var arr = new Uint8Array(1)
- arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
- return arr.foo() === 42
- } catch (e) {
- return false
- }
-}
-
-Object.defineProperty(Buffer.prototype, 'parent', {
- enumerable: true,
- get: function () {
- if (!Buffer.isBuffer(this)) return undefined
- return this.buffer
- }
-})
-
-Object.defineProperty(Buffer.prototype, 'offset', {
- enumerable: true,
- get: function () {
- if (!Buffer.isBuffer(this)) return undefined
- return this.byteOffset
- }
-})
-
-function createBuffer (length) {
- if (length > K_MAX_LENGTH) {
- throw new RangeError('The value "' + length + '" is invalid for option "size"')
- }
- // Return an augmented `Uint8Array` instance
- var buf = new Uint8Array(length)
- buf.__proto__ = Buffer.prototype
- return buf
-}
-
-/**
- * The Buffer constructor returns instances of `Uint8Array` that have their
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
- * returns a single octet.
- *
- * The `Uint8Array` prototype remains unmodified.
- */
-
-function Buffer (arg, encodingOrOffset, length) {
- // Common case.
- if (typeof arg === 'number') {
- if (typeof encodingOrOffset === 'string') {
- throw new TypeError(
- 'The "string" argument must be of type string. Received type number'
- )
- }
- return allocUnsafe(arg)
- }
- return from(arg, encodingOrOffset, length)
-}
-
-// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
-if (typeof Symbol !== 'undefined' && Symbol.species != null &&
- Buffer[Symbol.species] === Buffer) {
- Object.defineProperty(Buffer, Symbol.species, {
- value: null,
- configurable: true,
- enumerable: false,
- writable: false
- })
-}
-
-Buffer.poolSize = 8192 // not used by this implementation
-
-function from (value, encodingOrOffset, length) {
- if (typeof value === 'string') {
- return fromString(value, encodingOrOffset)
- }
-
- if (ArrayBuffer.isView(value)) {
- return fromArrayLike(value)
- }
-
- if (value == null) {
- throw TypeError(
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
- 'or Array-like Object. Received type ' + (typeof value)
- )
- }
-
- if (isInstance(value, ArrayBuffer) ||
- (value && isInstance(value.buffer, ArrayBuffer))) {
- return fromArrayBuffer(value, encodingOrOffset, length)
- }
-
- if (typeof value === 'number') {
- throw new TypeError(
- 'The "value" argument must not be of type number. Received type number'
- )
- }
-
- var valueOf = value.valueOf && value.valueOf()
- if (valueOf != null && valueOf !== value) {
- return Buffer.from(valueOf, encodingOrOffset, length)
- }
-
- var b = fromObject(value)
- if (b) return b
-
- if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
- typeof value[Symbol.toPrimitive] === 'function') {
- return Buffer.from(
- value[Symbol.toPrimitive]('string'), encodingOrOffset, length
- )
- }
-
- throw new TypeError(
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
- 'or Array-like Object. Received type ' + (typeof value)
- )
-}
-
-/**
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
- * if value is a number.
- * Buffer.from(str[, encoding])
- * Buffer.from(array)
- * Buffer.from(buffer)
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
- **/
-Buffer.from = function (value, encodingOrOffset, length) {
- return from(value, encodingOrOffset, length)
-}
-
-// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
-// https://github.com/feross/buffer/pull/148
-Buffer.prototype.__proto__ = Uint8Array.prototype
-Buffer.__proto__ = Uint8Array
-
-function assertSize (size) {
- if (typeof size !== 'number') {
- throw new TypeError('"size" argument must be of type number')
- } else if (size < 0) {
- throw new RangeError('The value "' + size + '" is invalid for option "size"')
- }
-}
-
-function alloc (size, fill, encoding) {
- assertSize(size)
- if (size <= 0) {
- return createBuffer(size)
- }
- if (fill !== undefined) {
- // Only pay attention to encoding if it's a string. This
- // prevents accidentally sending in a number that would
- // be interpretted as a start offset.
- return typeof encoding === 'string'
- ? createBuffer(size).fill(fill, encoding)
- : createBuffer(size).fill(fill)
- }
- return createBuffer(size)
-}
-
-/**
- * Creates a new filled Buffer instance.
- * alloc(size[, fill[, encoding]])
- **/
-Buffer.alloc = function (size, fill, encoding) {
- return alloc(size, fill, encoding)
-}
-
-function allocUnsafe (size) {
- assertSize(size)
- return createBuffer(size < 0 ? 0 : checked(size) | 0)
-}
-
-/**
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
- * */
-Buffer.allocUnsafe = function (size) {
- return allocUnsafe(size)
-}
-/**
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
- */
-Buffer.allocUnsafeSlow = function (size) {
- return allocUnsafe(size)
-}
-
-function fromString (string, encoding) {
- if (typeof encoding !== 'string' || encoding === '') {
- encoding = 'utf8'
- }
-
- if (!Buffer.isEncoding(encoding)) {
- throw new TypeError('Unknown encoding: ' + encoding)
- }
-
- var length = byteLength(string, encoding) | 0
- var buf = createBuffer(length)
-
- var actual = buf.write(string, encoding)
-
- if (actual !== length) {
- // Writing a hex string, for example, that contains invalid characters will
- // cause everything after the first invalid character to be ignored. (e.g.
- // 'abxxcd' will be treated as 'ab')
- buf = buf.slice(0, actual)
- }
-
- return buf
-}
-
-function fromArrayLike (array) {
- var length = array.length < 0 ? 0 : checked(array.length) | 0
- var buf = createBuffer(length)
- for (var i = 0; i < length; i += 1) {
- buf[i] = array[i] & 255
- }
- return buf
-}
-
-function fromArrayBuffer (array, byteOffset, length) {
- if (byteOffset < 0 || array.byteLength < byteOffset) {
- throw new RangeError('"offset" is outside of buffer bounds')
- }
-
- if (array.byteLength < byteOffset + (length || 0)) {
- throw new RangeError('"length" is outside of buffer bounds')
- }
-
- var buf
- if (byteOffset === undefined && length === undefined) {
- buf = new Uint8Array(array)
- } else if (length === undefined) {
- buf = new Uint8Array(array, byteOffset)
- } else {
- buf = new Uint8Array(array, byteOffset, length)
- }
-
- // Return an augmented `Uint8Array` instance
- buf.__proto__ = Buffer.prototype
- return buf
-}
-
-function fromObject (obj) {
- if (Buffer.isBuffer(obj)) {
- var len = checked(obj.length) | 0
- var buf = createBuffer(len)
-
- if (buf.length === 0) {
- return buf
- }
-
- obj.copy(buf, 0, 0, len)
- return buf
- }
-
- if (obj.length !== undefined) {
- if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
- return createBuffer(0)
- }
- return fromArrayLike(obj)
- }
-
- if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
- return fromArrayLike(obj.data)
- }
-}
-
-function checked (length) {
- // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
- // length is NaN (which is otherwise coerced to zero.)
- if (length >= K_MAX_LENGTH) {
- throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
- 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
- }
- return length | 0
-}
-
-function SlowBuffer (length) {
- if (+length != length) { // eslint-disable-line eqeqeq
- length = 0
- }
- return Buffer.alloc(+length)
-}
-
-Buffer.isBuffer = function isBuffer (b) {
- return b != null && b._isBuffer === true &&
- b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
-}
-
-Buffer.compare = function compare (a, b) {
- if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
- if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
- if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
- throw new TypeError(
- 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
- )
- }
-
- if (a === b) return 0
-
- var x = a.length
- var y = b.length
-
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
- if (a[i] !== b[i]) {
- x = a[i]
- y = b[i]
- break
- }
- }
-
- if (x < y) return -1
- if (y < x) return 1
- return 0
-}
-
-Buffer.isEncoding = function isEncoding (encoding) {
- switch (String(encoding).toLowerCase()) {
- case 'hex':
- case 'utf8':
- case 'utf-8':
- case 'ascii':
- case 'latin1':
- case 'binary':
- case 'base64':
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return true
- default:
- return false
- }
-}
-
-Buffer.concat = function concat (list, length) {
- if (!Array.isArray(list)) {
- throw new TypeError('"list" argument must be an Array of Buffers')
- }
-
- if (list.length === 0) {
- return Buffer.alloc(0)
- }
-
- var i
- if (length === undefined) {
- length = 0
- for (i = 0; i < list.length; ++i) {
- length += list[i].length
- }
- }
-
- var buffer = Buffer.allocUnsafe(length)
- var pos = 0
- for (i = 0; i < list.length; ++i) {
- var buf = list[i]
- if (isInstance(buf, Uint8Array)) {
- buf = Buffer.from(buf)
- }
- if (!Buffer.isBuffer(buf)) {
- throw new TypeError('"list" argument must be an Array of Buffers')
- }
- buf.copy(buffer, pos)
- pos += buf.length
- }
- return buffer
-}
-
-function byteLength (string, encoding) {
- if (Buffer.isBuffer(string)) {
- return string.length
- }
- if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
- return string.byteLength
- }
- if (typeof string !== 'string') {
- throw new TypeError(
- 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
- 'Received type ' + typeof string
- )
- }
-
- var len = string.length
- var mustMatch = (arguments.length > 2 && arguments[2] === true)
- if (!mustMatch && len === 0) return 0
-
- // Use a for loop to avoid recursion
- var loweredCase = false
- for (;;) {
- switch (encoding) {
- case 'ascii':
- case 'latin1':
- case 'binary':
- return len
- case 'utf8':
- case 'utf-8':
- return utf8ToBytes(string).length
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return len * 2
- case 'hex':
- return len >>> 1
- case 'base64':
- return base64ToBytes(string).length
- default:
- if (loweredCase) {
- return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
- }
- encoding = ('' + encoding).toLowerCase()
- loweredCase = true
- }
- }
-}
-Buffer.byteLength = byteLength
-
-function slowToString (encoding, start, end) {
- var loweredCase = false
-
- // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
- // property of a typed array.
-
- // This behaves neither like String nor Uint8Array in that we set start/end
- // to their upper/lower bounds if the value passed is out of range.
- // undefined is handled specially as per ECMA-262 6th Edition,
- // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
- if (start === undefined || start < 0) {
- start = 0
- }
- // Return early if start > this.length. Done here to prevent potential uint32
- // coercion fail below.
- if (start > this.length) {
- return ''
- }
-
- if (end === undefined || end > this.length) {
- end = this.length
- }
-
- if (end <= 0) {
- return ''
- }
-
- // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
- end >>>= 0
- start >>>= 0
-
- if (end <= start) {
- return ''
- }
-
- if (!encoding) encoding = 'utf8'
-
- while (true) {
- switch (encoding) {
- case 'hex':
- return hexSlice(this, start, end)
-
- case 'utf8':
- case 'utf-8':
- return utf8Slice(this, start, end)
-
- case 'ascii':
- return asciiSlice(this, start, end)
-
- case 'latin1':
- case 'binary':
- return latin1Slice(this, start, end)
-
- case 'base64':
- return base64Slice(this, start, end)
-
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return utf16leSlice(this, start, end)
-
- default:
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
- encoding = (encoding + '').toLowerCase()
- loweredCase = true
- }
- }
-}
-
-// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
-// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
-// reliably in a browserify context because there could be multiple different
-// copies of the 'buffer' package in use. This method works even for Buffer
-// instances that were created from another copy of the `buffer` package.
-// See: https://github.com/feross/buffer/issues/154
-Buffer.prototype._isBuffer = true
-
-function swap (b, n, m) {
- var i = b[n]
- b[n] = b[m]
- b[m] = i
-}
-
-Buffer.prototype.swap16 = function swap16 () {
- var len = this.length
- if (len % 2 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 16-bits')
- }
- for (var i = 0; i < len; i += 2) {
- swap(this, i, i + 1)
- }
- return this
-}
-
-Buffer.prototype.swap32 = function swap32 () {
- var len = this.length
- if (len % 4 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 32-bits')
- }
- for (var i = 0; i < len; i += 4) {
- swap(this, i, i + 3)
- swap(this, i + 1, i + 2)
- }
- return this
-}
-
-Buffer.prototype.swap64 = function swap64 () {
- var len = this.length
- if (len % 8 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 64-bits')
- }
- for (var i = 0; i < len; i += 8) {
- swap(this, i, i + 7)
- swap(this, i + 1, i + 6)
- swap(this, i + 2, i + 5)
- swap(this, i + 3, i + 4)
- }
- return this
-}
-
-Buffer.prototype.toString = function toString () {
- var length = this.length
- if (length === 0) return ''
- if (arguments.length === 0) return utf8Slice(this, 0, length)
- return slowToString.apply(this, arguments)
-}
-
-Buffer.prototype.toLocaleString = Buffer.prototype.toString
-
-Buffer.prototype.equals = function equals (b) {
- if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
- if (this === b) return true
- return Buffer.compare(this, b) === 0
-}
-
-Buffer.prototype.inspect = function inspect () {
- var str = ''
- var max = exports.INSPECT_MAX_BYTES
- str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
- if (this.length > max) str += ' ... '
- return ''
-}
-
-Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
- if (isInstance(target, Uint8Array)) {
- target = Buffer.from(target, target.offset, target.byteLength)
- }
- if (!Buffer.isBuffer(target)) {
- throw new TypeError(
- 'The "target" argument must be one of type Buffer or Uint8Array. ' +
- 'Received type ' + (typeof target)
- )
- }
-
- if (start === undefined) {
- start = 0
- }
- if (end === undefined) {
- end = target ? target.length : 0
- }
- if (thisStart === undefined) {
- thisStart = 0
- }
- if (thisEnd === undefined) {
- thisEnd = this.length
- }
-
- if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
- throw new RangeError('out of range index')
- }
-
- if (thisStart >= thisEnd && start >= end) {
- return 0
- }
- if (thisStart >= thisEnd) {
- return -1
- }
- if (start >= end) {
- return 1
- }
-
- start >>>= 0
- end >>>= 0
- thisStart >>>= 0
- thisEnd >>>= 0
-
- if (this === target) return 0
-
- var x = thisEnd - thisStart
- var y = end - start
- var len = Math.min(x, y)
-
- var thisCopy = this.slice(thisStart, thisEnd)
- var targetCopy = target.slice(start, end)
-
- for (var i = 0; i < len; ++i) {
- if (thisCopy[i] !== targetCopy[i]) {
- x = thisCopy[i]
- y = targetCopy[i]
- break
- }
- }
-
- if (x < y) return -1
- if (y < x) return 1
- return 0
-}
-
-// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
-// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
-//
-// Arguments:
-// - buffer - a Buffer to search
-// - val - a string, Buffer, or number
-// - byteOffset - an index into `buffer`; will be clamped to an int32
-// - encoding - an optional encoding, relevant is val is a string
-// - dir - true for indexOf, false for lastIndexOf
-function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
- // Empty buffer means no match
- if (buffer.length === 0) return -1
-
- // Normalize byteOffset
- if (typeof byteOffset === 'string') {
- encoding = byteOffset
- byteOffset = 0
- } else if (byteOffset > 0x7fffffff) {
- byteOffset = 0x7fffffff
- } else if (byteOffset < -0x80000000) {
- byteOffset = -0x80000000
- }
- byteOffset = +byteOffset // Coerce to Number.
- if (numberIsNaN(byteOffset)) {
- // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
- byteOffset = dir ? 0 : (buffer.length - 1)
- }
-
- // Normalize byteOffset: negative offsets start from the end of the buffer
- if (byteOffset < 0) byteOffset = buffer.length + byteOffset
- if (byteOffset >= buffer.length) {
- if (dir) return -1
- else byteOffset = buffer.length - 1
- } else if (byteOffset < 0) {
- if (dir) byteOffset = 0
- else return -1
- }
-
- // Normalize val
- if (typeof val === 'string') {
- val = Buffer.from(val, encoding)
- }
-
- // Finally, search either indexOf (if dir is true) or lastIndexOf
- if (Buffer.isBuffer(val)) {
- // Special case: looking for empty string/buffer always fails
- if (val.length === 0) {
- return -1
- }
- return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
- } else if (typeof val === 'number') {
- val = val & 0xFF // Search for a byte value [0-255]
- if (typeof Uint8Array.prototype.indexOf === 'function') {
- if (dir) {
- return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
- } else {
- return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
- }
- }
- return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
- }
-
- throw new TypeError('val must be string, number or Buffer')
-}
-
-function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
- var indexSize = 1
- var arrLength = arr.length
- var valLength = val.length
-
- if (encoding !== undefined) {
- encoding = String(encoding).toLowerCase()
- if (encoding === 'ucs2' || encoding === 'ucs-2' ||
- encoding === 'utf16le' || encoding === 'utf-16le') {
- if (arr.length < 2 || val.length < 2) {
- return -1
- }
- indexSize = 2
- arrLength /= 2
- valLength /= 2
- byteOffset /= 2
- }
- }
-
- function read (buf, i) {
- if (indexSize === 1) {
- return buf[i]
- } else {
- return buf.readUInt16BE(i * indexSize)
- }
- }
-
- var i
- if (dir) {
- var foundIndex = -1
- for (i = byteOffset; i < arrLength; i++) {
- if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
- if (foundIndex === -1) foundIndex = i
- if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
- } else {
- if (foundIndex !== -1) i -= i - foundIndex
- foundIndex = -1
- }
- }
- } else {
- if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
- for (i = byteOffset; i >= 0; i--) {
- var found = true
- for (var j = 0; j < valLength; j++) {
- if (read(arr, i + j) !== read(val, j)) {
- found = false
- break
- }
- }
- if (found) return i
- }
- }
-
- return -1
-}
-
-Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
- return this.indexOf(val, byteOffset, encoding) !== -1
-}
-
-Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
- return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
-}
-
-Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
- return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
-}
-
-function hexWrite (buf, string, offset, length) {
- offset = Number(offset) || 0
- var remaining = buf.length - offset
- if (!length) {
- length = remaining
- } else {
- length = Number(length)
- if (length > remaining) {
- length = remaining
- }
- }
-
- var strLen = string.length
-
- if (length > strLen / 2) {
- length = strLen / 2
- }
- for (var i = 0; i < length; ++i) {
- var parsed = parseInt(string.substr(i * 2, 2), 16)
- if (numberIsNaN(parsed)) return i
- buf[offset + i] = parsed
- }
- return i
-}
-
-function utf8Write (buf, string, offset, length) {
- return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
-}
-
-function asciiWrite (buf, string, offset, length) {
- return blitBuffer(asciiToBytes(string), buf, offset, length)
-}
-
-function latin1Write (buf, string, offset, length) {
- return asciiWrite(buf, string, offset, length)
-}
-
-function base64Write (buf, string, offset, length) {
- return blitBuffer(base64ToBytes(string), buf, offset, length)
-}
-
-function ucs2Write (buf, string, offset, length) {
- return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
-}
-
-Buffer.prototype.write = function write (string, offset, length, encoding) {
- // Buffer#write(string)
- if (offset === undefined) {
- encoding = 'utf8'
- length = this.length
- offset = 0
- // Buffer#write(string, encoding)
- } else if (length === undefined && typeof offset === 'string') {
- encoding = offset
- length = this.length
- offset = 0
- // Buffer#write(string, offset[, length][, encoding])
- } else if (isFinite(offset)) {
- offset = offset >>> 0
- if (isFinite(length)) {
- length = length >>> 0
- if (encoding === undefined) encoding = 'utf8'
- } else {
- encoding = length
- length = undefined
- }
- } else {
- throw new Error(
- 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
- )
- }
-
- var remaining = this.length - offset
- if (length === undefined || length > remaining) length = remaining
-
- if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
- throw new RangeError('Attempt to write outside buffer bounds')
- }
-
- if (!encoding) encoding = 'utf8'
-
- var loweredCase = false
- for (;;) {
- switch (encoding) {
- case 'hex':
- return hexWrite(this, string, offset, length)
-
- case 'utf8':
- case 'utf-8':
- return utf8Write(this, string, offset, length)
-
- case 'ascii':
- return asciiWrite(this, string, offset, length)
-
- case 'latin1':
- case 'binary':
- return latin1Write(this, string, offset, length)
-
- case 'base64':
- // Warning: maxLength not taken into account in base64Write
- return base64Write(this, string, offset, length)
-
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return ucs2Write(this, string, offset, length)
-
- default:
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
- encoding = ('' + encoding).toLowerCase()
- loweredCase = true
- }
- }
-}
-
-Buffer.prototype.toJSON = function toJSON () {
- return {
- type: 'Buffer',
- data: Array.prototype.slice.call(this._arr || this, 0)
- }
-}
-
-function base64Slice (buf, start, end) {
- if (start === 0 && end === buf.length) {
- return base64.fromByteArray(buf)
- } else {
- return base64.fromByteArray(buf.slice(start, end))
- }
-}
-
-function utf8Slice (buf, start, end) {
- end = Math.min(buf.length, end)
- var res = []
-
- var i = start
- while (i < end) {
- var firstByte = buf[i]
- var codePoint = null
- var bytesPerSequence = (firstByte > 0xEF) ? 4
- : (firstByte > 0xDF) ? 3
- : (firstByte > 0xBF) ? 2
- : 1
-
- if (i + bytesPerSequence <= end) {
- var secondByte, thirdByte, fourthByte, tempCodePoint
-
- switch (bytesPerSequence) {
- case 1:
- if (firstByte < 0x80) {
- codePoint = firstByte
- }
- break
- case 2:
- secondByte = buf[i + 1]
- if ((secondByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
- if (tempCodePoint > 0x7F) {
- codePoint = tempCodePoint
- }
- }
- break
- case 3:
- secondByte = buf[i + 1]
- thirdByte = buf[i + 2]
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
- if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
- codePoint = tempCodePoint
- }
- }
- break
- case 4:
- secondByte = buf[i + 1]
- thirdByte = buf[i + 2]
- fourthByte = buf[i + 3]
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
- if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
- codePoint = tempCodePoint
- }
- }
- }
- }
-
- if (codePoint === null) {
- // we did not generate a valid codePoint so insert a
- // replacement char (U+FFFD) and advance only 1 byte
- codePoint = 0xFFFD
- bytesPerSequence = 1
- } else if (codePoint > 0xFFFF) {
- // encode to utf16 (surrogate pair dance)
- codePoint -= 0x10000
- res.push(codePoint >>> 10 & 0x3FF | 0xD800)
- codePoint = 0xDC00 | codePoint & 0x3FF
- }
-
- res.push(codePoint)
- i += bytesPerSequence
- }
-
- return decodeCodePointsArray(res)
-}
-
-// Based on http://stackoverflow.com/a/22747272/680742, the browser with
-// the lowest limit is Chrome, with 0x10000 args.
-// We go 1 magnitude less, for safety
-var MAX_ARGUMENTS_LENGTH = 0x1000
-
-function decodeCodePointsArray (codePoints) {
- var len = codePoints.length
- if (len <= MAX_ARGUMENTS_LENGTH) {
- return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
- }
-
- // Decode in chunks to avoid "call stack size exceeded".
- var res = ''
- var i = 0
- while (i < len) {
- res += String.fromCharCode.apply(
- String,
- codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
- )
- }
- return res
-}
-
-function asciiSlice (buf, start, end) {
- var ret = ''
- end = Math.min(buf.length, end)
-
- for (var i = start; i < end; ++i) {
- ret += String.fromCharCode(buf[i] & 0x7F)
- }
- return ret
-}
-
-function latin1Slice (buf, start, end) {
- var ret = ''
- end = Math.min(buf.length, end)
-
- for (var i = start; i < end; ++i) {
- ret += String.fromCharCode(buf[i])
- }
- return ret
-}
-
-function hexSlice (buf, start, end) {
- var len = buf.length
-
- if (!start || start < 0) start = 0
- if (!end || end < 0 || end > len) end = len
-
- var out = ''
- for (var i = start; i < end; ++i) {
- out += toHex(buf[i])
- }
- return out
-}
-
-function utf16leSlice (buf, start, end) {
- var bytes = buf.slice(start, end)
- var res = ''
- for (var i = 0; i < bytes.length; i += 2) {
- res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
- }
- return res
-}
-
-Buffer.prototype.slice = function slice (start, end) {
- var len = this.length
- start = ~~start
- end = end === undefined ? len : ~~end
-
- if (start < 0) {
- start += len
- if (start < 0) start = 0
- } else if (start > len) {
- start = len
- }
-
- if (end < 0) {
- end += len
- if (end < 0) end = 0
- } else if (end > len) {
- end = len
- }
-
- if (end < start) end = start
-
- var newBuf = this.subarray(start, end)
- // Return an augmented `Uint8Array` instance
- newBuf.__proto__ = Buffer.prototype
- return newBuf
-}
-
-/*
- * Need to make sure that buffer isn't trying to write out of bounds.
- */
-function checkOffset (offset, ext, length) {
- if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
- if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
-}
-
-Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
-
- var val = this[offset]
- var mul = 1
- var i = 0
- while (++i < byteLength && (mul *= 0x100)) {
- val += this[offset + i] * mul
- }
-
- return val
-}
-
-Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) {
- checkOffset(offset, byteLength, this.length)
- }
-
- var val = this[offset + --byteLength]
- var mul = 1
- while (byteLength > 0 && (mul *= 0x100)) {
- val += this[offset + --byteLength] * mul
- }
-
- return val
-}
-
-Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 1, this.length)
- return this[offset]
-}
-
-Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 2, this.length)
- return this[offset] | (this[offset + 1] << 8)
-}
-
-Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 2, this.length)
- return (this[offset] << 8) | this[offset + 1]
-}
-
-Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
-
- return ((this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16)) +
- (this[offset + 3] * 0x1000000)
-}
-
-Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
-
- return (this[offset] * 0x1000000) +
- ((this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- this[offset + 3])
-}
-
-Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
-
- var val = this[offset]
- var mul = 1
- var i = 0
- while (++i < byteLength && (mul *= 0x100)) {
- val += this[offset + i] * mul
- }
- mul *= 0x80
-
- if (val >= mul) val -= Math.pow(2, 8 * byteLength)
-
- return val
-}
-
-Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
-
- var i = byteLength
- var mul = 1
- var val = this[offset + --i]
- while (i > 0 && (mul *= 0x100)) {
- val += this[offset + --i] * mul
- }
- mul *= 0x80
-
- if (val >= mul) val -= Math.pow(2, 8 * byteLength)
-
- return val
-}
-
-Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 1, this.length)
- if (!(this[offset] & 0x80)) return (this[offset])
- return ((0xff - this[offset] + 1) * -1)
-}
-
-Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 2, this.length)
- var val = this[offset] | (this[offset + 1] << 8)
- return (val & 0x8000) ? val | 0xFFFF0000 : val
-}
-
-Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 2, this.length)
- var val = this[offset + 1] | (this[offset] << 8)
- return (val & 0x8000) ? val | 0xFFFF0000 : val
-}
-
-Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
-
- return (this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16) |
- (this[offset + 3] << 24)
-}
-
-Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
-
- return (this[offset] << 24) |
- (this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- (this[offset + 3])
-}
-
-Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ieee754.read(this, offset, true, 23, 4)
-}
-
-Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ieee754.read(this, offset, false, 23, 4)
-}
-
-Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 8, this.length)
- return ieee754.read(this, offset, true, 52, 8)
-}
-
-Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 8, this.length)
- return ieee754.read(this, offset, false, 52, 8)
-}
-
-function checkInt (buf, value, offset, ext, max, min) {
- if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
- if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
-}
-
-Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) {
- var maxBytes = Math.pow(2, 8 * byteLength) - 1
- checkInt(this, value, offset, byteLength, maxBytes, 0)
- }
-
- var mul = 1
- var i = 0
- this[offset] = value & 0xFF
- while (++i < byteLength && (mul *= 0x100)) {
- this[offset + i] = (value / mul) & 0xFF
- }
-
- return offset + byteLength
-}
-
-Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) {
- var maxBytes = Math.pow(2, 8 * byteLength) - 1
- checkInt(this, value, offset, byteLength, maxBytes, 0)
- }
-
- var i = byteLength - 1
- var mul = 1
- this[offset + i] = value & 0xFF
- while (--i >= 0 && (mul *= 0x100)) {
- this[offset + i] = (value / mul) & 0xFF
- }
-
- return offset + byteLength
-}
-
-Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
- this[offset] = (value & 0xff)
- return offset + 1
-}
-
-Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- return offset + 2
-}
-
-Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
- this[offset] = (value >>> 8)
- this[offset + 1] = (value & 0xff)
- return offset + 2
-}
-
-Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
- this[offset + 3] = (value >>> 24)
- this[offset + 2] = (value >>> 16)
- this[offset + 1] = (value >>> 8)
- this[offset] = (value & 0xff)
- return offset + 4
-}
-
-Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
- this[offset] = (value >>> 24)
- this[offset + 1] = (value >>> 16)
- this[offset + 2] = (value >>> 8)
- this[offset + 3] = (value & 0xff)
- return offset + 4
-}
-
-Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) {
- var limit = Math.pow(2, (8 * byteLength) - 1)
-
- checkInt(this, value, offset, byteLength, limit - 1, -limit)
- }
-
- var i = 0
- var mul = 1
- var sub = 0
- this[offset] = value & 0xFF
- while (++i < byteLength && (mul *= 0x100)) {
- if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
- sub = 1
- }
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
- }
-
- return offset + byteLength
-}
-
-Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) {
- var limit = Math.pow(2, (8 * byteLength) - 1)
-
- checkInt(this, value, offset, byteLength, limit - 1, -limit)
- }
-
- var i = byteLength - 1
- var mul = 1
- var sub = 0
- this[offset + i] = value & 0xFF
- while (--i >= 0 && (mul *= 0x100)) {
- if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
- sub = 1
- }
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
- }
-
- return offset + byteLength
-}
-
-Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
- if (value < 0) value = 0xff + value + 1
- this[offset] = (value & 0xff)
- return offset + 1
-}
-
-Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- return offset + 2
-}
-
-Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
- this[offset] = (value >>> 8)
- this[offset + 1] = (value & 0xff)
- return offset + 2
-}
-
-Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- this[offset + 2] = (value >>> 16)
- this[offset + 3] = (value >>> 24)
- return offset + 4
-}
-
-Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
- if (value < 0) value = 0xffffffff + value + 1
- this[offset] = (value >>> 24)
- this[offset + 1] = (value >>> 16)
- this[offset + 2] = (value >>> 8)
- this[offset + 3] = (value & 0xff)
- return offset + 4
-}
-
-function checkIEEE754 (buf, value, offset, ext, max, min) {
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
- if (offset < 0) throw new RangeError('Index out of range')
-}
-
-function writeFloat (buf, value, offset, littleEndian, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) {
- checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
- }
- ieee754.write(buf, value, offset, littleEndian, 23, 4)
- return offset + 4
-}
-
-Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
- return writeFloat(this, value, offset, true, noAssert)
-}
-
-Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
- return writeFloat(this, value, offset, false, noAssert)
-}
-
-function writeDouble (buf, value, offset, littleEndian, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) {
- checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
- }
- ieee754.write(buf, value, offset, littleEndian, 52, 8)
- return offset + 8
-}
-
-Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
- return writeDouble(this, value, offset, true, noAssert)
-}
-
-Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
- return writeDouble(this, value, offset, false, noAssert)
-}
-
-// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
-Buffer.prototype.copy = function copy (target, targetStart, start, end) {
- if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
- if (!start) start = 0
- if (!end && end !== 0) end = this.length
- if (targetStart >= target.length) targetStart = target.length
- if (!targetStart) targetStart = 0
- if (end > 0 && end < start) end = start
-
- // Copy 0 bytes; we're done
- if (end === start) return 0
- if (target.length === 0 || this.length === 0) return 0
-
- // Fatal error conditions
- if (targetStart < 0) {
- throw new RangeError('targetStart out of bounds')
- }
- if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
- if (end < 0) throw new RangeError('sourceEnd out of bounds')
-
- // Are we oob?
- if (end > this.length) end = this.length
- if (target.length - targetStart < end - start) {
- end = target.length - targetStart + start
- }
-
- var len = end - start
-
- if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
- // Use built-in when available, missing from IE11
- this.copyWithin(targetStart, start, end)
- } else if (this === target && start < targetStart && targetStart < end) {
- // descending copy from end
- for (var i = len - 1; i >= 0; --i) {
- target[i + targetStart] = this[i + start]
- }
- } else {
- Uint8Array.prototype.set.call(
- target,
- this.subarray(start, end),
- targetStart
- )
- }
-
- return len
-}
-
-// Usage:
-// buffer.fill(number[, offset[, end]])
-// buffer.fill(buffer[, offset[, end]])
-// buffer.fill(string[, offset[, end]][, encoding])
-Buffer.prototype.fill = function fill (val, start, end, encoding) {
- // Handle string cases:
- if (typeof val === 'string') {
- if (typeof start === 'string') {
- encoding = start
- start = 0
- end = this.length
- } else if (typeof end === 'string') {
- encoding = end
- end = this.length
- }
- if (encoding !== undefined && typeof encoding !== 'string') {
- throw new TypeError('encoding must be a string')
- }
- if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
- throw new TypeError('Unknown encoding: ' + encoding)
- }
- if (val.length === 1) {
- var code = val.charCodeAt(0)
- if ((encoding === 'utf8' && code < 128) ||
- encoding === 'latin1') {
- // Fast path: If `val` fits into a single byte, use that numeric value.
- val = code
- }
- }
- } else if (typeof val === 'number') {
- val = val & 255
- }
-
- // Invalid ranges are not set to a default, so can range check early.
- if (start < 0 || this.length < start || this.length < end) {
- throw new RangeError('Out of range index')
- }
-
- if (end <= start) {
- return this
- }
-
- start = start >>> 0
- end = end === undefined ? this.length : end >>> 0
-
- if (!val) val = 0
-
- var i
- if (typeof val === 'number') {
- for (i = start; i < end; ++i) {
- this[i] = val
- }
- } else {
- var bytes = Buffer.isBuffer(val)
- ? val
- : Buffer.from(val, encoding)
- var len = bytes.length
- if (len === 0) {
- throw new TypeError('The value "' + val +
- '" is invalid for argument "value"')
- }
- for (i = 0; i < end - start; ++i) {
- this[i + start] = bytes[i % len]
- }
- }
-
- return this
-}
-
-// HELPER FUNCTIONS
-// ================
-
-var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
-
-function base64clean (str) {
- // Node takes equal signs as end of the Base64 encoding
- str = str.split('=')[0]
- // Node strips out invalid characters like \n and \t from the string, base64-js does not
- str = str.trim().replace(INVALID_BASE64_RE, '')
- // Node converts strings with length < 2 to ''
- if (str.length < 2) return ''
- // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
- while (str.length % 4 !== 0) {
- str = str + '='
- }
- return str
-}
-
-function toHex (n) {
- if (n < 16) return '0' + n.toString(16)
- return n.toString(16)
-}
-
-function utf8ToBytes (string, units) {
- units = units || Infinity
- var codePoint
- var length = string.length
- var leadSurrogate = null
- var bytes = []
-
- for (var i = 0; i < length; ++i) {
- codePoint = string.charCodeAt(i)
-
- // is surrogate component
- if (codePoint > 0xD7FF && codePoint < 0xE000) {
- // last char was a lead
- if (!leadSurrogate) {
- // no lead yet
- if (codePoint > 0xDBFF) {
- // unexpected trail
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- continue
- } else if (i + 1 === length) {
- // unpaired lead
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- continue
- }
-
- // valid lead
- leadSurrogate = codePoint
-
- continue
- }
-
- // 2 leads in a row
- if (codePoint < 0xDC00) {
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- leadSurrogate = codePoint
- continue
- }
-
- // valid surrogate pair
- codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
- } else if (leadSurrogate) {
- // valid bmp char, but last char was a lead
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- }
-
- leadSurrogate = null
-
- // encode utf8
- if (codePoint < 0x80) {
- if ((units -= 1) < 0) break
- bytes.push(codePoint)
- } else if (codePoint < 0x800) {
- if ((units -= 2) < 0) break
- bytes.push(
- codePoint >> 0x6 | 0xC0,
- codePoint & 0x3F | 0x80
- )
- } else if (codePoint < 0x10000) {
- if ((units -= 3) < 0) break
- bytes.push(
- codePoint >> 0xC | 0xE0,
- codePoint >> 0x6 & 0x3F | 0x80,
- codePoint & 0x3F | 0x80
- )
- } else if (codePoint < 0x110000) {
- if ((units -= 4) < 0) break
- bytes.push(
- codePoint >> 0x12 | 0xF0,
- codePoint >> 0xC & 0x3F | 0x80,
- codePoint >> 0x6 & 0x3F | 0x80,
- codePoint & 0x3F | 0x80
- )
- } else {
- throw new Error('Invalid code point')
- }
- }
-
- return bytes
-}
-
-function asciiToBytes (str) {
- var byteArray = []
- for (var i = 0; i < str.length; ++i) {
- // Node's code seems to be doing this and not & 0x7F..
- byteArray.push(str.charCodeAt(i) & 0xFF)
- }
- return byteArray
-}
-
-function utf16leToBytes (str, units) {
- var c, hi, lo
- var byteArray = []
- for (var i = 0; i < str.length; ++i) {
- if ((units -= 2) < 0) break
-
- c = str.charCodeAt(i)
- hi = c >> 8
- lo = c % 256
- byteArray.push(lo)
- byteArray.push(hi)
- }
-
- return byteArray
-}
-
-function base64ToBytes (str) {
- return base64.toByteArray(base64clean(str))
-}
-
-function blitBuffer (src, dst, offset, length) {
- for (var i = 0; i < length; ++i) {
- if ((i + offset >= dst.length) || (i >= src.length)) break
- dst[i + offset] = src[i]
- }
- return i
-}
-
-// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
-// the `instanceof` check but they should be treated as of that type.
-// See: https://github.com/feross/buffer/issues/166
-function isInstance (obj, type) {
- return obj instanceof type ||
- (obj != null && obj.constructor != null && obj.constructor.name != null &&
- obj.constructor.name === type.name)
-}
-function numberIsNaN (obj) {
- // For IE11 support
- return obj !== obj // eslint-disable-line no-self-compare
-}
-
-}).call(this,require("buffer").Buffer)
-},{"base64-js":39,"buffer":43,"ieee754":55}],44:[function(require,module,exports){
-(function (Buffer){
-// Copyright Joyent, Inc. and other Node 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.
-
-// NOTE: These type checking functions intentionally don't use `instanceof`
-// because it is fragile and can be easily faked with `Object.create()`.
-
-function isArray(arg) {
- if (Array.isArray) {
- return Array.isArray(arg);
- }
- return objectToString(arg) === '[object Array]';
-}
-exports.isArray = isArray;
-
-function isBoolean(arg) {
- return typeof arg === 'boolean';
-}
-exports.isBoolean = isBoolean;
-
-function isNull(arg) {
- return arg === null;
-}
-exports.isNull = isNull;
-
-function isNullOrUndefined(arg) {
- return arg == null;
-}
-exports.isNullOrUndefined = isNullOrUndefined;
-
-function isNumber(arg) {
- return typeof arg === 'number';
-}
-exports.isNumber = isNumber;
-
-function isString(arg) {
- return typeof arg === 'string';
-}
-exports.isString = isString;
-
-function isSymbol(arg) {
- return typeof arg === 'symbol';
-}
-exports.isSymbol = isSymbol;
-
-function isUndefined(arg) {
- return arg === void 0;
-}
-exports.isUndefined = isUndefined;
-
-function isRegExp(re) {
- return objectToString(re) === '[object RegExp]';
-}
-exports.isRegExp = isRegExp;
-
-function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
-}
-exports.isObject = isObject;
-
-function isDate(d) {
- return objectToString(d) === '[object Date]';
-}
-exports.isDate = isDate;
-
-function isError(e) {
- return (objectToString(e) === '[object Error]' || e instanceof Error);
-}
-exports.isError = isError;
-
-function isFunction(arg) {
- return typeof arg === 'function';
-}
-exports.isFunction = isFunction;
-
-function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
-}
-exports.isPrimitive = isPrimitive;
-
-exports.isBuffer = Buffer.isBuffer;
-
-function objectToString(o) {
- return Object.prototype.toString.call(o);
-}
-
-}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
-},{"../../is-buffer/index.js":57}],45:[function(require,module,exports){
-(function (process){
-"use strict";
-
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
-
-/* eslint-env browser */
-
-/**
- * This is the web browser implementation of `debug()`.
- */
-exports.log = log;
-exports.formatArgs = formatArgs;
-exports.save = save;
-exports.load = load;
-exports.useColors = useColors;
-exports.storage = localstorage();
-/**
- * Colors.
- */
-
-exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
-/**
- * Currently only WebKit-based Web Inspectors, Firefox >= v31,
- * and the Firebug extension (any Firefox version) are known
- * to support "%c" CSS customizations.
- *
- * TODO: add a `localStorage` variable to explicitly enable/disable colors
- */
-// eslint-disable-next-line complexity
-
-function useColors() {
- // NB: In an Electron preload script, document will be defined but not fully
- // initialized. Since we know we're in Chrome, we'll just detect this case
- // explicitly
- if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
- return true;
- } // Internet Explorer and Edge do not support colors.
-
-
- if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
- return false;
- } // Is webkit? http://stackoverflow.com/a/16459606/376773
- // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
-
-
- return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
- typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
- // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
- typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
- typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
-}
-/**
- * Colorize log arguments if enabled.
- *
- * @api public
- */
-
-
-function formatArgs(args) {
- args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
-
- if (!this.useColors) {
- return;
- }
-
- var c = 'color: ' + this.color;
- args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
- // arguments passed either before or after the %c, so we need to
- // figure out the correct index to insert the CSS into
-
- var index = 0;
- var lastC = 0;
- args[0].replace(/%[a-zA-Z%]/g, function (match) {
- if (match === '%%') {
- return;
- }
-
- index++;
-
- if (match === '%c') {
- // We only are interested in the *last* %c
- // (the user may have provided their own)
- lastC = index;
- }
- });
- args.splice(lastC, 0, c);
-}
-/**
- * Invokes `console.log()` when available.
- * No-op when `console.log` is not a "function".
- *
- * @api public
- */
-
-
-function log() {
- var _console;
-
- // This hackery is required for IE8/9, where
- // the `console.log` function doesn't have 'apply'
- return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
-}
-/**
- * Save `namespaces`.
- *
- * @param {String} namespaces
- * @api private
- */
-
-
-function save(namespaces) {
- try {
- if (namespaces) {
- exports.storage.setItem('debug', namespaces);
- } else {
- exports.storage.removeItem('debug');
- }
- } catch (error) {// Swallow
- // XXX (@Qix-) should we be logging these?
- }
-}
-/**
- * Load `namespaces`.
- *
- * @return {String} returns the previously persisted debug modes
- * @api private
- */
-
-
-function load() {
- var r;
-
- try {
- r = exports.storage.getItem('debug');
- } catch (error) {} // Swallow
- // XXX (@Qix-) should we be logging these?
- // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
-
-
- if (!r && typeof process !== 'undefined' && 'env' in process) {
- r = process.env.DEBUG;
- }
-
- return r;
-}
-/**
- * Localstorage attempts to return the localstorage.
- *
- * This is necessary because safari throws
- * when a user disables cookies/localstorage
- * and you attempt to access it.
- *
- * @return {LocalStorage}
- * @api private
- */
-
-
-function localstorage() {
- try {
- // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
- // The Browser also has localStorage in the global context.
- return localStorage;
- } catch (error) {// Swallow
- // XXX (@Qix-) should we be logging these?
- }
-}
-
-module.exports = require('./common')(exports);
-var formatters = module.exports.formatters;
-/**
- * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
- */
-
-formatters.j = function (v) {
- try {
- return JSON.stringify(v);
- } catch (error) {
- return '[UnexpectedJSONParseError]: ' + error.message;
- }
-};
-
-
-}).call(this,require('_process'))
-},{"./common":46,"_process":69}],46:[function(require,module,exports){
-"use strict";
-
-/**
- * This is the common logic for both the Node.js and web browser
- * implementations of `debug()`.
- */
-function setup(env) {
- createDebug.debug = createDebug;
- createDebug.default = createDebug;
- createDebug.coerce = coerce;
- createDebug.disable = disable;
- createDebug.enable = enable;
- createDebug.enabled = enabled;
- createDebug.humanize = require('ms');
- Object.keys(env).forEach(function (key) {
- createDebug[key] = env[key];
- });
- /**
- * Active `debug` instances.
- */
-
- createDebug.instances = [];
- /**
- * The currently active debug mode names, and names to skip.
- */
-
- createDebug.names = [];
- createDebug.skips = [];
- /**
- * Map of special "%n" handling functions, for the debug "format" argument.
- *
- * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
- */
-
- createDebug.formatters = {};
- /**
- * Selects a color for a debug namespace
- * @param {String} namespace The namespace string for the for the debug instance to be colored
- * @return {Number|String} An ANSI color code for the given namespace
- * @api private
- */
-
- function selectColor(namespace) {
- var hash = 0;
-
- for (var i = 0; i < namespace.length; i++) {
- hash = (hash << 5) - hash + namespace.charCodeAt(i);
- hash |= 0; // Convert to 32bit integer
- }
-
- return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
- }
-
- createDebug.selectColor = selectColor;
- /**
- * Create a debugger with the given `namespace`.
- *
- * @param {String} namespace
- * @return {Function}
- * @api public
- */
-
- function createDebug(namespace) {
- var prevTime;
-
- function debug() {
- // Disabled?
- if (!debug.enabled) {
- return;
- }
-
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- var self = debug; // Set `diff` timestamp
-
- var curr = Number(new Date());
- var ms = curr - (prevTime || curr);
- self.diff = ms;
- self.prev = prevTime;
- self.curr = curr;
- prevTime = curr;
- args[0] = createDebug.coerce(args[0]);
-
- if (typeof args[0] !== 'string') {
- // Anything else let's inspect with %O
- args.unshift('%O');
- } // Apply any `formatters` transformations
-
-
- var index = 0;
- args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
- // If we encounter an escaped % then don't increase the array index
- if (match === '%%') {
- return match;
- }
-
- index++;
- var formatter = createDebug.formatters[format];
-
- if (typeof formatter === 'function') {
- var val = args[index];
- match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
-
- args.splice(index, 1);
- index--;
- }
-
- return match;
- }); // Apply env-specific formatting (colors, etc.)
-
- createDebug.formatArgs.call(self, args);
- var logFn = self.log || createDebug.log;
- logFn.apply(self, args);
- }
-
- debug.namespace = namespace;
- debug.enabled = createDebug.enabled(namespace);
- debug.useColors = createDebug.useColors();
- debug.color = selectColor(namespace);
- debug.destroy = destroy;
- debug.extend = extend; // Debug.formatArgs = formatArgs;
- // debug.rawLog = rawLog;
- // env-specific initialization logic for debug instances
-
- if (typeof createDebug.init === 'function') {
- createDebug.init(debug);
- }
-
- createDebug.instances.push(debug);
- return debug;
- }
-
- function destroy() {
- var index = createDebug.instances.indexOf(this);
-
- if (index !== -1) {
- createDebug.instances.splice(index, 1);
- return true;
- }
-
- return false;
- }
-
- function extend(namespace, delimiter) {
- return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
- }
- /**
- * Enables a debug mode by namespaces. This can include modes
- * separated by a colon and wildcards.
- *
- * @param {String} namespaces
- * @api public
- */
-
-
- function enable(namespaces) {
- createDebug.save(namespaces);
- createDebug.names = [];
- createDebug.skips = [];
- var i;
- var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
- var len = split.length;
-
- for (i = 0; i < len; i++) {
- if (!split[i]) {
- // ignore empty strings
- continue;
- }
-
- namespaces = split[i].replace(/\*/g, '.*?');
-
- if (namespaces[0] === '-') {
- createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
- } else {
- createDebug.names.push(new RegExp('^' + namespaces + '$'));
- }
- }
-
- for (i = 0; i < createDebug.instances.length; i++) {
- var instance = createDebug.instances[i];
- instance.enabled = createDebug.enabled(instance.namespace);
- }
- }
- /**
- * Disable debug output.
- *
- * @api public
- */
-
-
- function disable() {
- createDebug.enable('');
- }
- /**
- * Returns true if the given mode name is enabled, false otherwise.
- *
- * @param {String} name
- * @return {Boolean}
- * @api public
- */
-
-
- function enabled(name) {
- if (name[name.length - 1] === '*') {
- return true;
- }
-
- var i;
- var len;
-
- for (i = 0, len = createDebug.skips.length; i < len; i++) {
- if (createDebug.skips[i].test(name)) {
- return false;
- }
- }
-
- for (i = 0, len = createDebug.names.length; i < len; i++) {
- if (createDebug.names[i].test(name)) {
- return true;
- }
- }
-
- return false;
- }
- /**
- * Coerce `val`.
- *
- * @param {Mixed} val
- * @return {Mixed}
- * @api private
- */
-
-
- function coerce(val) {
- if (val instanceof Error) {
- return val.stack || val.message;
- }
-
- return val;
- }
-
- createDebug.enable(createDebug.load());
- return createDebug;
-}
-
-module.exports = setup;
-
-
-},{"ms":60}],47:[function(require,module,exports){
-'use strict';
-
-var keys = require('object-keys');
-var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
-
-var toStr = Object.prototype.toString;
-var concat = Array.prototype.concat;
-var origDefineProperty = Object.defineProperty;
-
-var isFunction = function (fn) {
- return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
-};
-
-var arePropertyDescriptorsSupported = function () {
- var obj = {};
- try {
- origDefineProperty(obj, 'x', { enumerable: false, value: obj });
- // eslint-disable-next-line no-unused-vars, no-restricted-syntax
- for (var _ in obj) { // jscs:ignore disallowUnusedVariables
- return false;
- }
- return obj.x === obj;
- } catch (e) { /* this is IE 8. */
- return false;
- }
-};
-var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();
-
-var defineProperty = function (object, name, value, predicate) {
- if (name in object && (!isFunction(predicate) || !predicate())) {
- return;
- }
- if (supportsDescriptors) {
- origDefineProperty(object, name, {
- configurable: true,
- enumerable: false,
- value: value,
- writable: true
- });
- } else {
- object[name] = value;
+// mocha@9.1.2 transpiled to javascript ES5
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+ typeof define === 'function' && define.amd ? define(factory) :
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.mocha = factory());
+})(this, (function () { 'use strict';
+
+ var regeneratorRuntime;
+
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
+
+ function createCommonjsModule(fn, basedir, module) {
+ return module = {
+ path: basedir,
+ exports: {},
+ require: function (path, base) {
+ return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
+ }
+ }, fn(module, module.exports), module.exports;
}
-};
-var defineProperties = function (object, map) {
- var predicates = arguments.length > 2 ? arguments[2] : {};
- var props = keys(map);
- if (hasSymbols) {
- props = concat.call(props, Object.getOwnPropertySymbols(map));
+ function getCjsExportFromNamespace (n) {
+ return n && n['default'] || n;
}
- for (var i = 0; i < props.length; i += 1) {
- defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
+
+ function commonjsRequire () {
+ throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
-};
-defineProperties.supportsDescriptors = !!supportsDescriptors;
+ var check = function (it) {
+ return it && it.Math == Math && it;
+ };
-module.exports = defineProperties;
+ // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
+ var global_1 =
+ // eslint-disable-next-line es/no-global-this -- safe
+ check(typeof globalThis == 'object' && globalThis) ||
+ check(typeof window == 'object' && window) ||
+ // eslint-disable-next-line no-restricted-globals -- safe
+ check(typeof self == 'object' && self) ||
+ check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
+ // eslint-disable-next-line no-new-func -- fallback
+ (function () { return this; })() || Function('return this')();
+
+ var fails = function (exec) {
+ try {
+ return !!exec();
+ } catch (error) {
+ return true;
+ }
+ };
-},{"object-keys":62}],48:[function(require,module,exports){
-/*!
+ // Detect IE8's incomplete defineProperty implementation
+ var descriptors = !fails(function () {
+ // eslint-disable-next-line es/no-object-defineproperty -- required for testing
+ return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
+ });
- diff v3.5.0
+ var $propertyIsEnumerable$1 = {}.propertyIsEnumerable;
+ // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
+ var getOwnPropertyDescriptor$3 = Object.getOwnPropertyDescriptor;
-Software License Agreement (BSD License)
+ // Nashorn ~ JDK8 bug
+ var NASHORN_BUG = getOwnPropertyDescriptor$3 && !$propertyIsEnumerable$1.call({ 1: 2 }, 1);
-Copyright (c) 2009-2015, Kevin Decker
+ // `Object.prototype.propertyIsEnumerable` method implementation
+ // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
+ var f$7 = NASHORN_BUG ? function propertyIsEnumerable(V) {
+ var descriptor = getOwnPropertyDescriptor$3(this, V);
+ return !!descriptor && descriptor.enumerable;
+ } : $propertyIsEnumerable$1;
-All rights reserved.
+ var objectPropertyIsEnumerable = {
+ f: f$7
+ };
-Redistribution and use of this software in source and binary forms, with or without modification,
-are permitted provided that the following conditions are met:
+ var createPropertyDescriptor = function (bitmap, value) {
+ return {
+ enumerable: !(bitmap & 1),
+ configurable: !(bitmap & 2),
+ writable: !(bitmap & 4),
+ value: value
+ };
+ };
-* Redistributions of source code must retain the above
- copyright notice, this list of conditions and the
- following disclaimer.
+ var toString$4 = {}.toString;
-* Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the
- following disclaimer in the documentation and/or other
- materials provided with the distribution.
+ var classofRaw = function (it) {
+ return toString$4.call(it).slice(8, -1);
+ };
-* Neither the name of Kevin Decker nor the names of its
- contributors may be used to endorse or promote products
- derived from this software without specific prior
- written permission.
+ var split = ''.split;
+
+ // fallback for non-array-like ES3 and non-enumerable old V8 strings
+ var indexedObject = fails(function () {
+ // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
+ // eslint-disable-next-line no-prototype-builtins -- safe
+ return !Object('z').propertyIsEnumerable(0);
+ }) ? function (it) {
+ return classofRaw(it) == 'String' ? split.call(it, '') : Object(it);
+ } : Object;
+
+ // `RequireObjectCoercible` abstract operation
+ // https://tc39.es/ecma262/#sec-requireobjectcoercible
+ var requireObjectCoercible = function (it) {
+ if (it == undefined) throw TypeError("Can't call method on " + it);
+ return it;
+ };
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
-IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
-IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-@license
-*/
-(function webpackUniversalModuleDefinition(root, factory) {
- if(typeof exports === 'object' && typeof module === 'object')
- module.exports = factory();
- else if(false)
- define([], factory);
- else if(typeof exports === 'object')
- exports["JsDiff"] = factory();
- else
- root["JsDiff"] = factory();
-})(this, function() {
-return /******/ (function(modules) { // webpackBootstrap
-/******/ // The module cache
-/******/ var installedModules = {};
+ // toObject with fallback for non-array-like ES3 strings
-/******/ // The require function
-/******/ function __webpack_require__(moduleId) {
-/******/ // Check if module is in cache
-/******/ if(installedModules[moduleId])
-/******/ return installedModules[moduleId].exports;
-/******/ // Create a new module (and put it into the cache)
-/******/ var module = installedModules[moduleId] = {
-/******/ exports: {},
-/******/ id: moduleId,
-/******/ loaded: false
-/******/ };
+ var toIndexedObject = function (it) {
+ return indexedObject(requireObjectCoercible(it));
+ };
-/******/ // Execute the module function
-/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+ // `isCallable` abstract operation
+ // https://tc39.es/ecma262/#sec-iscallable
+ var isCallable = function (argument) {
+ return typeof argument === 'function';
+ };
-/******/ // Flag the module as loaded
-/******/ module.loaded = true;
+ var isObject$1 = function (it) {
+ return typeof it === 'object' ? it !== null : isCallable(it);
+ };
-/******/ // Return the exports of the module
-/******/ return module.exports;
-/******/ }
+ var aFunction = function (argument) {
+ return isCallable(argument) ? argument : undefined;
+ };
+ var getBuiltIn = function (namespace, method) {
+ return arguments.length < 2 ? aFunction(global_1[namespace]) : global_1[namespace] && global_1[namespace][method];
+ };
-/******/ // expose the modules object (__webpack_modules__)
-/******/ __webpack_require__.m = modules;
+ var engineUserAgent = getBuiltIn('navigator', 'userAgent') || '';
+
+ var process$5 = global_1.process;
+ var Deno = global_1.Deno;
+ var versions$2 = process$5 && process$5.versions || Deno && Deno.version;
+ var v8 = versions$2 && versions$2.v8;
+ var match, version$3;
+
+ if (v8) {
+ match = v8.split('.');
+ version$3 = match[0] < 4 ? 1 : match[0] + match[1];
+ } else if (engineUserAgent) {
+ match = engineUserAgent.match(/Edge\/(\d+)/);
+ if (!match || match[1] >= 74) {
+ match = engineUserAgent.match(/Chrome\/(\d+)/);
+ if (match) version$3 = match[1];
+ }
+ }
-/******/ // expose the module cache
-/******/ __webpack_require__.c = installedModules;
+ var engineV8Version = version$3 && +version$3;
-/******/ // __webpack_public_path__
-/******/ __webpack_require__.p = "";
+ /* eslint-disable es/no-symbol -- required for testing */
-/******/ // Load entry module and return exports
-/******/ return __webpack_require__(0);
-/******/ })
-/************************************************************************/
-/******/ ([
-/* 0 */
-/***/ (function(module, exports, __webpack_require__) {
- /*istanbul ignore start*/'use strict';
- exports.__esModule = true;
- exports.canonicalize = exports.convertChangesToXML = exports.convertChangesToDMP = exports.merge = exports.parsePatch = exports.applyPatches = exports.applyPatch = exports.createPatch = exports.createTwoFilesPatch = exports.structuredPatch = exports.diffArrays = exports.diffJson = exports.diffCss = exports.diffSentences = exports.diffTrimmedLines = exports.diffLines = exports.diffWordsWithSpace = exports.diffWords = exports.diffChars = exports.Diff = undefined;
+ // eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
+ var nativeSymbol$1 = !!Object.getOwnPropertySymbols && !fails(function () {
+ var symbol = Symbol();
+ // Chrome 38 Symbol has incorrect toString conversion
+ // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
+ return !String(symbol) || !(Object(symbol) instanceof Symbol) ||
+ // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
+ !Symbol.sham && engineV8Version && engineV8Version < 41;
+ });
- /*istanbul ignore end*/var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
+ /* eslint-disable es/no-symbol -- required for testing */
- /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
- /*istanbul ignore end*/var /*istanbul ignore start*/_character = __webpack_require__(2) /*istanbul ignore end*/;
+ var useSymbolAsUid = nativeSymbol$1
+ && !Symbol.sham
+ && typeof Symbol.iterator == 'symbol';
- var /*istanbul ignore start*/_word = __webpack_require__(3) /*istanbul ignore end*/;
+ var isSymbol$1 = useSymbolAsUid ? function (it) {
+ return typeof it == 'symbol';
+ } : function (it) {
+ var $Symbol = getBuiltIn('Symbol');
+ return isCallable($Symbol) && Object(it) instanceof $Symbol;
+ };
- var /*istanbul ignore start*/_line = __webpack_require__(5) /*istanbul ignore end*/;
+ var tryToString = function (argument) {
+ try {
+ return String(argument);
+ } catch (error) {
+ return 'Object';
+ }
+ };
- var /*istanbul ignore start*/_sentence = __webpack_require__(6) /*istanbul ignore end*/;
+ // `Assert: IsCallable(argument) is true`
+ var aCallable = function (argument) {
+ if (isCallable(argument)) return argument;
+ throw TypeError(tryToString(argument) + ' is not a function');
+ };
- var /*istanbul ignore start*/_css = __webpack_require__(7) /*istanbul ignore end*/;
+ // `GetMethod` abstract operation
+ // https://tc39.es/ecma262/#sec-getmethod
+ var getMethod = function (V, P) {
+ var func = V[P];
+ return func == null ? undefined : aCallable(func);
+ };
- var /*istanbul ignore start*/_json = __webpack_require__(8) /*istanbul ignore end*/;
+ // `OrdinaryToPrimitive` abstract operation
+ // https://tc39.es/ecma262/#sec-ordinarytoprimitive
+ var ordinaryToPrimitive = function (input, pref) {
+ var fn, val;
+ if (pref === 'string' && isCallable(fn = input.toString) && !isObject$1(val = fn.call(input))) return val;
+ if (isCallable(fn = input.valueOf) && !isObject$1(val = fn.call(input))) return val;
+ if (pref !== 'string' && isCallable(fn = input.toString) && !isObject$1(val = fn.call(input))) return val;
+ throw TypeError("Can't convert object to primitive value");
+ };
- var /*istanbul ignore start*/_array = __webpack_require__(9) /*istanbul ignore end*/;
+ var setGlobal = function (key, value) {
+ try {
+ // eslint-disable-next-line es/no-object-defineproperty -- safe
+ Object.defineProperty(global_1, key, { value: value, configurable: true, writable: true });
+ } catch (error) {
+ global_1[key] = value;
+ } return value;
+ };
- var /*istanbul ignore start*/_apply = __webpack_require__(10) /*istanbul ignore end*/;
+ var SHARED = '__core-js_shared__';
+ var store$1 = global_1[SHARED] || setGlobal(SHARED, {});
+
+ var sharedStore = store$1;
+
+ var shared = createCommonjsModule(function (module) {
+ (module.exports = function (key, value) {
+ return sharedStore[key] || (sharedStore[key] = value !== undefined ? value : {});
+ })('versions', []).push({
+ version: '3.18.0',
+ mode: 'global',
+ copyright: '© 2021 Denis Pushkarev (zloirock.ru)'
+ });
+ });
+
+ // `ToObject` abstract operation
+ // https://tc39.es/ecma262/#sec-toobject
+ var toObject = function (argument) {
+ return Object(requireObjectCoercible(argument));
+ };
- var /*istanbul ignore start*/_parse = __webpack_require__(11) /*istanbul ignore end*/;
+ var hasOwnProperty$1 = {}.hasOwnProperty;
- var /*istanbul ignore start*/_merge = __webpack_require__(13) /*istanbul ignore end*/;
+ var has$1 = Object.hasOwn || function hasOwn(it, key) {
+ return hasOwnProperty$1.call(toObject(it), key);
+ };
- var /*istanbul ignore start*/_create = __webpack_require__(14) /*istanbul ignore end*/;
+ var id = 0;
+ var postfix = Math.random();
- var /*istanbul ignore start*/_dmp = __webpack_require__(16) /*istanbul ignore end*/;
+ var uid = function (key) {
+ return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
+ };
- var /*istanbul ignore start*/_xml = __webpack_require__(17) /*istanbul ignore end*/;
+ var WellKnownSymbolsStore$1 = shared('wks');
+ var Symbol$1 = global_1.Symbol;
+ var createWellKnownSymbol = useSymbolAsUid ? Symbol$1 : Symbol$1 && Symbol$1.withoutSetter || uid;
- /*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+ var wellKnownSymbol = function (name) {
+ if (!has$1(WellKnownSymbolsStore$1, name) || !(nativeSymbol$1 || typeof WellKnownSymbolsStore$1[name] == 'string')) {
+ if (nativeSymbol$1 && has$1(Symbol$1, name)) {
+ WellKnownSymbolsStore$1[name] = Symbol$1[name];
+ } else {
+ WellKnownSymbolsStore$1[name] = createWellKnownSymbol('Symbol.' + name);
+ }
+ } return WellKnownSymbolsStore$1[name];
+ };
- /* See LICENSE file for terms of use */
+ var TO_PRIMITIVE$1 = wellKnownSymbol('toPrimitive');
+
+ // `ToPrimitive` abstract operation
+ // https://tc39.es/ecma262/#sec-toprimitive
+ var toPrimitive = function (input, pref) {
+ if (!isObject$1(input) || isSymbol$1(input)) return input;
+ var exoticToPrim = getMethod(input, TO_PRIMITIVE$1);
+ var result;
+ if (exoticToPrim) {
+ if (pref === undefined) pref = 'default';
+ result = exoticToPrim.call(input, pref);
+ if (!isObject$1(result) || isSymbol$1(result)) return result;
+ throw TypeError("Can't convert object to primitive value");
+ }
+ if (pref === undefined) pref = 'number';
+ return ordinaryToPrimitive(input, pref);
+ };
- /*
- * Text diff implementation.
- *
- * This library supports the following APIS:
- * JsDiff.diffChars: Character by character diff
- * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
- * JsDiff.diffLines: Line based diff
- *
- * JsDiff.diffCss: Diff targeted at CSS content
- *
- * These methods are based on the implementation proposed in
- * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
- * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
- */
- exports. /*istanbul ignore end*/Diff = _base2['default'];
- /*istanbul ignore start*/exports. /*istanbul ignore end*/diffChars = _character.diffChars;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWords = _word.diffWords;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = _word.diffWordsWithSpace;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/diffLines = _line.diffLines;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = _line.diffTrimmedLines;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/diffSentences = _sentence.diffSentences;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/diffCss = _css.diffCss;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/diffJson = _json.diffJson;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/diffArrays = _array.diffArrays;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/structuredPatch = _create.structuredPatch;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = _create.createTwoFilesPatch;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = _create.createPatch;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatch = _apply.applyPatch;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = _apply.applyPatches;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/parsePatch = _parse.parsePatch;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/merge = _merge.merge;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToDMP = _dmp.convertChangesToDMP;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToXML = _xml.convertChangesToXML;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = _json.canonicalize;
-
-
-
-/***/ }),
-/* 1 */
-/***/ (function(module, exports) {
-
- /*istanbul ignore start*/'use strict';
-
- exports.__esModule = true;
- exports['default'] = /*istanbul ignore end*/Diff;
- function Diff() {}
-
- Diff.prototype = {
- /*istanbul ignore start*/ /*istanbul ignore end*/diff: function diff(oldString, newString) {
- /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
-
- var callback = options.callback;
- if (typeof options === 'function') {
- callback = options;
- options = {};
- }
- this.options = options;
+ // `ToPropertyKey` abstract operation
+ // https://tc39.es/ecma262/#sec-topropertykey
+ var toPropertyKey = function (argument) {
+ var key = toPrimitive(argument, 'string');
+ return isSymbol$1(key) ? key : String(key);
+ };
- var self = this;
+ var document$3 = global_1.document;
+ // typeof document.createElement is 'object' in old IE
+ var EXISTS$1 = isObject$1(document$3) && isObject$1(document$3.createElement);
- function done(value) {
- if (callback) {
- setTimeout(function () {
- callback(undefined, value);
- }, 0);
- return true;
- } else {
- return value;
- }
- }
+ var documentCreateElement = function (it) {
+ return EXISTS$1 ? document$3.createElement(it) : {};
+ };
- // Allow subclasses to massage the input prior to running
- oldString = this.castInput(oldString);
- newString = this.castInput(newString);
-
- oldString = this.removeEmpty(this.tokenize(oldString));
- newString = this.removeEmpty(this.tokenize(newString));
-
- var newLen = newString.length,
- oldLen = oldString.length;
- var editLength = 1;
- var maxEditLength = newLen + oldLen;
- var bestPath = [{ newPos: -1, components: [] }];
-
- // Seed editLength = 0, i.e. the content starts with the same values
- var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
- if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
- // Identity per the equality and tokenizer
- return done([{ value: this.join(newString), count: newString.length }]);
- }
-
- // Main worker method. checks all permutations of a given edit length for acceptance.
- function execEditLength() {
- for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
- var basePath = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
- var addPath = bestPath[diagonalPath - 1],
- removePath = bestPath[diagonalPath + 1],
- _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
- if (addPath) {
- // No one else is going to attempt to use this value, clear it
- bestPath[diagonalPath - 1] = undefined;
- }
+ // Thank's IE8 for his funny defineProperty
+ var ie8DomDefine = !descriptors && !fails(function () {
+ // eslint-disable-next-line es/no-object-defineproperty -- requied for testing
+ return Object.defineProperty(documentCreateElement('div'), 'a', {
+ get: function () { return 7; }
+ }).a != 7;
+ });
+
+ // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
+ var $getOwnPropertyDescriptor$1 = Object.getOwnPropertyDescriptor;
+
+ // `Object.getOwnPropertyDescriptor` method
+ // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
+ var f$6 = descriptors ? $getOwnPropertyDescriptor$1 : function getOwnPropertyDescriptor(O, P) {
+ O = toIndexedObject(O);
+ P = toPropertyKey(P);
+ if (ie8DomDefine) try {
+ return $getOwnPropertyDescriptor$1(O, P);
+ } catch (error) { /* empty */ }
+ if (has$1(O, P)) return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]);
+ };
- var canAdd = addPath && addPath.newPos + 1 < newLen,
- canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
- if (!canAdd && !canRemove) {
- // If this path is a terminal then prune
- bestPath[diagonalPath] = undefined;
- continue;
- }
+ var objectGetOwnPropertyDescriptor = {
+ f: f$6
+ };
- // Select the diagonal that we want to branch from. We select the prior
- // path whose position in the new string is the farthest from the origin
- // and does not pass the bounds of the diff graph
- if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
- basePath = clonePath(removePath);
- self.pushComponent(basePath.components, undefined, true);
- } else {
- basePath = addPath; // No need to clone, we've pulled it from the list
- basePath.newPos++;
- self.pushComponent(basePath.components, true, undefined);
- }
+ // `Assert: Type(argument) is Object`
+ var anObject = function (argument) {
+ if (isObject$1(argument)) return argument;
+ throw TypeError(String(argument) + ' is not an object');
+ };
- _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
+ // eslint-disable-next-line es/no-object-defineproperty -- safe
+ var $defineProperty$1 = Object.defineProperty;
+
+ // `Object.defineProperty` method
+ // https://tc39.es/ecma262/#sec-object.defineproperty
+ var f$5 = descriptors ? $defineProperty$1 : function defineProperty(O, P, Attributes) {
+ anObject(O);
+ P = toPropertyKey(P);
+ anObject(Attributes);
+ if (ie8DomDefine) try {
+ return $defineProperty$1(O, P, Attributes);
+ } catch (error) { /* empty */ }
+ if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
+ if ('value' in Attributes) O[P] = Attributes.value;
+ return O;
+ };
- // If we have hit the end of both strings, then we are done
- if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
- return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
- } else {
- // Otherwise track this path as a potential candidate and continue.
- bestPath[diagonalPath] = basePath;
- }
- }
+ var objectDefineProperty = {
+ f: f$5
+ };
- editLength++;
- }
+ var createNonEnumerableProperty = descriptors ? function (object, key, value) {
+ return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value));
+ } : function (object, key, value) {
+ object[key] = value;
+ return object;
+ };
- // Performs the length of edit iteration. Is a bit fugly as this has to support the
- // sync and async mode which is never fun. Loops over execEditLength until a value
- // is produced.
- if (callback) {
- (function exec() {
- setTimeout(function () {
- // This should not happen, but we want to be safe.
- /* istanbul ignore next */
- if (editLength > maxEditLength) {
- return callback();
- }
+ var functionToString = Function.toString;
- if (!execEditLength()) {
- exec();
- }
- }, 0);
- })();
- } else {
- while (editLength <= maxEditLength) {
- var ret = execEditLength();
- if (ret) {
- return ret;
- }
- }
- }
- },
- /*istanbul ignore start*/ /*istanbul ignore end*/pushComponent: function pushComponent(components, added, removed) {
- var last = components[components.length - 1];
- if (last && last.added === added && last.removed === removed) {
- // We need to clone here as the component clone operation is just
- // as shallow array clone
- components[components.length - 1] = { count: last.count + 1, added: added, removed: removed };
- } else {
- components.push({ count: 1, added: added, removed: removed });
- }
- },
- /*istanbul ignore start*/ /*istanbul ignore end*/extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
- var newLen = newString.length,
- oldLen = oldString.length,
- newPos = basePath.newPos,
- oldPos = newPos - diagonalPath,
- commonCount = 0;
- while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
- newPos++;
- oldPos++;
- commonCount++;
- }
+ // this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
+ if (!isCallable(sharedStore.inspectSource)) {
+ sharedStore.inspectSource = function (it) {
+ return functionToString.call(it);
+ };
+ }
- if (commonCount) {
- basePath.components.push({ count: commonCount });
- }
+ var inspectSource = sharedStore.inspectSource;
- basePath.newPos = newPos;
- return oldPos;
- },
- /*istanbul ignore start*/ /*istanbul ignore end*/equals: function equals(left, right) {
- if (this.options.comparator) {
- return this.options.comparator(left, right);
- } else {
- return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
- }
- },
- /*istanbul ignore start*/ /*istanbul ignore end*/removeEmpty: function removeEmpty(array) {
- var ret = [];
- for (var i = 0; i < array.length; i++) {
- if (array[i]) {
- ret.push(array[i]);
- }
- }
- return ret;
- },
- /*istanbul ignore start*/ /*istanbul ignore end*/castInput: function castInput(value) {
- return value;
- },
- /*istanbul ignore start*/ /*istanbul ignore end*/tokenize: function tokenize(value) {
- return value.split('');
- },
- /*istanbul ignore start*/ /*istanbul ignore end*/join: function join(chars) {
- return chars.join('');
- }
- };
+ var WeakMap$1 = global_1.WeakMap;
- function buildValues(diff, components, newString, oldString, useLongestToken) {
- var componentPos = 0,
- componentLen = components.length,
- newPos = 0,
- oldPos = 0;
+ var nativeWeakMap = isCallable(WeakMap$1) && /native code/.test(inspectSource(WeakMap$1));
- for (; componentPos < componentLen; componentPos++) {
- var component = components[componentPos];
- if (!component.removed) {
- if (!component.added && useLongestToken) {
- var value = newString.slice(newPos, newPos + component.count);
- value = value.map(function (value, i) {
- var oldValue = oldString[oldPos + i];
- return oldValue.length > value.length ? oldValue : value;
- });
+ var keys$4 = shared('keys');
- component.value = diff.join(value);
- } else {
- component.value = diff.join(newString.slice(newPos, newPos + component.count));
- }
- newPos += component.count;
+ var sharedKey = function (key) {
+ return keys$4[key] || (keys$4[key] = uid(key));
+ };
- // Common case
- if (!component.added) {
- oldPos += component.count;
- }
- } else {
- component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
- oldPos += component.count;
-
- // Reverse add and remove so removes are output first to match common convention
- // The diffing algorithm is tied to add then remove output and this is the simplest
- // route to get the desired output with minimal overhead.
- if (componentPos && components[componentPos - 1].added) {
- var tmp = components[componentPos - 1];
- components[componentPos - 1] = components[componentPos];
- components[componentPos] = tmp;
- }
- }
- }
+ var hiddenKeys$1 = {};
- // Special case handle for when one terminal is ignored (i.e. whitespace).
- // For this case we merge the terminal into the prior string and drop the change.
- // This is only available for string mode.
- var lastComponent = components[componentLen - 1];
- if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
- components[componentLen - 2].value += lastComponent.value;
- components.pop();
- }
+ var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
+ var WeakMap = global_1.WeakMap;
+ var set$2, get$1, has;
- return components;
- }
+ var enforce = function (it) {
+ return has(it) ? get$1(it) : set$2(it, {});
+ };
+
+ var getterFor = function (TYPE) {
+ return function (it) {
+ var state;
+ if (!isObject$1(it) || (state = get$1(it)).type !== TYPE) {
+ throw TypeError('Incompatible receiver, ' + TYPE + ' required');
+ } return state;
+ };
+ };
- function clonePath(path) {
- return { newPos: path.newPos, components: path.components.slice(0) };
+ if (nativeWeakMap || sharedStore.state) {
+ var store = sharedStore.state || (sharedStore.state = new WeakMap());
+ var wmget = store.get;
+ var wmhas = store.has;
+ var wmset = store.set;
+ set$2 = function (it, metadata) {
+ if (wmhas.call(store, it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
+ metadata.facade = it;
+ wmset.call(store, it, metadata);
+ return metadata;
+ };
+ get$1 = function (it) {
+ return wmget.call(store, it) || {};
+ };
+ has = function (it) {
+ return wmhas.call(store, it);
+ };
+ } else {
+ var STATE = sharedKey('state');
+ hiddenKeys$1[STATE] = true;
+ set$2 = function (it, metadata) {
+ if (has$1(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
+ metadata.facade = it;
+ createNonEnumerableProperty(it, STATE, metadata);
+ return metadata;
+ };
+ get$1 = function (it) {
+ return has$1(it, STATE) ? it[STATE] : {};
+ };
+ has = function (it) {
+ return has$1(it, STATE);
+ };
}
+ var internalState = {
+ set: set$2,
+ get: get$1,
+ has: has,
+ enforce: enforce,
+ getterFor: getterFor
+ };
+
+ var FunctionPrototype$1 = Function.prototype;
+ // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
+ var getDescriptor = descriptors && Object.getOwnPropertyDescriptor;
+ var EXISTS = has$1(FunctionPrototype$1, 'name');
+ // additional protection from minified / mangled / dropped function names
+ var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
+ var CONFIGURABLE = EXISTS && (!descriptors || (descriptors && getDescriptor(FunctionPrototype$1, 'name').configurable));
-/***/ }),
-/* 2 */
-/***/ (function(module, exports, __webpack_require__) {
+ var functionName = {
+ EXISTS: EXISTS,
+ PROPER: PROPER,
+ CONFIGURABLE: CONFIGURABLE
+ };
- /*istanbul ignore start*/'use strict';
+ var redefine = createCommonjsModule(function (module) {
+ var CONFIGURABLE_FUNCTION_NAME = functionName.CONFIGURABLE;
+
+ var getInternalState = internalState.get;
+ var enforceInternalState = internalState.enforce;
+ var TEMPLATE = String(String).split('String');
+
+ (module.exports = function (O, key, value, options) {
+ var unsafe = options ? !!options.unsafe : false;
+ var simple = options ? !!options.enumerable : false;
+ var noTargetGet = options ? !!options.noTargetGet : false;
+ var name = options && options.name !== undefined ? options.name : key;
+ var state;
+ if (isCallable(value)) {
+ if (String(name).slice(0, 7) === 'Symbol(') {
+ name = '[' + String(name).replace(/^Symbol\(([^)]*)\)/, '$1') + ']';
+ }
+ if (!has$1(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
+ createNonEnumerableProperty(value, 'name', name);
+ }
+ state = enforceInternalState(value);
+ if (!state.source) {
+ state.source = TEMPLATE.join(typeof name == 'string' ? name : '');
+ }
+ }
+ if (O === global_1) {
+ if (simple) O[key] = value;
+ else setGlobal(key, value);
+ return;
+ } else if (!unsafe) {
+ delete O[key];
+ } else if (!noTargetGet && O[key]) {
+ simple = true;
+ }
+ if (simple) O[key] = value;
+ else createNonEnumerableProperty(O, key, value);
+ // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
+ })(Function.prototype, 'toString', function toString() {
+ return isCallable(this) && getInternalState(this).source || inspectSource(this);
+ });
+ });
+
+ var ceil = Math.ceil;
+ var floor$6 = Math.floor;
+
+ // `ToInteger` abstract operation
+ // https://tc39.es/ecma262/#sec-tointeger
+ var toInteger = function (argument) {
+ return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor$6 : ceil)(argument);
+ };
- exports.__esModule = true;
- exports.characterDiff = undefined;
- exports. /*istanbul ignore end*/diffChars = diffChars;
+ var min$7 = Math.min;
- var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
+ // `ToLength` abstract operation
+ // https://tc39.es/ecma262/#sec-tolength
+ var toLength = function (argument) {
+ return argument > 0 ? min$7(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
+ };
- /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+ var max$3 = Math.max;
+ var min$6 = Math.min;
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+ // Helper for a popular repeating case of the spec:
+ // Let integer be ? ToInteger(index).
+ // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
+ var toAbsoluteIndex = function (index, length) {
+ var integer = toInteger(index);
+ return integer < 0 ? max$3(integer + length, 0) : min$6(integer, length);
+ };
- /*istanbul ignore end*/var characterDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/characterDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
- function diffChars(oldStr, newStr, options) {
- return characterDiff.diff(oldStr, newStr, options);
- }
+ // `Array.prototype.{ indexOf, includes }` methods implementation
+ var createMethod$5 = function (IS_INCLUDES) {
+ return function ($this, el, fromIndex) {
+ var O = toIndexedObject($this);
+ var length = toLength(O.length);
+ var index = toAbsoluteIndex(fromIndex, length);
+ var value;
+ // Array#includes uses SameValueZero equality algorithm
+ // eslint-disable-next-line no-self-compare -- NaN check
+ if (IS_INCLUDES && el != el) while (length > index) {
+ value = O[index++];
+ // eslint-disable-next-line no-self-compare -- NaN check
+ if (value != value) return true;
+ // Array#indexOf ignores holes, Array#includes - not
+ } else for (;length > index; index++) {
+ if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
+ } return !IS_INCLUDES && -1;
+ };
+ };
+ var arrayIncludes = {
+ // `Array.prototype.includes` method
+ // https://tc39.es/ecma262/#sec-array.prototype.includes
+ includes: createMethod$5(true),
+ // `Array.prototype.indexOf` method
+ // https://tc39.es/ecma262/#sec-array.prototype.indexof
+ indexOf: createMethod$5(false)
+ };
+ var indexOf$1 = arrayIncludes.indexOf;
-/***/ }),
-/* 3 */
-/***/ (function(module, exports, __webpack_require__) {
- /*istanbul ignore start*/'use strict';
+ var objectKeysInternal = function (object, names) {
+ var O = toIndexedObject(object);
+ var i = 0;
+ var result = [];
+ var key;
+ for (key in O) !has$1(hiddenKeys$1, key) && has$1(O, key) && result.push(key);
+ // Don't enum bug & hidden keys
+ while (names.length > i) if (has$1(O, key = names[i++])) {
+ ~indexOf$1(result, key) || result.push(key);
+ }
+ return result;
+ };
- exports.__esModule = true;
- exports.wordDiff = undefined;
- exports. /*istanbul ignore end*/diffWords = diffWords;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = diffWordsWithSpace;
+ // IE8- don't enum bug keys
+ var enumBugKeys = [
+ 'constructor',
+ 'hasOwnProperty',
+ 'isPrototypeOf',
+ 'propertyIsEnumerable',
+ 'toLocaleString',
+ 'toString',
+ 'valueOf'
+ ];
- var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
+ var hiddenKeys = enumBugKeys.concat('length', 'prototype');
- /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+ // `Object.getOwnPropertyNames` method
+ // https://tc39.es/ecma262/#sec-object.getownpropertynames
+ // eslint-disable-next-line es/no-object-getownpropertynames -- safe
+ var f$4 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
+ return objectKeysInternal(O, hiddenKeys);
+ };
- /*istanbul ignore end*/var /*istanbul ignore start*/_params = __webpack_require__(4) /*istanbul ignore end*/;
+ var objectGetOwnPropertyNames = {
+ f: f$4
+ };
- /*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+ // eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
+ var f$3 = Object.getOwnPropertySymbols;
- /*istanbul ignore end*/ // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode
- //
- // Ranges and exceptions:
- // Latin-1 Supplement, 0080–00FF
- // - U+00D7 × Multiplication sign
- // - U+00F7 ÷ Division sign
- // Latin Extended-A, 0100–017F
- // Latin Extended-B, 0180–024F
- // IPA Extensions, 0250–02AF
- // Spacing Modifier Letters, 02B0–02FF
- // - U+02C7 ˇ ˇ Caron
- // - U+02D8 ˘ ˘ Breve
- // - U+02D9 ˙ ˙ Dot Above
- // - U+02DA ˚ ˚ Ring Above
- // - U+02DB ˛ ˛ Ogonek
- // - U+02DC ˜ ˜ Small Tilde
- // - U+02DD ˝ ˝ Double Acute Accent
- // Latin Extended Additional, 1E00–1EFF
- var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
+ var objectGetOwnPropertySymbols = {
+ f: f$3
+ };
- var reWhitespace = /\S/;
+ // all object keys, includes non-enumerable and symbols
+ var ownKeys$1 = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
+ var keys = objectGetOwnPropertyNames.f(anObject(it));
+ var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
+ return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
+ };
- var wordDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/wordDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
- wordDiff.equals = function (left, right) {
- if (this.options.ignoreCase) {
- left = left.toLowerCase();
- right = right.toLowerCase();
+ var copyConstructorProperties = function (target, source) {
+ var keys = ownKeys$1(source);
+ var defineProperty = objectDefineProperty.f;
+ var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
+ for (var i = 0; i < keys.length; i++) {
+ var key = keys[i];
+ if (!has$1(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
}
- return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
};
- wordDiff.tokenize = function (value) {
- var tokens = value.split(/(\s+|\b)/);
- // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
- for (var i = 0; i < tokens.length - 1; i++) {
- // If we have an empty string in the next field and we have only word chars before and after, merge
- if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
- tokens[i] += tokens[i + 2];
- tokens.splice(i + 1, 2);
- i--;
- }
- }
+ var replacement = /#|\.prototype\./;
- return tokens;
+ var isForced = function (feature, detection) {
+ var value = data[normalize$1(feature)];
+ return value == POLYFILL ? true
+ : value == NATIVE ? false
+ : isCallable(detection) ? fails(detection)
+ : !!detection;
};
- function diffWords(oldStr, newStr, options) {
- options = /*istanbul ignore start*/(0, _params.generateOptions) /*istanbul ignore end*/(options, { ignoreWhitespace: true });
- return wordDiff.diff(oldStr, newStr, options);
- }
+ var normalize$1 = isForced.normalize = function (string) {
+ return String(string).replace(replacement, '.').toLowerCase();
+ };
- function diffWordsWithSpace(oldStr, newStr, options) {
- return wordDiff.diff(oldStr, newStr, options);
- }
+ var data = isForced.data = {};
+ var NATIVE = isForced.NATIVE = 'N';
+ var POLYFILL = isForced.POLYFILL = 'P';
+ var isForced_1 = isForced;
+ var getOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f;
-/***/ }),
-/* 4 */
-/***/ (function(module, exports) {
- /*istanbul ignore start*/'use strict';
- exports.__esModule = true;
- exports. /*istanbul ignore end*/generateOptions = generateOptions;
- function generateOptions(options, defaults) {
- if (typeof options === 'function') {
- defaults.callback = options;
- } else if (options) {
- for (var name in options) {
- /* istanbul ignore else */
- if (options.hasOwnProperty(name)) {
- defaults[name] = options[name];
- }
+
+
+
+ /*
+ options.target - name of the target object
+ options.global - target is the global object
+ options.stat - export as static methods of target
+ options.proto - export as prototype methods of target
+ options.real - real prototype method for the `pure` version
+ options.forced - export even if the native feature is available
+ options.bind - bind methods to the target, required for the `pure` version
+ options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
+ options.unsafe - use the simple assignment of property instead of delete + defineProperty
+ options.sham - add a flag to not completely full polyfills
+ options.enumerable - export as enumerable property
+ options.noTargetGet - prevent calling a getter on target
+ options.name - the .name of the function if it does not match the key
+ */
+ var _export = function (options, source) {
+ var TARGET = options.target;
+ var GLOBAL = options.global;
+ var STATIC = options.stat;
+ var FORCED, target, key, targetProperty, sourceProperty, descriptor;
+ if (GLOBAL) {
+ target = global_1;
+ } else if (STATIC) {
+ target = global_1[TARGET] || setGlobal(TARGET, {});
+ } else {
+ target = (global_1[TARGET] || {}).prototype;
+ }
+ if (target) for (key in source) {
+ sourceProperty = source[key];
+ if (options.noTargetGet) {
+ descriptor = getOwnPropertyDescriptor$2(target, key);
+ targetProperty = descriptor && descriptor.value;
+ } else targetProperty = target[key];
+ FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
+ // contained in target
+ if (!FORCED && targetProperty !== undefined) {
+ if (typeof sourceProperty === typeof targetProperty) continue;
+ copyConstructorProperties(sourceProperty, targetProperty);
}
+ // add a flag to not completely full polyfills
+ if (options.sham || (targetProperty && targetProperty.sham)) {
+ createNonEnumerableProperty(sourceProperty, 'sham', true);
+ }
+ // extend global
+ redefine(target, key, sourceProperty, options);
}
- return defaults;
- }
+ };
+ // `IsArray` abstract operation
+ // https://tc39.es/ecma262/#sec-isarray
+ // eslint-disable-next-line es/no-array-isarray -- safe
+ var isArray$3 = Array.isArray || function isArray(argument) {
+ return classofRaw(argument) == 'Array';
+ };
+ var TO_STRING_TAG$4 = wellKnownSymbol('toStringTag');
+ var test$2 = {};
-/***/ }),
-/* 5 */
-/***/ (function(module, exports, __webpack_require__) {
+ test$2[TO_STRING_TAG$4] = 'z';
- /*istanbul ignore start*/'use strict';
+ var toStringTagSupport = String(test$2) === '[object z]';
- exports.__esModule = true;
- exports.lineDiff = undefined;
- exports. /*istanbul ignore end*/diffLines = diffLines;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = diffTrimmedLines;
+ var TO_STRING_TAG$3 = wellKnownSymbol('toStringTag');
+ // ES3 wrong here
+ var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';
- var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
+ // fallback for IE11 Script Access Denied error
+ var tryGet = function (it, key) {
+ try {
+ return it[key];
+ } catch (error) { /* empty */ }
+ };
- /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+ // getting tag from ES6+ `Object.prototype.toString`
+ var classof = toStringTagSupport ? classofRaw : function (it) {
+ var O, tag, result;
+ return it === undefined ? 'Undefined' : it === null ? 'Null'
+ // @@toStringTag case
+ : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG$3)) == 'string' ? tag
+ // builtinTag case
+ : CORRECT_ARGUMENTS ? classofRaw(O)
+ // ES3 arguments fallback
+ : (result = classofRaw(O)) == 'Object' && isCallable(O.callee) ? 'Arguments' : result;
+ };
- /*istanbul ignore end*/var /*istanbul ignore start*/_params = __webpack_require__(4) /*istanbul ignore end*/;
+ var empty = [];
+ var construct = getBuiltIn('Reflect', 'construct');
+ var constructorRegExp = /^\s*(?:class|function)\b/;
+ var exec = constructorRegExp.exec;
+ var INCORRECT_TO_STRING = !constructorRegExp.exec(function () { /* empty */ });
- /*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+ var isConstructorModern = function (argument) {
+ if (!isCallable(argument)) return false;
+ try {
+ construct(Object, empty, argument);
+ return true;
+ } catch (error) {
+ return false;
+ }
+ };
- /*istanbul ignore end*/var lineDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/lineDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
- lineDiff.tokenize = function (value) {
- var retLines = [],
- linesAndNewlines = value.split(/(\n|\r\n)/);
+ var isConstructorLegacy = function (argument) {
+ if (!isCallable(argument)) return false;
+ switch (classof(argument)) {
+ case 'AsyncFunction':
+ case 'GeneratorFunction':
+ case 'AsyncGeneratorFunction': return false;
+ // we can't check .prototype since constructors produced by .bind haven't it
+ } return INCORRECT_TO_STRING || !!exec.call(constructorRegExp, inspectSource(argument));
+ };
- // Ignore the final empty token that occurs if the string ends with a new line
- if (!linesAndNewlines[linesAndNewlines.length - 1]) {
- linesAndNewlines.pop();
- }
+ // `IsConstructor` abstract operation
+ // https://tc39.es/ecma262/#sec-isconstructor
+ var isConstructor = !construct || fails(function () {
+ var called;
+ return isConstructorModern(isConstructorModern.call)
+ || !isConstructorModern(Object)
+ || !isConstructorModern(function () { called = true; })
+ || called;
+ }) ? isConstructorLegacy : isConstructorModern;
+
+ var SPECIES$6 = wellKnownSymbol('species');
+
+ // a part of `ArraySpeciesCreate` abstract operation
+ // https://tc39.es/ecma262/#sec-arrayspeciescreate
+ var arraySpeciesConstructor = function (originalArray) {
+ var C;
+ if (isArray$3(originalArray)) {
+ C = originalArray.constructor;
+ // cross-realm fallback
+ if (isConstructor(C) && (C === Array || isArray$3(C.prototype))) C = undefined;
+ else if (isObject$1(C)) {
+ C = C[SPECIES$6];
+ if (C === null) C = undefined;
+ }
+ } return C === undefined ? Array : C;
+ };
+
+ // `ArraySpeciesCreate` abstract operation
+ // https://tc39.es/ecma262/#sec-arrayspeciescreate
+ var arraySpeciesCreate = function (originalArray, length) {
+ return new (arraySpeciesConstructor(originalArray))(length === 0 ? 0 : length);
+ };
- // Merge the content and line separators into single tokens
- for (var i = 0; i < linesAndNewlines.length; i++) {
- var line = linesAndNewlines[i];
+ var createProperty = function (object, key, value) {
+ var propertyKey = toPropertyKey(key);
+ if (propertyKey in object) objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value));
+ else object[propertyKey] = value;
+ };
+
+ var SPECIES$5 = wellKnownSymbol('species');
+
+ var arrayMethodHasSpeciesSupport = function (METHOD_NAME) {
+ // We can't use this feature detection in V8 since it causes
+ // deoptimization and serious performance degradation
+ // https://github.com/zloirock/core-js/issues/677
+ return engineV8Version >= 51 || !fails(function () {
+ var array = [];
+ var constructor = array.constructor = {};
+ constructor[SPECIES$5] = function () {
+ return { foo: 1 };
+ };
+ return array[METHOD_NAME](Boolean).foo !== 1;
+ });
+ };
- if (i % 2 && !this.options.newlineIsToken) {
- retLines[retLines.length - 1] += line;
+ var HAS_SPECIES_SUPPORT$3 = arrayMethodHasSpeciesSupport('splice');
+
+ var max$2 = Math.max;
+ var min$5 = Math.min;
+ var MAX_SAFE_INTEGER$1 = 0x1FFFFFFFFFFFFF;
+ var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded';
+
+ // `Array.prototype.splice` method
+ // https://tc39.es/ecma262/#sec-array.prototype.splice
+ // with adding support of @@species
+ _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$3 }, {
+ splice: function splice(start, deleteCount /* , ...items */) {
+ var O = toObject(this);
+ var len = toLength(O.length);
+ var actualStart = toAbsoluteIndex(start, len);
+ var argumentsLength = arguments.length;
+ var insertCount, actualDeleteCount, A, k, from, to;
+ if (argumentsLength === 0) {
+ insertCount = actualDeleteCount = 0;
+ } else if (argumentsLength === 1) {
+ insertCount = 0;
+ actualDeleteCount = len - actualStart;
} else {
- if (this.options.ignoreWhitespace) {
- line = line.trim();
+ insertCount = argumentsLength - 2;
+ actualDeleteCount = min$5(max$2(toInteger(deleteCount), 0), len - actualStart);
+ }
+ if (len + insertCount - actualDeleteCount > MAX_SAFE_INTEGER$1) {
+ throw TypeError(MAXIMUM_ALLOWED_LENGTH_EXCEEDED);
+ }
+ A = arraySpeciesCreate(O, actualDeleteCount);
+ for (k = 0; k < actualDeleteCount; k++) {
+ from = actualStart + k;
+ if (from in O) createProperty(A, k, O[from]);
+ }
+ A.length = actualDeleteCount;
+ if (insertCount < actualDeleteCount) {
+ for (k = actualStart; k < len - actualDeleteCount; k++) {
+ from = k + actualDeleteCount;
+ to = k + insertCount;
+ if (from in O) O[to] = O[from];
+ else delete O[to];
}
- retLines.push(line);
+ for (k = len; k > len - actualDeleteCount + insertCount; k--) delete O[k - 1];
+ } else if (insertCount > actualDeleteCount) {
+ for (k = len - actualDeleteCount; k > actualStart; k--) {
+ from = k + actualDeleteCount - 1;
+ to = k + insertCount - 1;
+ if (from in O) O[to] = O[from];
+ else delete O[to];
+ }
+ }
+ for (k = 0; k < insertCount; k++) {
+ O[k + actualStart] = arguments[k + 2];
}
+ O.length = len - actualDeleteCount + insertCount;
+ return A;
}
-
- return retLines;
+ });
+
+ // iterable DOM collections
+ // flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
+ var domIterables = {
+ CSSRuleList: 0,
+ CSSStyleDeclaration: 0,
+ CSSValueList: 0,
+ ClientRectList: 0,
+ DOMRectList: 0,
+ DOMStringList: 0,
+ DOMTokenList: 1,
+ DataTransferItemList: 0,
+ FileList: 0,
+ HTMLAllCollection: 0,
+ HTMLCollection: 0,
+ HTMLFormElement: 0,
+ HTMLSelectElement: 0,
+ MediaList: 0,
+ MimeTypeArray: 0,
+ NamedNodeMap: 0,
+ NodeList: 1,
+ PaintRequestList: 0,
+ Plugin: 0,
+ PluginArray: 0,
+ SVGLengthList: 0,
+ SVGNumberList: 0,
+ SVGPathSegList: 0,
+ SVGPointList: 0,
+ SVGStringList: 0,
+ SVGTransformList: 0,
+ SourceBufferList: 0,
+ StyleSheetList: 0,
+ TextTrackCueList: 0,
+ TextTrackList: 0,
+ TouchList: 0
};
- function diffLines(oldStr, newStr, callback) {
- return lineDiff.diff(oldStr, newStr, callback);
- }
- function diffTrimmedLines(oldStr, newStr, callback) {
- var options = /*istanbul ignore start*/(0, _params.generateOptions) /*istanbul ignore end*/(callback, { ignoreWhitespace: true });
- return lineDiff.diff(oldStr, newStr, options);
- }
+ // in old WebKit versions, `element.classList` is not an instance of global `DOMTokenList`
+
+
+ var classList = documentCreateElement('span').classList;
+ var DOMTokenListPrototype = classList && classList.constructor && classList.constructor.prototype;
+
+ var domTokenListPrototype = DOMTokenListPrototype === Object.prototype ? undefined : DOMTokenListPrototype;
+ // optional / simple context binding
+ var functionBindContext = function (fn, that, length) {
+ aCallable(fn);
+ if (that === undefined) return fn;
+ switch (length) {
+ case 0: return function () {
+ return fn.call(that);
+ };
+ case 1: return function (a) {
+ return fn.call(that, a);
+ };
+ case 2: return function (a, b) {
+ return fn.call(that, a, b);
+ };
+ case 3: return function (a, b, c) {
+ return fn.call(that, a, b, c);
+ };
+ }
+ return function (/* ...args */) {
+ return fn.apply(that, arguments);
+ };
+ };
+ var push = [].push;
+
+ // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterReject }` methods implementation
+ var createMethod$4 = function (TYPE) {
+ var IS_MAP = TYPE == 1;
+ var IS_FILTER = TYPE == 2;
+ var IS_SOME = TYPE == 3;
+ var IS_EVERY = TYPE == 4;
+ var IS_FIND_INDEX = TYPE == 6;
+ var IS_FILTER_REJECT = TYPE == 7;
+ var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
+ return function ($this, callbackfn, that, specificCreate) {
+ var O = toObject($this);
+ var self = indexedObject(O);
+ var boundFunction = functionBindContext(callbackfn, that, 3);
+ var length = toLength(self.length);
+ var index = 0;
+ var create = specificCreate || arraySpeciesCreate;
+ var target = IS_MAP ? create($this, length) : IS_FILTER || IS_FILTER_REJECT ? create($this, 0) : undefined;
+ var value, result;
+ for (;length > index; index++) if (NO_HOLES || index in self) {
+ value = self[index];
+ result = boundFunction(value, index, O);
+ if (TYPE) {
+ if (IS_MAP) target[index] = result; // map
+ else if (result) switch (TYPE) {
+ case 3: return true; // some
+ case 5: return value; // find
+ case 6: return index; // findIndex
+ case 2: push.call(target, value); // filter
+ } else switch (TYPE) {
+ case 4: return false; // every
+ case 7: push.call(target, value); // filterReject
+ }
+ }
+ }
+ return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
+ };
+ };
-/***/ }),
-/* 6 */
-/***/ (function(module, exports, __webpack_require__) {
+ var arrayIteration = {
+ // `Array.prototype.forEach` method
+ // https://tc39.es/ecma262/#sec-array.prototype.foreach
+ forEach: createMethod$4(0),
+ // `Array.prototype.map` method
+ // https://tc39.es/ecma262/#sec-array.prototype.map
+ map: createMethod$4(1),
+ // `Array.prototype.filter` method
+ // https://tc39.es/ecma262/#sec-array.prototype.filter
+ filter: createMethod$4(2),
+ // `Array.prototype.some` method
+ // https://tc39.es/ecma262/#sec-array.prototype.some
+ some: createMethod$4(3),
+ // `Array.prototype.every` method
+ // https://tc39.es/ecma262/#sec-array.prototype.every
+ every: createMethod$4(4),
+ // `Array.prototype.find` method
+ // https://tc39.es/ecma262/#sec-array.prototype.find
+ find: createMethod$4(5),
+ // `Array.prototype.findIndex` method
+ // https://tc39.es/ecma262/#sec-array.prototype.findIndex
+ findIndex: createMethod$4(6),
+ // `Array.prototype.filterReject` method
+ // https://github.com/tc39/proposal-array-filtering
+ filterReject: createMethod$4(7)
+ };
- /*istanbul ignore start*/'use strict';
+ var arrayMethodIsStrict = function (METHOD_NAME, argument) {
+ var method = [][METHOD_NAME];
+ return !!method && fails(function () {
+ // eslint-disable-next-line no-useless-call,no-throw-literal -- required for testing
+ method.call(null, argument || function () { throw 1; }, 1);
+ });
+ };
- exports.__esModule = true;
- exports.sentenceDiff = undefined;
- exports. /*istanbul ignore end*/diffSentences = diffSentences;
+ var $forEach$2 = arrayIteration.forEach;
- var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
- /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+ var STRICT_METHOD$3 = arrayMethodIsStrict('forEach');
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+ // `Array.prototype.forEach` method implementation
+ // https://tc39.es/ecma262/#sec-array.prototype.foreach
+ var arrayForEach = !STRICT_METHOD$3 ? function forEach(callbackfn /* , thisArg */) {
+ return $forEach$2(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
+ // eslint-disable-next-line es/no-array-prototype-foreach -- safe
+ } : [].forEach;
- /*istanbul ignore end*/var sentenceDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/sentenceDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
- sentenceDiff.tokenize = function (value) {
- return value.split(/(\S.+?[.!?])(?=\s+|$)/);
+ var handlePrototype$1 = function (CollectionPrototype) {
+ // some Chrome versions have non-configurable methods on DOMTokenList
+ if (CollectionPrototype && CollectionPrototype.forEach !== arrayForEach) try {
+ createNonEnumerableProperty(CollectionPrototype, 'forEach', arrayForEach);
+ } catch (error) {
+ CollectionPrototype.forEach = arrayForEach;
+ }
};
- function diffSentences(oldStr, newStr, callback) {
- return sentenceDiff.diff(oldStr, newStr, callback);
+ for (var COLLECTION_NAME$1 in domIterables) {
+ handlePrototype$1(global_1[COLLECTION_NAME$1] && global_1[COLLECTION_NAME$1].prototype);
}
+ handlePrototype$1(domTokenListPrototype);
+ var $filter$1 = arrayIteration.filter;
-/***/ }),
-/* 7 */
-/***/ (function(module, exports, __webpack_require__) {
- /*istanbul ignore start*/'use strict';
+ var HAS_SPECIES_SUPPORT$2 = arrayMethodHasSpeciesSupport('filter');
- exports.__esModule = true;
- exports.cssDiff = undefined;
- exports. /*istanbul ignore end*/diffCss = diffCss;
+ // `Array.prototype.filter` method
+ // https://tc39.es/ecma262/#sec-array.prototype.filter
+ // with adding support of @@species
+ _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$2 }, {
+ filter: function filter(callbackfn /* , thisArg */) {
+ return $filter$1(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
+ }
+ });
- var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
+ // `Object.keys` method
+ // https://tc39.es/ecma262/#sec-object.keys
+ // eslint-disable-next-line es/no-object-keys -- safe
+ var objectKeys = Object.keys || function keys(O) {
+ return objectKeysInternal(O, enumBugKeys);
+ };
- /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+ var FAILS_ON_PRIMITIVES$4 = fails(function () { objectKeys(1); });
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+ // `Object.keys` method
+ // https://tc39.es/ecma262/#sec-object.keys
+ _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$4 }, {
+ keys: function keys(it) {
+ return objectKeys(toObject(it));
+ }
+ });
- /*istanbul ignore end*/var cssDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/cssDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
- cssDiff.tokenize = function (value) {
- return value.split(/([{}:;,]|\s+)/);
+ var toString_1 = function (argument) {
+ if (classof(argument) === 'Symbol') throw TypeError('Cannot convert a Symbol value to a string');
+ return String(argument);
};
- function diffCss(oldStr, newStr, callback) {
- return cssDiff.diff(oldStr, newStr, callback);
- }
+ // `RegExp.prototype.flags` getter implementation
+ // https://tc39.es/ecma262/#sec-get-regexp.prototype.flags
+ var regexpFlags = function () {
+ var that = anObject(this);
+ var result = '';
+ if (that.global) result += 'g';
+ if (that.ignoreCase) result += 'i';
+ if (that.multiline) result += 'm';
+ if (that.dotAll) result += 's';
+ if (that.unicode) result += 'u';
+ if (that.sticky) result += 'y';
+ return result;
+ };
+ // babel-minify and Closure Compiler transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError
+ var $RegExp$2 = global_1.RegExp;
+
+ var UNSUPPORTED_Y$3 = fails(function () {
+ var re = $RegExp$2('a', 'y');
+ re.lastIndex = 2;
+ return re.exec('abcd') != null;
+ });
+
+ var BROKEN_CARET = fails(function () {
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=773687
+ var re = $RegExp$2('^r', 'gy');
+ re.lastIndex = 2;
+ return re.exec('str') != null;
+ });
+
+ var regexpStickyHelpers = {
+ UNSUPPORTED_Y: UNSUPPORTED_Y$3,
+ BROKEN_CARET: BROKEN_CARET
+ };
+ // `Object.defineProperties` method
+ // https://tc39.es/ecma262/#sec-object.defineproperties
+ // eslint-disable-next-line es/no-object-defineproperties -- safe
+ var objectDefineProperties = descriptors ? Object.defineProperties : function defineProperties(O, Properties) {
+ anObject(O);
+ var keys = objectKeys(Properties);
+ var length = keys.length;
+ var index = 0;
+ var key;
+ while (length > index) objectDefineProperty.f(O, key = keys[index++], Properties[key]);
+ return O;
+ };
-/***/ }),
-/* 8 */
-/***/ (function(module, exports, __webpack_require__) {
+ var html$1 = getBuiltIn('document', 'documentElement');
- /*istanbul ignore start*/'use strict';
+ /* global ActiveXObject -- old IE, WSH */
- exports.__esModule = true;
- exports.jsonDiff = undefined;
- var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
- exports. /*istanbul ignore end*/diffJson = diffJson;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = canonicalize;
- var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
- /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
- /*istanbul ignore end*/var /*istanbul ignore start*/_line = __webpack_require__(5) /*istanbul ignore end*/;
- /*istanbul ignore start*/function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
- /*istanbul ignore end*/var objectPrototypeToString = Object.prototype.toString;
+ var GT = '>';
+ var LT = '<';
+ var PROTOTYPE$2 = 'prototype';
+ var SCRIPT = 'script';
+ var IE_PROTO$1 = sharedKey('IE_PROTO');
- var jsonDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/jsonDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
- // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
- // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
- jsonDiff.useLongestToken = true;
+ var EmptyConstructor = function () { /* empty */ };
- jsonDiff.tokenize = /*istanbul ignore start*/_line.lineDiff /*istanbul ignore end*/.tokenize;
- jsonDiff.castInput = function (value) {
- /*istanbul ignore start*/var _options = /*istanbul ignore end*/this.options,
- undefinedReplacement = _options.undefinedReplacement,
- _options$stringifyRep = _options.stringifyReplacer,
- stringifyReplacer = _options$stringifyRep === undefined ? function (k, v) /*istanbul ignore start*/{
- return (/*istanbul ignore end*/typeof v === 'undefined' ? undefinedReplacement : v
- );
- } : _options$stringifyRep;
+ var scriptTag = function (content) {
+ return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
+ };
+ // Create object with fake `null` prototype: use ActiveX Object with cleared prototype
+ var NullProtoObjectViaActiveX = function (activeXDocument) {
+ activeXDocument.write(scriptTag(''));
+ activeXDocument.close();
+ var temp = activeXDocument.parentWindow.Object;
+ activeXDocument = null; // avoid memory leak
+ return temp;
+ };
- return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
+ // Create object with fake `null` prototype: use iframe Object with cleared prototype
+ var NullProtoObjectViaIFrame = function () {
+ // Thrash, waste and sodomy: IE GC bug
+ var iframe = documentCreateElement('iframe');
+ var JS = 'java' + SCRIPT + ':';
+ var iframeDocument;
+ iframe.style.display = 'none';
+ html$1.appendChild(iframe);
+ // https://github.com/zloirock/core-js/issues/475
+ iframe.src = String(JS);
+ iframeDocument = iframe.contentWindow.document;
+ iframeDocument.open();
+ iframeDocument.write(scriptTag('document.F=Object'));
+ iframeDocument.close();
+ return iframeDocument.F;
};
- jsonDiff.equals = function (left, right) {
- return (/*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'))
- );
+
+ // Check for document.domain and active x support
+ // No need to use active x approach when document.domain is not set
+ // see https://github.com/es-shims/es5-shim/issues/150
+ // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
+ // avoid IE GC bug
+ var activeXDocument;
+ var NullProtoObject = function () {
+ try {
+ activeXDocument = new ActiveXObject('htmlfile');
+ } catch (error) { /* ignore */ }
+ NullProtoObject = typeof document != 'undefined'
+ ? document.domain && activeXDocument
+ ? NullProtoObjectViaActiveX(activeXDocument) // old IE
+ : NullProtoObjectViaIFrame()
+ : NullProtoObjectViaActiveX(activeXDocument); // WSH
+ var length = enumBugKeys.length;
+ while (length--) delete NullProtoObject[PROTOTYPE$2][enumBugKeys[length]];
+ return NullProtoObject();
};
- function diffJson(oldObj, newObj, options) {
- return jsonDiff.diff(oldObj, newObj, options);
- }
+ hiddenKeys$1[IE_PROTO$1] = true;
+
+ // `Object.create` method
+ // https://tc39.es/ecma262/#sec-object.create
+ var objectCreate = Object.create || function create(O, Properties) {
+ var result;
+ if (O !== null) {
+ EmptyConstructor[PROTOTYPE$2] = anObject(O);
+ result = new EmptyConstructor();
+ EmptyConstructor[PROTOTYPE$2] = null;
+ // add "__proto__" for Object.getPrototypeOf polyfill
+ result[IE_PROTO$1] = O;
+ } else result = NullProtoObject();
+ return Properties === undefined ? result : objectDefineProperties(result, Properties);
+ };
- // This function handles the presence of circular references by bailing out when encountering an
- // object that is already on the "stack" of items being processed. Accepts an optional replacer
- function canonicalize(obj, stack, replacementStack, replacer, key) {
- stack = stack || [];
- replacementStack = replacementStack || [];
+ // babel-minify and Closure Compiler transpiles RegExp('.', 's') -> /./s and it causes SyntaxError
+ var $RegExp$1 = global_1.RegExp;
- if (replacer) {
- obj = replacer(key, obj);
- }
+ var regexpUnsupportedDotAll = fails(function () {
+ var re = $RegExp$1('.', 's');
+ return !(re.dotAll && re.exec('\n') && re.flags === 's');
+ });
- var i = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
+ // babel-minify and Closure Compiler transpiles RegExp('(?b)', 'g') -> /(? b)/g and it causes SyntaxError
+ var $RegExp = global_1.RegExp;
- for (i = 0; i < stack.length; i += 1) {
- if (stack[i] === obj) {
- return replacementStack[i];
- }
- }
+ var regexpUnsupportedNcg = fails(function () {
+ var re = $RegExp('(? b)', 'g');
+ return re.exec('b').groups.a !== 'b' ||
+ 'b'.replace(re, '$ c') !== 'bc';
+ });
- var canonicalizedObj = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
+ /* eslint-disable regexp/no-empty-capturing-group, regexp/no-empty-group, regexp/no-lazy-ends -- testing */
+ /* eslint-disable regexp/no-useless-quantifier -- testing */
- if ('[object Array]' === objectPrototypeToString.call(obj)) {
- stack.push(obj);
- canonicalizedObj = new Array(obj.length);
- replacementStack.push(canonicalizedObj);
- for (i = 0; i < obj.length; i += 1) {
- canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
- }
- stack.pop();
- replacementStack.pop();
- return canonicalizedObj;
- }
- if (obj && obj.toJSON) {
- obj = obj.toJSON();
- }
- if ( /*istanbul ignore start*/(typeof /*istanbul ignore end*/obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null) {
- stack.push(obj);
- canonicalizedObj = {};
- replacementStack.push(canonicalizedObj);
- var sortedKeys = [],
- _key = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
- for (_key in obj) {
- /* istanbul ignore else */
- if (obj.hasOwnProperty(_key)) {
- sortedKeys.push(_key);
- }
- }
- sortedKeys.sort();
- for (i = 0; i < sortedKeys.length; i += 1) {
- _key = sortedKeys[i];
- canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
- }
- stack.pop();
- replacementStack.pop();
- } else {
- canonicalizedObj = obj;
- }
- return canonicalizedObj;
- }
+ var getInternalState$5 = internalState.get;
-/***/ }),
-/* 9 */
-/***/ (function(module, exports, __webpack_require__) {
- /*istanbul ignore start*/'use strict';
- exports.__esModule = true;
- exports.arrayDiff = undefined;
- exports. /*istanbul ignore end*/diffArrays = diffArrays;
+ var nativeExec = RegExp.prototype.exec;
+ var nativeReplace = shared('native-string-replace', String.prototype.replace);
- var /*istanbul ignore start*/_base = __webpack_require__(1) /*istanbul ignore end*/;
+ var patchedExec = nativeExec;
- /*istanbul ignore start*/var _base2 = _interopRequireDefault(_base);
+ var UPDATES_LAST_INDEX_WRONG = (function () {
+ var re1 = /a/;
+ var re2 = /b*/g;
+ nativeExec.call(re1, 'a');
+ nativeExec.call(re2, 'a');
+ return re1.lastIndex !== 0 || re2.lastIndex !== 0;
+ })();
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+ var UNSUPPORTED_Y$2 = regexpStickyHelpers.UNSUPPORTED_Y || regexpStickyHelpers.BROKEN_CARET;
- /*istanbul ignore end*/var arrayDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/arrayDiff = new /*istanbul ignore start*/_base2['default'] /*istanbul ignore end*/();
- arrayDiff.tokenize = function (value) {
- return value.slice();
- };
- arrayDiff.join = arrayDiff.removeEmpty = function (value) {
- return value;
- };
+ // nonparticipating capturing group, copied from es5-shim's String#split patch.
+ var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined;
- function diffArrays(oldArr, newArr, callback) {
- return arrayDiff.diff(oldArr, newArr, callback);
- }
+ var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y$2 || regexpUnsupportedDotAll || regexpUnsupportedNcg;
+ if (PATCH) {
+ // eslint-disable-next-line max-statements -- TODO
+ patchedExec = function exec(string) {
+ var re = this;
+ var state = getInternalState$5(re);
+ var str = toString_1(string);
+ var raw = state.raw;
+ var result, reCopy, lastIndex, match, i, object, group;
+ if (raw) {
+ raw.lastIndex = re.lastIndex;
+ result = patchedExec.call(raw, str);
+ re.lastIndex = raw.lastIndex;
+ return result;
+ }
-/***/ }),
-/* 10 */
-/***/ (function(module, exports, __webpack_require__) {
+ var groups = state.groups;
+ var sticky = UNSUPPORTED_Y$2 && re.sticky;
+ var flags = regexpFlags.call(re);
+ var source = re.source;
+ var charsAdded = 0;
+ var strCopy = str;
+
+ if (sticky) {
+ flags = flags.replace('y', '');
+ if (flags.indexOf('g') === -1) {
+ flags += 'g';
+ }
- /*istanbul ignore start*/'use strict';
+ strCopy = str.slice(re.lastIndex);
+ // Support anchored sticky behavior.
+ if (re.lastIndex > 0 && (!re.multiline || re.multiline && str.charAt(re.lastIndex - 1) !== '\n')) {
+ source = '(?: ' + source + ')';
+ strCopy = ' ' + strCopy;
+ charsAdded++;
+ }
+ // ^(? + rx + ) is needed, in combination with some str slicing, to
+ // simulate the 'y' flag.
+ reCopy = new RegExp('^(?:' + source + ')', flags);
+ }
- exports.__esModule = true;
- exports. /*istanbul ignore end*/applyPatch = applyPatch;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = applyPatches;
+ if (NPCG_INCLUDED) {
+ reCopy = new RegExp('^' + source + '$(?!\\s)', flags);
+ }
+ if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex;
+
+ match = nativeExec.call(sticky ? reCopy : re, strCopy);
+
+ if (sticky) {
+ if (match) {
+ match.input = match.input.slice(charsAdded);
+ match[0] = match[0].slice(charsAdded);
+ match.index = re.lastIndex;
+ re.lastIndex += match[0].length;
+ } else re.lastIndex = 0;
+ } else if (UPDATES_LAST_INDEX_WRONG && match) {
+ re.lastIndex = re.global ? match.index + match[0].length : lastIndex;
+ }
+ if (NPCG_INCLUDED && match && match.length > 1) {
+ // Fix browsers whose `exec` methods don't consistently return `undefined`
+ // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/
+ nativeReplace.call(match[0], reCopy, function () {
+ for (i = 1; i < arguments.length - 2; i++) {
+ if (arguments[i] === undefined) match[i] = undefined;
+ }
+ });
+ }
- var /*istanbul ignore start*/_parse = __webpack_require__(11) /*istanbul ignore end*/;
+ if (match && groups) {
+ match.groups = object = objectCreate(null);
+ for (i = 0; i < groups.length; i++) {
+ group = groups[i];
+ object[group[0]] = match[group[1]];
+ }
+ }
- var /*istanbul ignore start*/_distanceIterator = __webpack_require__(12) /*istanbul ignore end*/;
+ return match;
+ };
+ }
- /*istanbul ignore start*/var _distanceIterator2 = _interopRequireDefault(_distanceIterator);
+ var regexpExec = patchedExec;
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+ // `RegExp.prototype.exec` method
+ // https://tc39.es/ecma262/#sec-regexp.prototype.exec
+ _export({ target: 'RegExp', proto: true, forced: /./.exec !== regexpExec }, {
+ exec: regexpExec
+ });
- /*istanbul ignore end*/function applyPatch(source, uniDiff) {
- /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+ // TODO: Remove from `core-js@4` since it's moved to entry points
- if (typeof uniDiff === 'string') {
- uniDiff = /*istanbul ignore start*/(0, _parse.parsePatch) /*istanbul ignore end*/(uniDiff);
- }
- if (Array.isArray(uniDiff)) {
- if (uniDiff.length > 1) {
- throw new Error('applyPatch only works with a single input.');
- }
- uniDiff = uniDiff[0];
- }
- // Apply the diff to the input
- var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
- delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
- hunks = uniDiff.hunks,
- compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) /*istanbul ignore start*/{
- return (/*istanbul ignore end*/line === patchContent
- );
- },
- errorCount = 0,
- fuzzFactor = options.fuzzFactor || 0,
- minLine = 0,
- offset = 0,
- removeEOFNL = /*istanbul ignore start*/void 0 /*istanbul ignore end*/,
- addEOFNL = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
- /**
- * Checks if the hunk exactly fits on the provided location
- */
- function hunkFits(hunk, toPos) {
- for (var j = 0; j < hunk.lines.length; j++) {
- var line = hunk.lines[j],
- operation = line.length > 0 ? line[0] : ' ',
- content = line.length > 0 ? line.substr(1) : line;
- if (operation === ' ' || operation === '-') {
- // Context sanity check
- if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
- errorCount++;
- if (errorCount > fuzzFactor) {
- return false;
- }
- }
- toPos++;
- }
- }
+ var SPECIES$4 = wellKnownSymbol('species');
+ var RegExpPrototype$2 = RegExp.prototype;
- return true;
- }
+ var fixRegexpWellKnownSymbolLogic = function (KEY, exec, FORCED, SHAM) {
+ var SYMBOL = wellKnownSymbol(KEY);
- // Search best fit offsets for each hunk based on the previous ones
- for (var i = 0; i < hunks.length; i++) {
- var hunk = hunks[i],
- maxLine = lines.length - hunk.oldLines,
- localOffset = 0,
- toPos = offset + hunk.oldStart - 1;
+ var DELEGATES_TO_SYMBOL = !fails(function () {
+ // String methods call symbol-named RegEp methods
+ var O = {};
+ O[SYMBOL] = function () { return 7; };
+ return ''[KEY](O) != 7;
+ });
- var iterator = /*istanbul ignore start*/(0, _distanceIterator2['default']) /*istanbul ignore end*/(toPos, minLine, maxLine);
+ var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () {
+ // Symbol-named RegExp methods call .exec
+ var execCalled = false;
+ var re = /a/;
+
+ if (KEY === 'split') {
+ // We can't use real regex here since it causes deoptimization
+ // and serious performance degradation in V8
+ // https://github.com/zloirock/core-js/issues/306
+ re = {};
+ // RegExp[@@split] doesn't call the regex's exec method, but first creates
+ // a new one. We need to return the patched regex when creating the new one.
+ re.constructor = {};
+ re.constructor[SPECIES$4] = function () { return re; };
+ re.flags = '';
+ re[SYMBOL] = /./[SYMBOL];
+ }
- for (; localOffset !== undefined; localOffset = iterator()) {
- if (hunkFits(hunk, toPos + localOffset)) {
- hunk.offset = offset += localOffset;
- break;
- }
- }
+ re.exec = function () { execCalled = true; return null; };
- if (localOffset === undefined) {
- return false;
- }
+ re[SYMBOL]('');
+ return !execCalled;
+ });
- // Set lower text limit to end of the current hunk, so next ones don't try
- // to fit over already patched text
- minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
- }
-
- // Apply patch hunks
- var diffOffset = 0;
- for (var _i = 0; _i < hunks.length; _i++) {
- var _hunk = hunks[_i],
- _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
- diffOffset += _hunk.newLines - _hunk.oldLines;
-
- if (_toPos < 0) {
- // Creating a new file
- _toPos = 0;
- }
-
- for (var j = 0; j < _hunk.lines.length; j++) {
- var line = _hunk.lines[j],
- operation = line.length > 0 ? line[0] : ' ',
- content = line.length > 0 ? line.substr(1) : line,
- delimiter = _hunk.linedelimiters[j];
-
- if (operation === ' ') {
- _toPos++;
- } else if (operation === '-') {
- lines.splice(_toPos, 1);
- delimiters.splice(_toPos, 1);
- /* istanbul ignore else */
- } else if (operation === '+') {
- lines.splice(_toPos, 0, content);
- delimiters.splice(_toPos, 0, delimiter);
- _toPos++;
- } else if (operation === '\\') {
- var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
- if (previousOperation === '+') {
- removeEOFNL = true;
- } else if (previousOperation === '-') {
- addEOFNL = true;
+ if (
+ !DELEGATES_TO_SYMBOL ||
+ !DELEGATES_TO_EXEC ||
+ FORCED
+ ) {
+ var nativeRegExpMethod = /./[SYMBOL];
+ var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) {
+ var $exec = regexp.exec;
+ if ($exec === regexpExec || $exec === RegExpPrototype$2.exec) {
+ if (DELEGATES_TO_SYMBOL && !forceStringMethod) {
+ // The native String method already delegates to @@method (this
+ // polyfilled function), leasing to infinite recursion.
+ // We avoid it by directly calling the native @@method method.
+ return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) };
}
+ return { done: true, value: nativeMethod.call(str, regexp, arg2) };
}
- }
- }
+ return { done: false };
+ });
- // Handle EOFNL insertion/removal
- if (removeEOFNL) {
- while (!lines[lines.length - 1]) {
- lines.pop();
- delimiters.pop();
- }
- } else if (addEOFNL) {
- lines.push('');
- delimiters.push('\n');
- }
- for (var _k = 0; _k < lines.length - 1; _k++) {
- lines[_k] = lines[_k] + delimiters[_k];
+ redefine(String.prototype, KEY, methods[0]);
+ redefine(RegExpPrototype$2, SYMBOL, methods[1]);
}
- return lines.join('');
- }
- // Wrapper that supports multiple file patches via callbacks.
- function applyPatches(uniDiff, options) {
- if (typeof uniDiff === 'string') {
- uniDiff = /*istanbul ignore start*/(0, _parse.parsePatch) /*istanbul ignore end*/(uniDiff);
+ if (SHAM) createNonEnumerableProperty(RegExpPrototype$2[SYMBOL], 'sham', true);
+ };
+
+ // `SameValue` abstract operation
+ // https://tc39.es/ecma262/#sec-samevalue
+ // eslint-disable-next-line es/no-object-is -- safe
+ var sameValue = Object.is || function is(x, y) {
+ // eslint-disable-next-line no-self-compare -- NaN check
+ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
+ };
+
+ // `RegExpExec` abstract operation
+ // https://tc39.es/ecma262/#sec-regexpexec
+ var regexpExecAbstract = function (R, S) {
+ var exec = R.exec;
+ if (isCallable(exec)) {
+ var result = exec.call(R, S);
+ if (result !== null) anObject(result);
+ return result;
}
+ if (classofRaw(R) === 'RegExp') return regexpExec.call(R, S);
+ throw TypeError('RegExp#exec called on incompatible receiver');
+ };
- var currentIndex = 0;
- function processIndex() {
- var index = uniDiff[currentIndex++];
- if (!index) {
- return options.complete();
+ // @@search logic
+ fixRegexpWellKnownSymbolLogic('search', function (SEARCH, nativeSearch, maybeCallNative) {
+ return [
+ // `String.prototype.search` method
+ // https://tc39.es/ecma262/#sec-string.prototype.search
+ function search(regexp) {
+ var O = requireObjectCoercible(this);
+ var searcher = regexp == undefined ? undefined : getMethod(regexp, SEARCH);
+ return searcher ? searcher.call(regexp, O) : new RegExp(regexp)[SEARCH](toString_1(O));
+ },
+ // `RegExp.prototype[@@search]` method
+ // https://tc39.es/ecma262/#sec-regexp.prototype-@@search
+ function (string) {
+ var rx = anObject(this);
+ var S = toString_1(string);
+ var res = maybeCallNative(nativeSearch, rx, S);
+
+ if (res.done) return res.value;
+
+ var previousLastIndex = rx.lastIndex;
+ if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0;
+ var result = regexpExecAbstract(rx, S);
+ if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex;
+ return result === null ? -1 : result.index;
}
+ ];
+ });
+
+ var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');
+ var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
+ var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded';
+
+ // We can't use this feature detection in V8 since it causes
+ // deoptimization and serious performance degradation
+ // https://github.com/zloirock/core-js/issues/679
+ var IS_CONCAT_SPREADABLE_SUPPORT = engineV8Version >= 51 || !fails(function () {
+ var array = [];
+ array[IS_CONCAT_SPREADABLE] = false;
+ return array.concat()[0] !== array;
+ });
+
+ var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat');
+
+ var isConcatSpreadable = function (O) {
+ if (!isObject$1(O)) return false;
+ var spreadable = O[IS_CONCAT_SPREADABLE];
+ return spreadable !== undefined ? !!spreadable : isArray$3(O);
+ };
- options.loadFile(index, function (err, data) {
- if (err) {
- return options.complete(err);
+ var FORCED$8 = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT;
+
+ // `Array.prototype.concat` method
+ // https://tc39.es/ecma262/#sec-array.prototype.concat
+ // with adding support of @@isConcatSpreadable and @@species
+ _export({ target: 'Array', proto: true, forced: FORCED$8 }, {
+ // eslint-disable-next-line no-unused-vars -- required for `.length`
+ concat: function concat(arg) {
+ var O = toObject(this);
+ var A = arraySpeciesCreate(O, 0);
+ var n = 0;
+ var i, k, length, len, E;
+ for (i = -1, length = arguments.length; i < length; i++) {
+ E = i === -1 ? O : arguments[i];
+ if (isConcatSpreadable(E)) {
+ len = toLength(E.length);
+ if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
+ for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);
+ } else {
+ if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
+ createProperty(A, n++, E);
}
-
- var updatedContent = applyPatch(data, index, options);
- options.patched(index, updatedContent, function (err) {
- if (err) {
- return options.complete(err);
- }
-
- processIndex();
- });
- });
+ }
+ A.length = n;
+ return A;
}
- processIndex();
- }
+ });
+ var global$2 = typeof global$1 !== "undefined" ? global$1 : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
+ var global$1 = typeof global$2 !== "undefined" ? global$2 : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
-/***/ }),
-/* 11 */
-/***/ (function(module, exports) {
+ // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
- /*istanbul ignore start*/'use strict';
+ function defaultSetTimout$1() {
+ throw new Error('setTimeout has not been defined');
+ }
- exports.__esModule = true;
- exports. /*istanbul ignore end*/parsePatch = parsePatch;
- function parsePatch(uniDiff) {
- /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ function defaultClearTimeout$1() {
+ throw new Error('clearTimeout has not been defined');
+ }
- var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
- delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
- list = [],
- i = 0;
+ var cachedSetTimeout$1 = defaultSetTimout$1;
+ var cachedClearTimeout$1 = defaultClearTimeout$1;
- function parseIndex() {
- var index = {};
- list.push(index);
+ if (typeof global$1.setTimeout === 'function') {
+ cachedSetTimeout$1 = setTimeout;
+ }
- // Parse diff metadata
- while (i < diffstr.length) {
- var line = diffstr[i];
+ if (typeof global$1.clearTimeout === 'function') {
+ cachedClearTimeout$1 = clearTimeout;
+ }
- // File header found, end parsing diff metadata
- if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
- break;
- }
+ function runTimeout$1(fun) {
+ if (cachedSetTimeout$1 === setTimeout) {
+ //normal enviroments in sane situations
+ return setTimeout(fun, 0);
+ } // if setTimeout wasn't available but was latter defined
- // Diff index
- var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
- if (header) {
- index.index = header[1];
- }
- i++;
+ if ((cachedSetTimeout$1 === defaultSetTimout$1 || !cachedSetTimeout$1) && setTimeout) {
+ cachedSetTimeout$1 = setTimeout;
+ return setTimeout(fun, 0);
+ }
+
+ try {
+ // when when somebody has screwed with setTimeout but no I.E. maddness
+ return cachedSetTimeout$1(fun, 0);
+ } catch (e) {
+ try {
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
+ return cachedSetTimeout$1.call(null, fun, 0);
+ } catch (e) {
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
+ return cachedSetTimeout$1.call(this, fun, 0);
}
+ }
+ }
- // Parse file headers if they are defined. Unified diff requires them, but
- // there's no technical issues to have an isolated hunk without file header
- parseFileHeader(index);
- parseFileHeader(index);
+ function runClearTimeout$1(marker) {
+ if (cachedClearTimeout$1 === clearTimeout) {
+ //normal enviroments in sane situations
+ return clearTimeout(marker);
+ } // if clearTimeout wasn't available but was latter defined
- // Parse hunks
- index.hunks = [];
- while (i < diffstr.length) {
- var _line = diffstr[i];
+ if ((cachedClearTimeout$1 === defaultClearTimeout$1 || !cachedClearTimeout$1) && clearTimeout) {
+ cachedClearTimeout$1 = clearTimeout;
+ return clearTimeout(marker);
+ }
- if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
- break;
- } else if (/^@@/.test(_line)) {
- index.hunks.push(parseHunk());
- } else if (_line && options.strict) {
- // Ignore unexpected content unless in strict mode
- throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
- } else {
- i++;
- }
+ try {
+ // when when somebody has screwed with setTimeout but no I.E. maddness
+ return cachedClearTimeout$1(marker);
+ } catch (e) {
+ try {
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
+ return cachedClearTimeout$1.call(null, marker);
+ } catch (e) {
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
+ // Some versions of I.E. have different rules for clearTimeout vs setTimeout
+ return cachedClearTimeout$1.call(this, marker);
}
}
+ }
- // Parses the --- and +++ headers, if none are found, no lines
- // are consumed.
- function parseFileHeader(index) {
- var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
- if (fileHeader) {
- var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
- var data = fileHeader[2].split('\t', 2);
- var fileName = data[0].replace(/\\\\/g, '\\');
- if (/^".*"$/.test(fileName)) {
- fileName = fileName.substr(1, fileName.length - 2);
- }
- index[keyPrefix + 'FileName'] = fileName;
- index[keyPrefix + 'Header'] = (data[1] || '').trim();
+ var queue$2 = [];
+ var draining$1 = false;
+ var currentQueue$1;
+ var queueIndex$1 = -1;
- i++;
- }
+ function cleanUpNextTick$1() {
+ if (!draining$1 || !currentQueue$1) {
+ return;
}
- // Parses a hunk
- // This assumes that we are at the start of a hunk.
- function parseHunk() {
- var chunkHeaderIndex = i,
- chunkHeaderLine = diffstr[i++],
- chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
+ draining$1 = false;
- var hunk = {
- oldStart: +chunkHeader[1],
- oldLines: +chunkHeader[2] || 1,
- newStart: +chunkHeader[3],
- newLines: +chunkHeader[4] || 1,
- lines: [],
- linedelimiters: []
- };
+ if (currentQueue$1.length) {
+ queue$2 = currentQueue$1.concat(queue$2);
+ } else {
+ queueIndex$1 = -1;
+ }
- var addCount = 0,
- removeCount = 0;
- for (; i < diffstr.length; i++) {
- // Lines starting with '---' could be mistaken for the "remove line" operation
- // But they could be the header for the next file. Therefore prune such cases out.
- if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
- break;
- }
- var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
-
- if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
- hunk.lines.push(diffstr[i]);
- hunk.linedelimiters.push(delimiters[i] || '\n');
-
- if (operation === '+') {
- addCount++;
- } else if (operation === '-') {
- removeCount++;
- } else if (operation === ' ') {
- addCount++;
- removeCount++;
- }
- } else {
- break;
- }
- }
+ if (queue$2.length) {
+ drainQueue$1();
+ }
+ }
- // Handle the empty block count case
- if (!addCount && hunk.newLines === 1) {
- hunk.newLines = 0;
- }
- if (!removeCount && hunk.oldLines === 1) {
- hunk.oldLines = 0;
- }
+ function drainQueue$1() {
+ if (draining$1) {
+ return;
+ }
- // Perform optional sanity checking
- if (options.strict) {
- if (addCount !== hunk.newLines) {
- throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
- }
- if (removeCount !== hunk.oldLines) {
- throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
+ var timeout = runTimeout$1(cleanUpNextTick$1);
+ draining$1 = true;
+ var len = queue$2.length;
+
+ while (len) {
+ currentQueue$1 = queue$2;
+ queue$2 = [];
+
+ while (++queueIndex$1 < len) {
+ if (currentQueue$1) {
+ currentQueue$1[queueIndex$1].run();
}
}
- return hunk;
+ queueIndex$1 = -1;
+ len = queue$2.length;
}
- while (i < diffstr.length) {
- parseIndex();
- }
-
- return list;
+ currentQueue$1 = null;
+ draining$1 = false;
+ runClearTimeout$1(timeout);
}
+ function nextTick$1(fun) {
+ var args = new Array(arguments.length - 1);
+ if (arguments.length > 1) {
+ for (var i = 1; i < arguments.length; i++) {
+ args[i - 1] = arguments[i];
+ }
+ }
-/***/ }),
-/* 12 */
-/***/ (function(module, exports) {
+ queue$2.push(new Item$1(fun, args));
- /*istanbul ignore start*/"use strict";
+ if (queue$2.length === 1 && !draining$1) {
+ runTimeout$1(drainQueue$1);
+ }
+ } // v8 likes predictible objects
- exports.__esModule = true;
+ function Item$1(fun, array) {
+ this.fun = fun;
+ this.array = array;
+ }
- exports["default"] = /*istanbul ignore end*/function (start, minLine, maxLine) {
- var wantForward = true,
- backwardExhausted = false,
- forwardExhausted = false,
- localOffset = 1;
+ Item$1.prototype.run = function () {
+ this.fun.apply(null, this.array);
+ };
- return function iterator() {
- if (wantForward && !forwardExhausted) {
- if (backwardExhausted) {
- localOffset++;
- } else {
- wantForward = false;
- }
+ var title$1 = 'browser';
+ var platform$1 = 'browser';
+ var browser$4 = true;
+ var env$1 = {};
+ var argv$1 = [];
+ var version$2 = ''; // empty string to avoid regexp issues
+
+ var versions$1 = {};
+ var release$1 = {};
+ var config$1 = {};
+
+ function noop$1() {}
+
+ var on$1 = noop$1;
+ var addListener$1 = noop$1;
+ var once$1 = noop$1;
+ var off$1 = noop$1;
+ var removeListener$1 = noop$1;
+ var removeAllListeners$1 = noop$1;
+ var emit$1 = noop$1;
+ function binding$1(name) {
+ throw new Error('process.binding is not supported');
+ }
+ function cwd$1() {
+ return '/';
+ }
+ function chdir$1(dir) {
+ throw new Error('process.chdir is not supported');
+ }
+ function umask$1() {
+ return 0;
+ } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
- // Check if trying to fit beyond text length, and if not, check it fits
- // after offset location (or desired location on first iteration)
- if (start + localOffset <= maxLine) {
- return localOffset;
- }
+ var performance$1 = global$1.performance || {};
- forwardExhausted = true;
- }
+ var performanceNow$1 = performance$1.now || performance$1.mozNow || performance$1.msNow || performance$1.oNow || performance$1.webkitNow || function () {
+ return new Date().getTime();
+ }; // generate timestamp or delta
+ // see http://nodejs.org/api/process.html#process_process_hrtime
- if (!backwardExhausted) {
- if (!forwardExhausted) {
- wantForward = true;
- }
- // Check if trying to fit before text beginning, and if not, check it fits
- // before offset location
- if (minLine <= start - localOffset) {
- return -localOffset++;
- }
+ function hrtime$1(previousTimestamp) {
+ var clocktime = performanceNow$1.call(performance$1) * 1e-3;
+ var seconds = Math.floor(clocktime);
+ var nanoseconds = Math.floor(clocktime % 1 * 1e9);
- backwardExhausted = true;
- return iterator();
+ if (previousTimestamp) {
+ seconds = seconds - previousTimestamp[0];
+ nanoseconds = nanoseconds - previousTimestamp[1];
+
+ if (nanoseconds < 0) {
+ seconds--;
+ nanoseconds += 1e9;
}
+ }
- // We tried to fit hunk before text beginning and beyond text length, then
- // hunk can't fit on the text. Return undefined
- };
+ return [seconds, nanoseconds];
+ }
+ var startTime$1 = new Date();
+ function uptime$1() {
+ var currentTime = new Date();
+ var dif = currentTime - startTime$1;
+ return dif / 1000;
+ }
+ var process$4 = {
+ nextTick: nextTick$1,
+ title: title$1,
+ browser: browser$4,
+ env: env$1,
+ argv: argv$1,
+ version: version$2,
+ versions: versions$1,
+ on: on$1,
+ addListener: addListener$1,
+ once: once$1,
+ off: off$1,
+ removeListener: removeListener$1,
+ removeAllListeners: removeAllListeners$1,
+ emit: emit$1,
+ binding: binding$1,
+ cwd: cwd$1,
+ chdir: chdir$1,
+ umask: umask$1,
+ hrtime: hrtime$1,
+ platform: platform$1,
+ release: release$1,
+ config: config$1,
+ uptime: uptime$1
};
+ // `Object.prototype.toString` method implementation
+ // https://tc39.es/ecma262/#sec-object.prototype.tostring
+ var objectToString$1 = toStringTagSupport ? {}.toString : function toString() {
+ return '[object ' + classof(this) + ']';
+ };
+ // `Object.prototype.toString` method
+ // https://tc39.es/ecma262/#sec-object.prototype.tostring
+ if (!toStringTagSupport) {
+ redefine(Object.prototype, 'toString', objectToString$1, { unsafe: true });
+ }
-/***/ }),
-/* 13 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /*istanbul ignore start*/'use strict';
+ var PROPER_FUNCTION_NAME$4 = functionName.PROPER;
- exports.__esModule = true;
- exports. /*istanbul ignore end*/calcLineCount = calcLineCount;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/merge = merge;
- var /*istanbul ignore start*/_create = __webpack_require__(14) /*istanbul ignore end*/;
- var /*istanbul ignore start*/_parse = __webpack_require__(11) /*istanbul ignore end*/;
- var /*istanbul ignore start*/_array = __webpack_require__(15) /*istanbul ignore end*/;
- /*istanbul ignore start*/function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
- /*istanbul ignore end*/function calcLineCount(hunk) {
- /*istanbul ignore start*/var _calcOldNewLineCount = /*istanbul ignore end*/calcOldNewLineCount(hunk.lines),
- oldLines = _calcOldNewLineCount.oldLines,
- newLines = _calcOldNewLineCount.newLines;
+ var TO_STRING = 'toString';
+ var RegExpPrototype$1 = RegExp.prototype;
+ var nativeToString = RegExpPrototype$1[TO_STRING];
- if (oldLines !== undefined) {
- hunk.oldLines = oldLines;
- } else {
- delete hunk.oldLines;
- }
+ var NOT_GENERIC = fails(function () { return nativeToString.call({ source: 'a', flags: 'b' }) != '/a/b'; });
+ // FF44- RegExp#toString has a wrong name
+ var INCORRECT_NAME = PROPER_FUNCTION_NAME$4 && nativeToString.name != TO_STRING;
- if (newLines !== undefined) {
- hunk.newLines = newLines;
- } else {
- delete hunk.newLines;
- }
+ // `RegExp.prototype.toString` method
+ // https://tc39.es/ecma262/#sec-regexp.prototype.tostring
+ if (NOT_GENERIC || INCORRECT_NAME) {
+ redefine(RegExp.prototype, TO_STRING, function toString() {
+ var R = anObject(this);
+ var p = toString_1(R.source);
+ var rf = R.flags;
+ var f = toString_1(rf === undefined && R instanceof RegExp && !('flags' in RegExpPrototype$1) ? regexpFlags.call(R) : rf);
+ return '/' + p + '/' + f;
+ }, { unsafe: true });
}
- function merge(mine, theirs, base) {
- mine = loadPatch(mine, base);
- theirs = loadPatch(theirs, base);
+ var correctPrototypeGetter = !fails(function () {
+ function F() { /* empty */ }
+ F.prototype.constructor = null;
+ // eslint-disable-next-line es/no-object-getprototypeof -- required for testing
+ return Object.getPrototypeOf(new F()) !== F.prototype;
+ });
+
+ var IE_PROTO = sharedKey('IE_PROTO');
+ var ObjectPrototype$3 = Object.prototype;
+
+ // `Object.getPrototypeOf` method
+ // https://tc39.es/ecma262/#sec-object.getprototypeof
+ // eslint-disable-next-line es/no-object-getprototypeof -- safe
+ var objectGetPrototypeOf = correctPrototypeGetter ? Object.getPrototypeOf : function (O) {
+ var object = toObject(O);
+ if (has$1(object, IE_PROTO)) return object[IE_PROTO];
+ var constructor = object.constructor;
+ if (isCallable(constructor) && object instanceof constructor) {
+ return constructor.prototype;
+ } return object instanceof Object ? ObjectPrototype$3 : null;
+ };
- var ret = {};
+ var FAILS_ON_PRIMITIVES$3 = fails(function () { objectGetPrototypeOf(1); });
- // For index we just let it pass through as it doesn't have any necessary meaning.
- // Leaving sanity checks on this to the API consumer that may know more about the
- // meaning in their own context.
- if (mine.index || theirs.index) {
- ret.index = mine.index || theirs.index;
+ // `Object.getPrototypeOf` method
+ // https://tc39.es/ecma262/#sec-object.getprototypeof
+ _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$3, sham: !correctPrototypeGetter }, {
+ getPrototypeOf: function getPrototypeOf(it) {
+ return objectGetPrototypeOf(toObject(it));
}
-
- if (mine.newFileName || theirs.newFileName) {
- if (!fileNameChanged(mine)) {
- // No header or no change in ours, use theirs (and ours if theirs does not exist)
- ret.oldFileName = theirs.oldFileName || mine.oldFileName;
- ret.newFileName = theirs.newFileName || mine.newFileName;
- ret.oldHeader = theirs.oldHeader || mine.oldHeader;
- ret.newHeader = theirs.newHeader || mine.newHeader;
- } else if (!fileNameChanged(theirs)) {
- // No header or no change in theirs, use ours
- ret.oldFileName = mine.oldFileName;
- ret.newFileName = mine.newFileName;
- ret.oldHeader = mine.oldHeader;
- ret.newHeader = mine.newHeader;
- } else {
- // Both changed... figure it out
- ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
- ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
- ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
- ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
- }
- }
-
- ret.hunks = [];
-
- var mineIndex = 0,
- theirsIndex = 0,
- mineOffset = 0,
- theirsOffset = 0;
-
- while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
- var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity },
- theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity };
-
- if (hunkBefore(mineCurrent, theirsCurrent)) {
- // This patch does not overlap with any of the others, yay.
- ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
- mineIndex++;
- theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
- } else if (hunkBefore(theirsCurrent, mineCurrent)) {
- // This patch does not overlap with any of the others, yay.
- ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
- theirsIndex++;
- mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
- } else {
- // Overlap, merge as best we can
- var mergedHunk = {
- oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
- oldLines: 0,
- newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
- newLines: 0,
- lines: []
- };
- mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
- theirsIndex++;
- mineIndex++;
-
- ret.hunks.push(mergedHunk);
+ });
+
+ var FUNCTION_NAME_EXISTS = functionName.EXISTS;
+ var defineProperty$9 = objectDefineProperty.f;
+
+ var FunctionPrototype = Function.prototype;
+ var FunctionPrototypeToString = FunctionPrototype.toString;
+ var nameRE = /^\s*function ([^ (]*)/;
+ var NAME$1 = 'name';
+
+ // Function instances `.name` property
+ // https://tc39.es/ecma262/#sec-function-instances-name
+ if (descriptors && !FUNCTION_NAME_EXISTS) {
+ defineProperty$9(FunctionPrototype, NAME$1, {
+ configurable: true,
+ get: function () {
+ try {
+ return FunctionPrototypeToString.call(this).match(nameRE)[1];
+ } catch (error) {
+ return '';
+ }
}
- }
-
- return ret;
+ });
}
- function loadPatch(param, base) {
- if (typeof param === 'string') {
- if (/^@@/m.test(param) || /^Index:/m.test(param)) {
- return (/*istanbul ignore start*/(0, _parse.parsePatch) /*istanbul ignore end*/(param)[0]
- );
- }
+ // `Reflect.ownKeys` method
+ // https://tc39.es/ecma262/#sec-reflect.ownkeys
+ _export({ target: 'Reflect', stat: true }, {
+ ownKeys: ownKeys$1
+ });
- if (!base) {
- throw new Error('Must provide a base reference or pass in a patch');
- }
- return (/*istanbul ignore start*/(0, _create.structuredPatch) /*istanbul ignore end*/(undefined, undefined, base, param)
- );
- }
+ var domain; // This constructor is used to store event handlers. Instantiating this is
+ // faster than explicitly calling `Object.create(null)` to get a "clean" empty
+ // object (tested with v8 v4.9).
- return param;
- }
+ function EventHandlers() {}
- function fileNameChanged(patch) {
- return patch.newFileName && patch.newFileName !== patch.oldFileName;
- }
+ EventHandlers.prototype = Object.create(null);
- function selectField(index, mine, theirs) {
- if (mine === theirs) {
- return mine;
- } else {
- index.conflict = true;
- return { mine: mine, theirs: theirs };
- }
+ function EventEmitter$2() {
+ EventEmitter$2.init.call(this);
}
+ // require('events') === require('events').EventEmitter
- function hunkBefore(test, check) {
- return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
- }
+ EventEmitter$2.EventEmitter = EventEmitter$2;
+ EventEmitter$2.usingDomains = false;
+ EventEmitter$2.prototype.domain = undefined;
+ EventEmitter$2.prototype._events = undefined;
+ EventEmitter$2.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are
+ // added to it. This is a useful default which helps finding memory leaks.
- function cloneHunk(hunk, offset) {
- return {
- oldStart: hunk.oldStart, oldLines: hunk.oldLines,
- newStart: hunk.newStart + offset, newLines: hunk.newLines,
- lines: hunk.lines
- };
- }
+ EventEmitter$2.defaultMaxListeners = 10;
- function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
- // This will generally result in a conflicted hunk, but there are cases where the context
- // is the only overlap where we can successfully merge the content here.
- var mine = { offset: mineOffset, lines: mineLines, index: 0 },
- their = { offset: theirOffset, lines: theirLines, index: 0 };
-
- // Handle any leading content
- insertLeading(hunk, mine, their);
- insertLeading(hunk, their, mine);
-
- // Now in the overlap content. Scan through and select the best changes from each.
- while (mine.index < mine.lines.length && their.index < their.lines.length) {
- var mineCurrent = mine.lines[mine.index],
- theirCurrent = their.lines[their.index];
-
- if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
- // Both modified ...
- mutualChange(hunk, mine, their);
- } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
- /*istanbul ignore start*/var _hunk$lines;
-
- /*istanbul ignore end*/ // Mine inserted
- /*istanbul ignore start*/(_hunk$lines = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/collectChange(mine)));
- } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
- /*istanbul ignore start*/var _hunk$lines2;
-
- /*istanbul ignore end*/ // Theirs inserted
- /*istanbul ignore start*/(_hunk$lines2 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines2 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/collectChange(their)));
- } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
- // Mine removed or edited
- removal(hunk, mine, their);
- } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
- // Their removed or edited
- removal(hunk, their, mine, true);
- } else if (mineCurrent === theirCurrent) {
- // Context identity
- hunk.lines.push(mineCurrent);
- mine.index++;
- their.index++;
- } else {
- // Context mismatch
- conflict(hunk, collectChange(mine), collectChange(their));
- }
+ EventEmitter$2.init = function () {
+ this.domain = null;
+
+ if (EventEmitter$2.usingDomains) {
+ // if there is an active domain, then attach to it.
+ if (domain.active ) ;
+ }
+
+ if (!this._events || this._events === Object.getPrototypeOf(this)._events) {
+ this._events = new EventHandlers();
+ this._eventsCount = 0;
}
- // Now push anything that may be remaining
- insertTrailing(hunk, mine);
- insertTrailing(hunk, their);
+ this._maxListeners = this._maxListeners || undefined;
+ }; // Obviously not all Emitters should be limited to 10. This function allows
+ // that to be increased. Set to zero for unlimited.
+
+
+ EventEmitter$2.prototype.setMaxListeners = function setMaxListeners(n) {
+ if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number');
+ this._maxListeners = n;
+ return this;
+ };
- calcLineCount(hunk);
+ function $getMaxListeners(that) {
+ if (that._maxListeners === undefined) return EventEmitter$2.defaultMaxListeners;
+ return that._maxListeners;
}
- function mutualChange(hunk, mine, their) {
- var myChanges = collectChange(mine),
- theirChanges = collectChange(their);
+ EventEmitter$2.prototype.getMaxListeners = function getMaxListeners() {
+ return $getMaxListeners(this);
+ }; // These standalone emit* functions are used to optimize calling of event
+ // handlers for fast cases because emit() itself often has a variable number of
+ // arguments and can be deoptimized because of that. These functions always have
+ // the same number of arguments and thus do not get deoptimized, so the code
+ // inside them can execute faster.
- if (allRemoves(myChanges) && allRemoves(theirChanges)) {
- // Special case for remove changes that are supersets of one another
- if ( /*istanbul ignore start*/(0, _array.arrayStartsWith) /*istanbul ignore end*/(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
- /*istanbul ignore start*/var _hunk$lines3;
- /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines3 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines3 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/myChanges));
- return;
- } else if ( /*istanbul ignore start*/(0, _array.arrayStartsWith) /*istanbul ignore end*/(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
- /*istanbul ignore start*/var _hunk$lines4;
+ function emitNone(handler, isFn, self) {
+ if (isFn) handler.call(self);else {
+ var len = handler.length;
+ var listeners = arrayClone(handler, len);
- /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines4 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines4 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/theirChanges));
- return;
+ for (var i = 0; i < len; ++i) {
+ listeners[i].call(self);
}
- } else if ( /*istanbul ignore start*/(0, _array.arrayEqual) /*istanbul ignore end*/(myChanges, theirChanges)) {
- /*istanbul ignore start*/var _hunk$lines5;
-
- /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines5 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines5 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/myChanges));
- return;
}
-
- conflict(hunk, myChanges, theirChanges);
}
- function removal(hunk, mine, their, swap) {
- var myChanges = collectChange(mine),
- theirChanges = collectContext(their, myChanges);
- if (theirChanges.merged) {
- /*istanbul ignore start*/var _hunk$lines6;
+ function emitOne(handler, isFn, self, arg1) {
+ if (isFn) handler.call(self, arg1);else {
+ var len = handler.length;
+ var listeners = arrayClone(handler, len);
- /*istanbul ignore end*/ /*istanbul ignore start*/(_hunk$lines6 = /*istanbul ignore end*/hunk.lines).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_hunk$lines6 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/theirChanges.merged));
- } else {
- conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
+ for (var i = 0; i < len; ++i) {
+ listeners[i].call(self, arg1);
+ }
}
}
- function conflict(hunk, mine, their) {
- hunk.conflict = true;
- hunk.lines.push({
- conflict: true,
- mine: mine,
- theirs: their
- });
- }
+ function emitTwo(handler, isFn, self, arg1, arg2) {
+ if (isFn) handler.call(self, arg1, arg2);else {
+ var len = handler.length;
+ var listeners = arrayClone(handler, len);
- function insertLeading(hunk, insert, their) {
- while (insert.offset < their.offset && insert.index < insert.lines.length) {
- var line = insert.lines[insert.index++];
- hunk.lines.push(line);
- insert.offset++;
+ for (var i = 0; i < len; ++i) {
+ listeners[i].call(self, arg1, arg2);
+ }
}
}
- function insertTrailing(hunk, insert) {
- while (insert.index < insert.lines.length) {
- var line = insert.lines[insert.index++];
- hunk.lines.push(line);
+
+ function emitThree(handler, isFn, self, arg1, arg2, arg3) {
+ if (isFn) handler.call(self, arg1, arg2, arg3);else {
+ var len = handler.length;
+ var listeners = arrayClone(handler, len);
+
+ for (var i = 0; i < len; ++i) {
+ listeners[i].call(self, arg1, arg2, arg3);
+ }
}
}
- function collectChange(state) {
- var ret = [],
- operation = state.lines[state.index][0];
- while (state.index < state.lines.length) {
- var line = state.lines[state.index];
+ function emitMany(handler, isFn, self, args) {
+ if (isFn) handler.apply(self, args);else {
+ var len = handler.length;
+ var listeners = arrayClone(handler, len);
- // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
- if (operation === '-' && line[0] === '+') {
- operation = '+';
+ for (var i = 0; i < len; ++i) {
+ listeners[i].apply(self, args);
}
+ }
+ }
- if (operation === line[0]) {
- ret.push(line);
- state.index++;
+ EventEmitter$2.prototype.emit = function emit(type) {
+ var er, handler, len, args, i, events, domain;
+ var doError = type === 'error';
+ events = this._events;
+ if (events) doError = doError && events.error == null;else if (!doError) return false;
+ domain = this.domain; // If there is no 'error' event listener then throw.
+
+ if (doError) {
+ er = arguments[1];
+
+ if (domain) {
+ if (!er) er = new Error('Uncaught, unspecified "error" event');
+ er.domainEmitter = this;
+ er.domain = domain;
+ er.domainThrown = false;
+ domain.emit('error', er);
+ } else if (er instanceof Error) {
+ throw er; // Unhandled 'error' event
} else {
- break;
+ // At least give some kind of context to the user
+ var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
+ err.context = er;
+ throw err;
}
+
+ return false;
}
- return ret;
- }
- function collectContext(state, matchChanges) {
- var changes = [],
- merged = [],
- matchIndex = 0,
- contextChanges = false,
- conflicted = false;
- while (matchIndex < matchChanges.length && state.index < state.lines.length) {
- var change = state.lines[state.index],
- match = matchChanges[matchIndex];
-
- // Once we've hit our add, then we are done
- if (match[0] === '+') {
- break;
- }
+ handler = events[type];
+ if (!handler) return false;
+ var isFn = typeof handler === 'function';
+ len = arguments.length;
- contextChanges = contextChanges || change[0] !== ' ';
+ switch (len) {
+ // fast cases
+ case 1:
+ emitNone(handler, isFn, this);
+ break;
- merged.push(match);
- matchIndex++;
+ case 2:
+ emitOne(handler, isFn, this, arguments[1]);
+ break;
- // Consume any additions in the other block as a conflict to attempt
- // to pull in the remaining context after this
- if (change[0] === '+') {
- conflicted = true;
+ case 3:
+ emitTwo(handler, isFn, this, arguments[1], arguments[2]);
+ break;
- while (change[0] === '+') {
- changes.push(change);
- change = state.lines[++state.index];
- }
- }
+ case 4:
+ emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
+ break;
+ // slower
- if (match.substr(1) === change.substr(1)) {
- changes.push(change);
- state.index++;
- } else {
- conflicted = true;
- }
- }
+ default:
+ args = new Array(len - 1);
- if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
- conflicted = true;
- }
+ for (i = 1; i < len; i++) {
+ args[i - 1] = arguments[i];
+ }
- if (conflicted) {
- return changes;
+ emitMany(handler, isFn, this, args);
}
+ return true;
+ };
- while (matchIndex < matchChanges.length) {
- merged.push(matchChanges[matchIndex++]);
- }
+ function _addListener(target, type, listener, prepend) {
+ var m;
+ var events;
+ var existing;
+ if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
+ events = target._events;
- return {
- merged: merged,
- changes: changes
- };
- }
+ if (!events) {
+ events = target._events = new EventHandlers();
+ target._eventsCount = 0;
+ } else {
+ // To avoid recursion in the case that type === "newListener"! Before
+ // adding it to the listeners, first emit "newListener".
+ if (events.newListener) {
+ target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the
+ // this._events to be assigned to a new object
- function allRemoves(changes) {
- return changes.reduce(function (prev, change) {
- return prev && change[0] === '-';
- }, true);
- }
- function skipRemoveSuperset(state, removeChanges, delta) {
- for (var i = 0; i < delta; i++) {
- var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
- if (state.lines[state.index + i] !== ' ' + changeContent) {
- return false;
+ events = target._events;
}
- }
- state.index += delta;
- return true;
- }
+ existing = events[type];
+ }
- function calcOldNewLineCount(lines) {
- var oldLines = 0;
- var newLines = 0;
+ if (!existing) {
+ // Optimize the case of one listener. Don't need the extra array object.
+ existing = events[type] = listener;
+ ++target._eventsCount;
+ } else {
+ if (typeof existing === 'function') {
+ // Adding the second element, need to change to array.
+ existing = events[type] = prepend ? [listener, existing] : [existing, listener];
+ } else {
+ // If we've already got an array, just append.
+ if (prepend) {
+ existing.unshift(listener);
+ } else {
+ existing.push(listener);
+ }
+ } // Check for listener leak
- lines.forEach(function (line) {
- if (typeof line !== 'string') {
- var myCount = calcOldNewLineCount(line.mine);
- var theirCount = calcOldNewLineCount(line.theirs);
- if (oldLines !== undefined) {
- if (myCount.oldLines === theirCount.oldLines) {
- oldLines += myCount.oldLines;
- } else {
- oldLines = undefined;
- }
- }
+ if (!existing.warned) {
+ m = $getMaxListeners(target);
- if (newLines !== undefined) {
- if (myCount.newLines === theirCount.newLines) {
- newLines += myCount.newLines;
- } else {
- newLines = undefined;
- }
- }
- } else {
- if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
- newLines++;
- }
- if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
- oldLines++;
+ if (m && m > 0 && existing.length > m) {
+ existing.warned = true;
+ var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + type + ' listeners added. ' + 'Use emitter.setMaxListeners() to increase limit');
+ w.name = 'MaxListenersExceededWarning';
+ w.emitter = target;
+ w.type = type;
+ w.count = existing.length;
+ emitWarning$1(w);
}
}
- });
+ }
- return { oldLines: oldLines, newLines: newLines };
+ return target;
}
+ function emitWarning$1(e) {
+ typeof console.warn === 'function' ? console.warn(e) : console.log(e);
+ }
+ EventEmitter$2.prototype.addListener = function addListener(type, listener) {
+ return _addListener(this, type, listener, false);
+ };
-/***/ }),
-/* 14 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /*istanbul ignore start*/'use strict';
-
- exports.__esModule = true;
- exports. /*istanbul ignore end*/structuredPatch = structuredPatch;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = createTwoFilesPatch;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = createPatch;
-
- var /*istanbul ignore start*/_line = __webpack_require__(5) /*istanbul ignore end*/;
+ EventEmitter$2.prototype.on = EventEmitter$2.prototype.addListener;
- /*istanbul ignore start*/function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+ EventEmitter$2.prototype.prependListener = function prependListener(type, listener) {
+ return _addListener(this, type, listener, true);
+ };
- /*istanbul ignore end*/function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
- if (!options) {
- options = {};
- }
- if (typeof options.context === 'undefined') {
- options.context = 4;
- }
+ function _onceWrap(target, type, listener) {
+ var fired = false;
- var diff = /*istanbul ignore start*/(0, _line.diffLines) /*istanbul ignore end*/(oldStr, newStr, options);
- diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier
+ function g() {
+ target.removeListener(type, g);
- function contextLines(lines) {
- return lines.map(function (entry) {
- return ' ' + entry;
- });
+ if (!fired) {
+ fired = true;
+ listener.apply(target, arguments);
+ }
}
- var hunks = [];
- var oldRangeStart = 0,
- newRangeStart = 0,
- curRange = [],
- oldLine = 1,
- newLine = 1;
-
- /*istanbul ignore start*/var _loop = function _loop( /*istanbul ignore end*/i) {
- var current = diff[i],
- lines = current.lines || current.value.replace(/\n$/, '').split('\n');
- current.lines = lines;
+ g.listener = listener;
+ return g;
+ }
- if (current.added || current.removed) {
- /*istanbul ignore start*/var _curRange;
+ EventEmitter$2.prototype.once = function once(type, listener) {
+ if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
+ this.on(type, _onceWrap(this, type, listener));
+ return this;
+ };
- /*istanbul ignore end*/ // If we have previous context, start with that
- if (!oldRangeStart) {
- var prev = diff[i - 1];
- oldRangeStart = oldLine;
- newRangeStart = newLine;
+ EventEmitter$2.prototype.prependOnceListener = function prependOnceListener(type, listener) {
+ if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
+ this.prependListener(type, _onceWrap(this, type, listener));
+ return this;
+ }; // emits a 'removeListener' event iff the listener was removed
+
+
+ EventEmitter$2.prototype.removeListener = function removeListener(type, listener) {
+ var list, events, position, i, originalListener;
+ if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function');
+ events = this._events;
+ if (!events) return this;
+ list = events[type];
+ if (!list) return this;
+
+ if (list === listener || list.listener && list.listener === listener) {
+ if (--this._eventsCount === 0) this._events = new EventHandlers();else {
+ delete events[type];
+ if (events.removeListener) this.emit('removeListener', type, list.listener || listener);
+ }
+ } else if (typeof list !== 'function') {
+ position = -1;
- if (prev) {
- curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
- oldRangeStart -= curRange.length;
- newRangeStart -= curRange.length;
- }
+ for (i = list.length; i-- > 0;) {
+ if (list[i] === listener || list[i].listener && list[i].listener === listener) {
+ originalListener = list[i].listener;
+ position = i;
+ break;
}
+ }
+
+ if (position < 0) return this;
- // Output our changes
- /*istanbul ignore start*/(_curRange = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/lines.map(function (entry) {
- return (current.added ? '+' : '-') + entry;
- })));
+ if (list.length === 1) {
+ list[0] = undefined;
- // Track the updated file position
- if (current.added) {
- newLine += lines.length;
+ if (--this._eventsCount === 0) {
+ this._events = new EventHandlers();
+ return this;
} else {
- oldLine += lines.length;
+ delete events[type];
}
} else {
- // Identical context lines. Track line changes
- if (oldRangeStart) {
- // Close out any changes that have been output (or join overlapping)
- if (lines.length <= options.context * 2 && i < diff.length - 2) {
- /*istanbul ignore start*/var _curRange2;
-
- /*istanbul ignore end*/ // Overlapping
- /*istanbul ignore start*/(_curRange2 = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange2 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/contextLines(lines)));
- } else {
- /*istanbul ignore start*/var _curRange3;
-
- /*istanbul ignore end*/ // end the range and output
- var contextSize = Math.min(lines.length, options.context);
- /*istanbul ignore start*/(_curRange3 = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange3 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/contextLines(lines.slice(0, contextSize))));
-
- var hunk = {
- oldStart: oldRangeStart,
- oldLines: oldLine - oldRangeStart + contextSize,
- newStart: newRangeStart,
- newLines: newLine - newRangeStart + contextSize,
- lines: curRange
- };
- if (i >= diff.length - 2 && lines.length <= options.context) {
- // EOF is inside this hunk
- var oldEOFNewline = /\n$/.test(oldStr);
- var newEOFNewline = /\n$/.test(newStr);
- if (lines.length == 0 && !oldEOFNewline) {
- // special case: old has no eol and no trailing context; no-nl can end up before adds
- curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
- } else if (!oldEOFNewline || !newEOFNewline) {
- curRange.push('\\ No newline at end of file');
- }
- }
- hunks.push(hunk);
-
- oldRangeStart = 0;
- newRangeStart = 0;
- curRange = [];
- }
- }
- oldLine += lines.length;
- newLine += lines.length;
+ spliceOne(list, position);
}
- };
- for (var i = 0; i < diff.length; i++) {
- /*istanbul ignore start*/_loop( /*istanbul ignore end*/i);
+ if (events.removeListener) this.emit('removeListener', type, originalListener || listener);
}
- return {
- oldFileName: oldFileName, newFileName: newFileName,
- oldHeader: oldHeader, newHeader: newHeader,
- hunks: hunks
- };
- }
+ return this;
+ };
- function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
- var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
+ EventEmitter$2.prototype.removeAllListeners = function removeAllListeners(type) {
+ var listeners, events;
+ events = this._events;
+ if (!events) return this; // not listening for removeListener, no need to emit
+
+ if (!events.removeListener) {
+ if (arguments.length === 0) {
+ this._events = new EventHandlers();
+ this._eventsCount = 0;
+ } else if (events[type]) {
+ if (--this._eventsCount === 0) this._events = new EventHandlers();else delete events[type];
+ }
+
+ return this;
+ } // emit removeListener for all listeners on all events
+
+
+ if (arguments.length === 0) {
+ var keys = Object.keys(events);
- var ret = [];
- if (oldFileName == newFileName) {
- ret.push('Index: ' + oldFileName);
+ for (var i = 0, key; i < keys.length; ++i) {
+ key = keys[i];
+ if (key === 'removeListener') continue;
+ this.removeAllListeners(key);
+ }
+
+ this.removeAllListeners('removeListener');
+ this._events = new EventHandlers();
+ this._eventsCount = 0;
+ return this;
}
- ret.push('===================================================================');
- ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
- ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
- for (var i = 0; i < diff.hunks.length; i++) {
- var hunk = diff.hunks[i];
- ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
- ret.push.apply(ret, hunk.lines);
+ listeners = events[type];
+
+ if (typeof listeners === 'function') {
+ this.removeListener(type, listeners);
+ } else if (listeners) {
+ // LIFO order
+ do {
+ this.removeListener(type, listeners[listeners.length - 1]);
+ } while (listeners[0]);
}
- return ret.join('\n') + '\n';
- }
+ return this;
+ };
- function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
- return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
- }
+ EventEmitter$2.prototype.listeners = function listeners(type) {
+ var evlistener;
+ var ret;
+ var events = this._events;
+ if (!events) ret = [];else {
+ evlistener = events[type];
+ if (!evlistener) ret = [];else if (typeof evlistener === 'function') ret = [evlistener.listener || evlistener];else ret = unwrapListeners(evlistener);
+ }
+ return ret;
+ };
+ EventEmitter$2.listenerCount = function (emitter, type) {
+ if (typeof emitter.listenerCount === 'function') {
+ return emitter.listenerCount(type);
+ } else {
+ return listenerCount$1.call(emitter, type);
+ }
+ };
+ EventEmitter$2.prototype.listenerCount = listenerCount$1;
-/***/ }),
-/* 15 */
-/***/ (function(module, exports) {
+ function listenerCount$1(type) {
+ var events = this._events;
- /*istanbul ignore start*/"use strict";
+ if (events) {
+ var evlistener = events[type];
- exports.__esModule = true;
- exports. /*istanbul ignore end*/arrayEqual = arrayEqual;
- /*istanbul ignore start*/exports. /*istanbul ignore end*/arrayStartsWith = arrayStartsWith;
- function arrayEqual(a, b) {
- if (a.length !== b.length) {
- return false;
+ if (typeof evlistener === 'function') {
+ return 1;
+ } else if (evlistener) {
+ return evlistener.length;
+ }
}
- return arrayStartsWith(a, b);
+ return 0;
}
- function arrayStartsWith(array, start) {
- if (start.length > array.length) {
- return false;
- }
+ EventEmitter$2.prototype.eventNames = function eventNames() {
+ return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
+ }; // About 1.5x faster than the two-arg version of Array#splice().
- for (var i = 0; i < start.length; i++) {
- if (start[i] !== array[i]) {
- return false;
- }
+
+ function spliceOne(list, index) {
+ for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) {
+ list[i] = list[k];
}
- return true;
+ list.pop();
}
+ function arrayClone(arr, i) {
+ var copy = new Array(i);
+ while (i--) {
+ copy[i] = arr[i];
+ }
-/***/ }),
-/* 16 */
-/***/ (function(module, exports) {
-
- /*istanbul ignore start*/"use strict";
+ return copy;
+ }
- exports.__esModule = true;
- exports. /*istanbul ignore end*/convertChangesToDMP = convertChangesToDMP;
- // See: http://code.google.com/p/google-diff-match-patch/wiki/API
- function convertChangesToDMP(changes) {
- var ret = [],
- change = /*istanbul ignore start*/void 0 /*istanbul ignore end*/,
- operation = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
- for (var i = 0; i < changes.length; i++) {
- change = changes[i];
- if (change.added) {
- operation = 1;
- } else if (change.removed) {
- operation = -1;
- } else {
- operation = 0;
- }
+ function unwrapListeners(arr) {
+ var ret = new Array(arr.length);
- ret.push([operation, change.value]);
+ for (var i = 0; i < ret.length; ++i) {
+ ret[i] = arr[i].listener || arr[i];
}
+
return ret;
}
+ function ownKeys(object, enumerableOnly) {
+ var keys = Object.keys(object);
+ if (Object.getOwnPropertySymbols) {
+ var symbols = Object.getOwnPropertySymbols(object);
-/***/ }),
-/* 17 */
-/***/ (function(module, exports) {
+ if (enumerableOnly) {
+ symbols = symbols.filter(function (sym) {
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
+ });
+ }
- /*istanbul ignore start*/'use strict';
+ keys.push.apply(keys, symbols);
+ }
- exports.__esModule = true;
- exports. /*istanbul ignore end*/convertChangesToXML = convertChangesToXML;
- function convertChangesToXML(changes) {
- var ret = [];
- for (var i = 0; i < changes.length; i++) {
- var change = changes[i];
- if (change.added) {
- ret.push('');
- } else if (change.removed) {
- ret.push('');
- }
+ return keys;
+ }
- ret.push(escapeHTML(change.value));
+ function _objectSpread2(target) {
+ for (var i = 1; i < arguments.length; i++) {
+ var source = arguments[i] != null ? arguments[i] : {};
- if (change.added) {
- ret.push(' ');
- } else if (change.removed) {
- ret.push('');
+ if (i % 2) {
+ ownKeys(Object(source), true).forEach(function (key) {
+ _defineProperty(target, key, source[key]);
+ });
+ } else if (Object.getOwnPropertyDescriptors) {
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
+ } else {
+ ownKeys(Object(source)).forEach(function (key) {
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
+ });
}
}
- return ret.join('');
+
+ return target;
}
- function escapeHTML(s) {
- var n = s;
- n = n.replace(/&/g, '&');
- n = n.replace(//g, '>');
- n = n.replace(/"/g, '"');
+ function _typeof(obj) {
+ "@babel/helpers - typeof";
- return n;
+ if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
+ _typeof = function (obj) {
+ return typeof obj;
+ };
+ } else {
+ _typeof = function (obj) {
+ return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
+ };
+ }
+
+ return _typeof(obj);
+ }
+
+ function _asyncIterator(iterable) {
+ var method;
+
+ if (typeof Symbol !== "undefined") {
+ if (Symbol.asyncIterator) method = iterable[Symbol.asyncIterator];
+ if (method == null && Symbol.iterator) method = iterable[Symbol.iterator];
+ }
+
+ if (method == null) method = iterable["@@asyncIterator"];
+ if (method == null) method = iterable["@@iterator"];
+ if (method == null) throw new TypeError("Object is not async iterable");
+ return method.call(iterable);
+ }
+
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
+ try {
+ var info = gen[key](arg);
+ var value = info.value;
+ } catch (error) {
+ reject(error);
+ return;
+ }
+
+ if (info.done) {
+ resolve(value);
+ } else {
+ Promise.resolve(value).then(_next, _throw);
+ }
+ }
+
+ function _asyncToGenerator(fn) {
+ return function () {
+ var self = this,
+ args = arguments;
+ return new Promise(function (resolve, reject) {
+ var gen = fn.apply(self, args);
+
+ function _next(value) {
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
+ }
+
+ function _throw(err) {
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
+ }
+
+ _next(undefined);
+ });
+ };
+ }
+
+ function _classCallCheck(instance, Constructor) {
+ if (!(instance instanceof Constructor)) {
+ throw new TypeError("Cannot call a class as a function");
+ }
+ }
+
+ function _defineProperty(obj, key, value) {
+ if (key in obj) {
+ Object.defineProperty(obj, key, {
+ value: value,
+ enumerable: true,
+ configurable: true,
+ writable: true
+ });
+ } else {
+ obj[key] = value;
+ }
+
+ return obj;
+ }
+
+ function _inherits(subClass, superClass) {
+ if (typeof superClass !== "function" && superClass !== null) {
+ throw new TypeError("Super expression must either be null or a function");
+ }
+
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
+ constructor: {
+ value: subClass,
+ writable: true,
+ configurable: true
+ }
+ });
+ if (superClass) _setPrototypeOf(subClass, superClass);
+ }
+
+ function _getPrototypeOf(o) {
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
+ return o.__proto__ || Object.getPrototypeOf(o);
+ };
+ return _getPrototypeOf(o);
+ }
+
+ function _setPrototypeOf(o, p) {
+ _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
+ o.__proto__ = p;
+ return o;
+ };
+
+ return _setPrototypeOf(o, p);
+ }
+
+ function _isNativeReflectConstruct() {
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
+ if (Reflect.construct.sham) return false;
+ if (typeof Proxy === "function") return true;
+
+ try {
+ Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
+ return true;
+ } catch (e) {
+ return false;
+ }
+ }
+
+ function _assertThisInitialized(self) {
+ if (self === void 0) {
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
+ }
+
+ return self;
+ }
+
+ function _possibleConstructorReturn(self, call) {
+ if (call && (typeof call === "object" || typeof call === "function")) {
+ return call;
+ } else if (call !== void 0) {
+ throw new TypeError("Derived constructors may only return object or undefined");
+ }
+
+ return _assertThisInitialized(self);
+ }
+
+ function _createSuper(Derived) {
+ var hasNativeReflectConstruct = _isNativeReflectConstruct();
+
+ return function _createSuperInternal() {
+ var Super = _getPrototypeOf(Derived),
+ result;
+
+ if (hasNativeReflectConstruct) {
+ var NewTarget = _getPrototypeOf(this).constructor;
+
+ result = Reflect.construct(Super, arguments, NewTarget);
+ } else {
+ result = Super.apply(this, arguments);
+ }
+
+ return _possibleConstructorReturn(this, result);
+ };
+ }
+
+ function _toConsumableArray(arr) {
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
+ }
+
+ function _arrayWithoutHoles(arr) {
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
+ }
+
+ function _iterableToArray(iter) {
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
+ }
+
+ function _unsupportedIterableToArray(o, minLen) {
+ if (!o) return;
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
+ var n = Object.prototype.toString.call(o).slice(8, -1);
+ if (n === "Object" && o.constructor) n = o.constructor.name;
+ if (n === "Map" || n === "Set") return Array.from(o);
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
+ }
+
+ function _arrayLikeToArray(arr, len) {
+ if (len == null || len > arr.length) len = arr.length;
+
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
+
+ return arr2;
+ }
+
+ function _nonIterableSpread() {
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
+ }
+
+ var nativeJoin = [].join;
+
+ var ES3_STRINGS = indexedObject != Object;
+ var STRICT_METHOD$2 = arrayMethodIsStrict('join', ',');
+
+ // `Array.prototype.join` method
+ // https://tc39.es/ecma262/#sec-array.prototype.join
+ _export({ target: 'Array', proto: true, forced: ES3_STRINGS || !STRICT_METHOD$2 }, {
+ join: function join(separator) {
+ return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator);
+ }
+ });
+
+ // `String.prototype.codePointAt` methods implementation
+ var createMethod$3 = function (CONVERT_TO_STRING) {
+ return function ($this, pos) {
+ var S = toString_1(requireObjectCoercible($this));
+ var position = toInteger(pos);
+ var size = S.length;
+ var first, second;
+ if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
+ first = S.charCodeAt(position);
+ return first < 0xD800 || first > 0xDBFF || position + 1 === size
+ || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF
+ ? CONVERT_TO_STRING ? S.charAt(position) : first
+ : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
+ };
+ };
+
+ var stringMultibyte = {
+ // `String.prototype.codePointAt` method
+ // https://tc39.es/ecma262/#sec-string.prototype.codepointat
+ codeAt: createMethod$3(false),
+ // `String.prototype.at` method
+ // https://github.com/mathiasbynens/String.prototype.at
+ charAt: createMethod$3(true)
+ };
+
+ var charAt$1 = stringMultibyte.charAt;
+
+ // `AdvanceStringIndex` abstract operation
+ // https://tc39.es/ecma262/#sec-advancestringindex
+ var advanceStringIndex = function (S, index, unicode) {
+ return index + (unicode ? charAt$1(S, index).length : 1);
+ };
+
+ var floor$5 = Math.floor;
+ var replace = ''.replace;
+ var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d{1,2}|<[^>]*>)/g;
+ var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d{1,2})/g;
+
+ // `GetSubstitution` abstract operation
+ // https://tc39.es/ecma262/#sec-getsubstitution
+ var getSubstitution = function (matched, str, position, captures, namedCaptures, replacement) {
+ var tailPos = position + matched.length;
+ var m = captures.length;
+ var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
+ if (namedCaptures !== undefined) {
+ namedCaptures = toObject(namedCaptures);
+ symbols = SUBSTITUTION_SYMBOLS;
+ }
+ return replace.call(replacement, symbols, function (match, ch) {
+ var capture;
+ switch (ch.charAt(0)) {
+ case '$': return '$';
+ case '&': return matched;
+ case '`': return str.slice(0, position);
+ case "'": return str.slice(tailPos);
+ case '<':
+ capture = namedCaptures[ch.slice(1, -1)];
+ break;
+ default: // \d\d?
+ var n = +ch;
+ if (n === 0) return match;
+ if (n > m) {
+ var f = floor$5(n / 10);
+ if (f === 0) return match;
+ if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1);
+ return match;
+ }
+ capture = captures[n - 1];
+ }
+ return capture === undefined ? '' : capture;
+ });
+ };
+
+ var REPLACE = wellKnownSymbol('replace');
+ var max$1 = Math.max;
+ var min$4 = Math.min;
+
+ var maybeToString = function (it) {
+ return it === undefined ? it : String(it);
+ };
+
+ // IE <= 11 replaces $0 with the whole match, as if it was $&
+ // https://stackoverflow.com/questions/6024666/getting-ie-to-replace-a-regex-with-the-literal-string-0
+ var REPLACE_KEEPS_$0 = (function () {
+ // eslint-disable-next-line regexp/prefer-escape-replacement-dollar-char -- required for testing
+ return 'a'.replace(/./, '$0') === '$0';
+ })();
+
+ // Safari <= 13.0.3(?) substitutes nth capture where n>m with an empty string
+ var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = (function () {
+ if (/./[REPLACE]) {
+ return /./[REPLACE]('a', '$0') === '';
+ }
+ return false;
+ })();
+
+ var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () {
+ var re = /./;
+ re.exec = function () {
+ var result = [];
+ result.groups = { a: '7' };
+ return result;
+ };
+ // eslint-disable-next-line regexp/no-useless-dollar-replacements -- false positive
+ return ''.replace(re, '$ ') !== '7';
+ });
+
+ // @@replace logic
+ fixRegexpWellKnownSymbolLogic('replace', function (_, nativeReplace, maybeCallNative) {
+ var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? '$' : '$0';
+
+ return [
+ // `String.prototype.replace` method
+ // https://tc39.es/ecma262/#sec-string.prototype.replace
+ function replace(searchValue, replaceValue) {
+ var O = requireObjectCoercible(this);
+ var replacer = searchValue == undefined ? undefined : getMethod(searchValue, REPLACE);
+ return replacer
+ ? replacer.call(searchValue, O, replaceValue)
+ : nativeReplace.call(toString_1(O), searchValue, replaceValue);
+ },
+ // `RegExp.prototype[@@replace]` method
+ // https://tc39.es/ecma262/#sec-regexp.prototype-@@replace
+ function (string, replaceValue) {
+ var rx = anObject(this);
+ var S = toString_1(string);
+
+ if (
+ typeof replaceValue === 'string' &&
+ replaceValue.indexOf(UNSAFE_SUBSTITUTE) === -1 &&
+ replaceValue.indexOf('$<') === -1
+ ) {
+ var res = maybeCallNative(nativeReplace, rx, S, replaceValue);
+ if (res.done) return res.value;
+ }
+
+ var functionalReplace = isCallable(replaceValue);
+ if (!functionalReplace) replaceValue = toString_1(replaceValue);
+
+ var global = rx.global;
+ if (global) {
+ var fullUnicode = rx.unicode;
+ rx.lastIndex = 0;
+ }
+ var results = [];
+ while (true) {
+ var result = regexpExecAbstract(rx, S);
+ if (result === null) break;
+
+ results.push(result);
+ if (!global) break;
+
+ var matchStr = toString_1(result[0]);
+ if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
+ }
+
+ var accumulatedResult = '';
+ var nextSourcePosition = 0;
+ for (var i = 0; i < results.length; i++) {
+ result = results[i];
+
+ var matched = toString_1(result[0]);
+ var position = max$1(min$4(toInteger(result.index), S.length), 0);
+ var captures = [];
+ // NOTE: This is equivalent to
+ // captures = result.slice(1).map(maybeToString)
+ // but for some reason `nativeSlice.call(result, 1, result.length)` (called in
+ // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and
+ // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.
+ for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j]));
+ var namedCaptures = result.groups;
+ if (functionalReplace) {
+ var replacerArgs = [matched].concat(captures, position, S);
+ if (namedCaptures !== undefined) replacerArgs.push(namedCaptures);
+ var replacement = toString_1(replaceValue.apply(undefined, replacerArgs));
+ } else {
+ replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue);
+ }
+ if (position >= nextSourcePosition) {
+ accumulatedResult += S.slice(nextSourcePosition, position) + replacement;
+ nextSourcePosition = position + matched.length;
+ }
+ }
+ return accumulatedResult + S.slice(nextSourcePosition);
+ }
+ ];
+ }, !REPLACE_SUPPORTS_NAMED_GROUPS || !REPLACE_KEEPS_$0 || REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE);
+
+ var aPossiblePrototype = function (argument) {
+ if (typeof argument === 'object' || isCallable(argument)) return argument;
+ throw TypeError("Can't set " + String(argument) + ' as a prototype');
+ };
+
+ /* eslint-disable no-proto -- safe */
+
+
+
+ // `Object.setPrototypeOf` method
+ // https://tc39.es/ecma262/#sec-object.setprototypeof
+ // Works with __proto__ only. Old v8 can't work with null proto objects.
+ // eslint-disable-next-line es/no-object-setprototypeof -- safe
+ var objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {
+ var CORRECT_SETTER = false;
+ var test = {};
+ var setter;
+ try {
+ // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
+ setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;
+ setter.call(test, []);
+ CORRECT_SETTER = test instanceof Array;
+ } catch (error) { /* empty */ }
+ return function setPrototypeOf(O, proto) {
+ anObject(O);
+ aPossiblePrototype(proto);
+ if (CORRECT_SETTER) setter.call(O, proto);
+ else O.__proto__ = proto;
+ return O;
+ };
+ }() : undefined);
+
+ // makes subclassing work correct for wrapped built-ins
+ var inheritIfRequired = function ($this, dummy, Wrapper) {
+ var NewTarget, NewTargetPrototype;
+ if (
+ // it can work only with native `setPrototypeOf`
+ objectSetPrototypeOf &&
+ // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
+ isCallable(NewTarget = dummy.constructor) &&
+ NewTarget !== Wrapper &&
+ isObject$1(NewTargetPrototype = NewTarget.prototype) &&
+ NewTargetPrototype !== Wrapper.prototype
+ ) objectSetPrototypeOf($this, NewTargetPrototype);
+ return $this;
+ };
+
+ // a string of all valid unicode whitespaces
+ var whitespaces = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002' +
+ '\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
+
+ var whitespace = '[' + whitespaces + ']';
+ var ltrim = RegExp('^' + whitespace + whitespace + '*');
+ var rtrim = RegExp(whitespace + whitespace + '*$');
+
+ // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
+ var createMethod$2 = function (TYPE) {
+ return function ($this) {
+ var string = toString_1(requireObjectCoercible($this));
+ if (TYPE & 1) string = string.replace(ltrim, '');
+ if (TYPE & 2) string = string.replace(rtrim, '');
+ return string;
+ };
+ };
+
+ var stringTrim = {
+ // `String.prototype.{ trimLeft, trimStart }` methods
+ // https://tc39.es/ecma262/#sec-string.prototype.trimstart
+ start: createMethod$2(1),
+ // `String.prototype.{ trimRight, trimEnd }` methods
+ // https://tc39.es/ecma262/#sec-string.prototype.trimend
+ end: createMethod$2(2),
+ // `String.prototype.trim` method
+ // https://tc39.es/ecma262/#sec-string.prototype.trim
+ trim: createMethod$2(3)
+ };
+
+ var getOwnPropertyNames$3 = objectGetOwnPropertyNames.f;
+ var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
+ var defineProperty$8 = objectDefineProperty.f;
+ var trim = stringTrim.trim;
+
+ var NUMBER = 'Number';
+ var NativeNumber = global_1[NUMBER];
+ var NumberPrototype = NativeNumber.prototype;
+
+ // Opera ~12 has broken Object#toString
+ var BROKEN_CLASSOF = classofRaw(objectCreate(NumberPrototype)) == NUMBER;
+
+ // `ToNumber` abstract operation
+ // https://tc39.es/ecma262/#sec-tonumber
+ var toNumber = function (argument) {
+ if (isSymbol$1(argument)) throw TypeError('Cannot convert a Symbol value to a number');
+ var it = toPrimitive(argument, 'number');
+ var first, third, radix, maxCode, digits, length, index, code;
+ if (typeof it == 'string' && it.length > 2) {
+ it = trim(it);
+ first = it.charCodeAt(0);
+ if (first === 43 || first === 45) {
+ third = it.charCodeAt(2);
+ if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix
+ } else if (first === 48) {
+ switch (it.charCodeAt(1)) {
+ case 66: case 98: radix = 2; maxCode = 49; break; // fast equal of /^0b[01]+$/i
+ case 79: case 111: radix = 8; maxCode = 55; break; // fast equal of /^0o[0-7]+$/i
+ default: return +it;
+ }
+ digits = it.slice(2);
+ length = digits.length;
+ for (index = 0; index < length; index++) {
+ code = digits.charCodeAt(index);
+ // parseInt parses a string to a first unavailable symbol
+ // but ToNumber should return NaN if a string contains unavailable symbols
+ if (code < 48 || code > maxCode) return NaN;
+ } return parseInt(digits, radix);
+ }
+ } return +it;
+ };
+
+ // `Number` constructor
+ // https://tc39.es/ecma262/#sec-number-constructor
+ if (isForced_1(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) {
+ var NumberWrapper = function Number(value) {
+ var it = arguments.length < 1 ? 0 : value;
+ var dummy = this;
+ return dummy instanceof NumberWrapper
+ // check on 1..constructor(foo) case
+ && (BROKEN_CLASSOF ? fails(function () { NumberPrototype.valueOf.call(dummy); }) : classofRaw(dummy) != NUMBER)
+ ? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it);
+ };
+ for (var keys$3 = descriptors ? getOwnPropertyNames$3(NativeNumber) : (
+ // ES3:
+ 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
+ // ES2015 (in case, if modules with ES2015 Number statics required before):
+ 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
+ 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger,' +
+ // ESNext
+ 'fromString,range'
+ ).split(','), j$1 = 0, key$1; keys$3.length > j$1; j$1++) {
+ if (has$1(NativeNumber, key$1 = keys$3[j$1]) && !has$1(NumberWrapper, key$1)) {
+ defineProperty$8(NumberWrapper, key$1, getOwnPropertyDescriptor$1(NativeNumber, key$1));
+ }
+ }
+ NumberWrapper.prototype = NumberPrototype;
+ NumberPrototype.constructor = NumberWrapper;
+ redefine(global_1, NUMBER, NumberWrapper);
+ }
+
+ var MATCH$2 = wellKnownSymbol('match');
+
+ // `IsRegExp` abstract operation
+ // https://tc39.es/ecma262/#sec-isregexp
+ var isRegexp = function (it) {
+ var isRegExp;
+ return isObject$1(it) && ((isRegExp = it[MATCH$2]) !== undefined ? !!isRegExp : classofRaw(it) == 'RegExp');
+ };
+
+ var SPECIES$3 = wellKnownSymbol('species');
+
+ var setSpecies = function (CONSTRUCTOR_NAME) {
+ var Constructor = getBuiltIn(CONSTRUCTOR_NAME);
+ var defineProperty = objectDefineProperty.f;
+
+ if (descriptors && Constructor && !Constructor[SPECIES$3]) {
+ defineProperty(Constructor, SPECIES$3, {
+ configurable: true,
+ get: function () { return this; }
+ });
+ }
+ };
+
+ var defineProperty$7 = objectDefineProperty.f;
+ var getOwnPropertyNames$2 = objectGetOwnPropertyNames.f;
+
+
+
+
+
+
+
+ var enforceInternalState = internalState.enforce;
+
+
+
+
+
+ var MATCH$1 = wellKnownSymbol('match');
+ var NativeRegExp = global_1.RegExp;
+ var RegExpPrototype = NativeRegExp.prototype;
+ // TODO: Use only propper RegExpIdentifierName
+ var IS_NCG = /^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/;
+ var re1 = /a/g;
+ var re2 = /a/g;
+
+ // "new" should create a new object, old webkit bug
+ var CORRECT_NEW = new NativeRegExp(re1) !== re1;
+
+ var UNSUPPORTED_Y$1 = regexpStickyHelpers.UNSUPPORTED_Y;
+
+ var BASE_FORCED = descriptors &&
+ (!CORRECT_NEW || UNSUPPORTED_Y$1 || regexpUnsupportedDotAll || regexpUnsupportedNcg || fails(function () {
+ re2[MATCH$1] = false;
+ // RegExp constructor can alter flags and IsRegExp works correct with @@match
+ return NativeRegExp(re1) != re1 || NativeRegExp(re2) == re2 || NativeRegExp(re1, 'i') != '/a/i';
+ }));
+
+ var handleDotAll = function (string) {
+ var length = string.length;
+ var index = 0;
+ var result = '';
+ var brackets = false;
+ var chr;
+ for (; index <= length; index++) {
+ chr = string.charAt(index);
+ if (chr === '\\') {
+ result += chr + string.charAt(++index);
+ continue;
+ }
+ if (!brackets && chr === '.') {
+ result += '[\\s\\S]';
+ } else {
+ if (chr === '[') {
+ brackets = true;
+ } else if (chr === ']') {
+ brackets = false;
+ } result += chr;
+ }
+ } return result;
+ };
+
+ var handleNCG = function (string) {
+ var length = string.length;
+ var index = 0;
+ var result = '';
+ var named = [];
+ var names = {};
+ var brackets = false;
+ var ncg = false;
+ var groupid = 0;
+ var groupname = '';
+ var chr;
+ for (; index <= length; index++) {
+ chr = string.charAt(index);
+ if (chr === '\\') {
+ chr = chr + string.charAt(++index);
+ } else if (chr === ']') {
+ brackets = false;
+ } else if (!brackets) switch (true) {
+ case chr === '[':
+ brackets = true;
+ break;
+ case chr === '(':
+ if (IS_NCG.test(string.slice(index + 1))) {
+ index += 2;
+ ncg = true;
+ }
+ result += chr;
+ groupid++;
+ continue;
+ case chr === '>' && ncg:
+ if (groupname === '' || has$1(names, groupname)) {
+ throw new SyntaxError('Invalid capture group name');
+ }
+ names[groupname] = true;
+ named.push([groupname, groupid]);
+ ncg = false;
+ groupname = '';
+ continue;
+ }
+ if (ncg) groupname += chr;
+ else result += chr;
+ } return [result, named];
+ };
+
+ // `RegExp` constructor
+ // https://tc39.es/ecma262/#sec-regexp-constructor
+ if (isForced_1('RegExp', BASE_FORCED)) {
+ var RegExpWrapper = function RegExp(pattern, flags) {
+ var thisIsRegExp = this instanceof RegExpWrapper;
+ var patternIsRegExp = isRegexp(pattern);
+ var flagsAreUndefined = flags === undefined;
+ var groups = [];
+ var rawPattern = pattern;
+ var rawFlags, dotAll, sticky, handled, result, state;
+
+ if (!thisIsRegExp && patternIsRegExp && flagsAreUndefined && pattern.constructor === RegExpWrapper) {
+ return pattern;
+ }
+
+ if (patternIsRegExp || pattern instanceof RegExpWrapper) {
+ pattern = pattern.source;
+ if (flagsAreUndefined) flags = 'flags' in rawPattern ? rawPattern.flags : regexpFlags.call(rawPattern);
+ }
+
+ pattern = pattern === undefined ? '' : toString_1(pattern);
+ flags = flags === undefined ? '' : toString_1(flags);
+ rawPattern = pattern;
+
+ if (regexpUnsupportedDotAll && 'dotAll' in re1) {
+ dotAll = !!flags && flags.indexOf('s') > -1;
+ if (dotAll) flags = flags.replace(/s/g, '');
+ }
+
+ rawFlags = flags;
+
+ if (UNSUPPORTED_Y$1 && 'sticky' in re1) {
+ sticky = !!flags && flags.indexOf('y') > -1;
+ if (sticky) flags = flags.replace(/y/g, '');
+ }
+
+ if (regexpUnsupportedNcg) {
+ handled = handleNCG(pattern);
+ pattern = handled[0];
+ groups = handled[1];
+ }
+
+ result = inheritIfRequired(NativeRegExp(pattern, flags), thisIsRegExp ? this : RegExpPrototype, RegExpWrapper);
+
+ if (dotAll || sticky || groups.length) {
+ state = enforceInternalState(result);
+ if (dotAll) {
+ state.dotAll = true;
+ state.raw = RegExpWrapper(handleDotAll(pattern), rawFlags);
+ }
+ if (sticky) state.sticky = true;
+ if (groups.length) state.groups = groups;
+ }
+
+ if (pattern !== rawPattern) try {
+ // fails in old engines, but we have no alternatives for unsupported regex syntax
+ createNonEnumerableProperty(result, 'source', rawPattern === '' ? '(?:)' : rawPattern);
+ } catch (error) { /* empty */ }
+
+ return result;
+ };
+
+ var proxy = function (key) {
+ key in RegExpWrapper || defineProperty$7(RegExpWrapper, key, {
+ configurable: true,
+ get: function () { return NativeRegExp[key]; },
+ set: function (it) { NativeRegExp[key] = it; }
+ });
+ };
+
+ for (var keys$2 = getOwnPropertyNames$2(NativeRegExp), index = 0; keys$2.length > index;) {
+ proxy(keys$2[index++]);
+ }
+
+ RegExpPrototype.constructor = RegExpWrapper;
+ RegExpWrapper.prototype = RegExpPrototype;
+ redefine(global_1, 'RegExp', RegExpWrapper);
+ }
+
+ // https://tc39.es/ecma262/#sec-get-regexp-@@species
+ setSpecies('RegExp');
+
+ /* eslint-disable es/no-object-getownpropertynames -- safe */
+
+ var $getOwnPropertyNames$1 = objectGetOwnPropertyNames.f;
+
+ var toString$3 = {}.toString;
+
+ var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
+ ? Object.getOwnPropertyNames(window) : [];
+
+ var getWindowNames = function (it) {
+ try {
+ return $getOwnPropertyNames$1(it);
+ } catch (error) {
+ return windowNames.slice();
+ }
+ };
+
+ // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
+ var f$2 = function getOwnPropertyNames(it) {
+ return windowNames && toString$3.call(it) == '[object Window]'
+ ? getWindowNames(it)
+ : $getOwnPropertyNames$1(toIndexedObject(it));
+ };
+
+ var objectGetOwnPropertyNamesExternal = {
+ f: f$2
+ };
+
+ var getOwnPropertyNames$1 = objectGetOwnPropertyNamesExternal.f;
+
+ // eslint-disable-next-line es/no-object-getownpropertynames -- required for testing
+ var FAILS_ON_PRIMITIVES$2 = fails(function () { return !Object.getOwnPropertyNames(1); });
+
+ // `Object.getOwnPropertyNames` method
+ // https://tc39.es/ecma262/#sec-object.getownpropertynames
+ _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$2 }, {
+ getOwnPropertyNames: getOwnPropertyNames$1
+ });
+
+ var $map$1 = arrayIteration.map;
+
+
+ var HAS_SPECIES_SUPPORT$1 = arrayMethodHasSpeciesSupport('map');
+
+ // `Array.prototype.map` method
+ // https://tc39.es/ecma262/#sec-array.prototype.map
+ // with adding support of @@species
+ _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$1 }, {
+ map: function map(callbackfn /* , thisArg */) {
+ return $map$1(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
+ }
+ });
+
+ // @@match logic
+ fixRegexpWellKnownSymbolLogic('match', function (MATCH, nativeMatch, maybeCallNative) {
+ return [
+ // `String.prototype.match` method
+ // https://tc39.es/ecma262/#sec-string.prototype.match
+ function match(regexp) {
+ var O = requireObjectCoercible(this);
+ var matcher = regexp == undefined ? undefined : getMethod(regexp, MATCH);
+ return matcher ? matcher.call(regexp, O) : new RegExp(regexp)[MATCH](toString_1(O));
+ },
+ // `RegExp.prototype[@@match]` method
+ // https://tc39.es/ecma262/#sec-regexp.prototype-@@match
+ function (string) {
+ var rx = anObject(this);
+ var S = toString_1(string);
+ var res = maybeCallNative(nativeMatch, rx, S);
+
+ if (res.done) return res.value;
+
+ if (!rx.global) return regexpExecAbstract(rx, S);
+
+ var fullUnicode = rx.unicode;
+ rx.lastIndex = 0;
+ var A = [];
+ var n = 0;
+ var result;
+ while ((result = regexpExecAbstract(rx, S)) !== null) {
+ var matchStr = toString_1(result[0]);
+ A[n] = matchStr;
+ if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
+ n++;
+ }
+ return n === 0 ? null : A;
+ }
+ ];
+ });
+
+ var nativeGetOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
+
+
+ var FAILS_ON_PRIMITIVES$1 = fails(function () { nativeGetOwnPropertyDescriptor$1(1); });
+ var FORCED$7 = !descriptors || FAILS_ON_PRIMITIVES$1;
+
+ // `Object.getOwnPropertyDescriptor` method
+ // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
+ _export({ target: 'Object', stat: true, forced: FORCED$7, sham: !descriptors }, {
+ getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) {
+ return nativeGetOwnPropertyDescriptor$1(toIndexedObject(it), key);
+ }
+ });
+
+ // `Assert: IsConstructor(argument) is true`
+ var aConstructor = function (argument) {
+ if (isConstructor(argument)) return argument;
+ throw TypeError(tryToString(argument) + ' is not a constructor');
+ };
+
+ var SPECIES$2 = wellKnownSymbol('species');
+
+ // `SpeciesConstructor` abstract operation
+ // https://tc39.es/ecma262/#sec-speciesconstructor
+ var speciesConstructor = function (O, defaultConstructor) {
+ var C = anObject(O).constructor;
+ var S;
+ return C === undefined || (S = anObject(C)[SPECIES$2]) == undefined ? defaultConstructor : aConstructor(S);
+ };
+
+ var UNSUPPORTED_Y = regexpStickyHelpers.UNSUPPORTED_Y;
+ var arrayPush = [].push;
+ var min$3 = Math.min;
+ var MAX_UINT32 = 0xFFFFFFFF;
+
+ // Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec
+ // Weex JS has frozen built-in prototypes, so use try / catch wrapper
+ var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails(function () {
+ // eslint-disable-next-line regexp/no-empty-group -- required for testing
+ var re = /(?:)/;
+ var originalExec = re.exec;
+ re.exec = function () { return originalExec.apply(this, arguments); };
+ var result = 'ab'.split(re);
+ return result.length !== 2 || result[0] !== 'a' || result[1] !== 'b';
+ });
+
+ // @@split logic
+ fixRegexpWellKnownSymbolLogic('split', function (SPLIT, nativeSplit, maybeCallNative) {
+ var internalSplit;
+ if (
+ 'abbc'.split(/(b)*/)[1] == 'c' ||
+ // eslint-disable-next-line regexp/no-empty-group -- required for testing
+ 'test'.split(/(?:)/, -1).length != 4 ||
+ 'ab'.split(/(?:ab)*/).length != 2 ||
+ '.'.split(/(.?)(.?)/).length != 4 ||
+ // eslint-disable-next-line regexp/no-empty-capturing-group, regexp/no-empty-group -- required for testing
+ '.'.split(/()()/).length > 1 ||
+ ''.split(/.?/).length
+ ) {
+ // based on es5-shim implementation, need to rework it
+ internalSplit = function (separator, limit) {
+ var string = toString_1(requireObjectCoercible(this));
+ var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
+ if (lim === 0) return [];
+ if (separator === undefined) return [string];
+ // If `separator` is not a regex, use native split
+ if (!isRegexp(separator)) {
+ return nativeSplit.call(string, separator, lim);
+ }
+ var output = [];
+ var flags = (separator.ignoreCase ? 'i' : '') +
+ (separator.multiline ? 'm' : '') +
+ (separator.unicode ? 'u' : '') +
+ (separator.sticky ? 'y' : '');
+ var lastLastIndex = 0;
+ // Make `global` and avoid `lastIndex` issues by working with a copy
+ var separatorCopy = new RegExp(separator.source, flags + 'g');
+ var match, lastIndex, lastLength;
+ while (match = regexpExec.call(separatorCopy, string)) {
+ lastIndex = separatorCopy.lastIndex;
+ if (lastIndex > lastLastIndex) {
+ output.push(string.slice(lastLastIndex, match.index));
+ if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1));
+ lastLength = match[0].length;
+ lastLastIndex = lastIndex;
+ if (output.length >= lim) break;
+ }
+ if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop
+ }
+ if (lastLastIndex === string.length) {
+ if (lastLength || !separatorCopy.test('')) output.push('');
+ } else output.push(string.slice(lastLastIndex));
+ return output.length > lim ? output.slice(0, lim) : output;
+ };
+ // Chakra, V8
+ } else if ('0'.split(undefined, 0).length) {
+ internalSplit = function (separator, limit) {
+ return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit);
+ };
+ } else internalSplit = nativeSplit;
+
+ return [
+ // `String.prototype.split` method
+ // https://tc39.es/ecma262/#sec-string.prototype.split
+ function split(separator, limit) {
+ var O = requireObjectCoercible(this);
+ var splitter = separator == undefined ? undefined : getMethod(separator, SPLIT);
+ return splitter
+ ? splitter.call(separator, O, limit)
+ : internalSplit.call(toString_1(O), separator, limit);
+ },
+ // `RegExp.prototype[@@split]` method
+ // https://tc39.es/ecma262/#sec-regexp.prototype-@@split
+ //
+ // NOTE: This cannot be properly polyfilled in engines that don't support
+ // the 'y' flag.
+ function (string, limit) {
+ var rx = anObject(this);
+ var S = toString_1(string);
+ var res = maybeCallNative(internalSplit, rx, S, limit, internalSplit !== nativeSplit);
+
+ if (res.done) return res.value;
+
+ var C = speciesConstructor(rx, RegExp);
+
+ var unicodeMatching = rx.unicode;
+ var flags = (rx.ignoreCase ? 'i' : '') +
+ (rx.multiline ? 'm' : '') +
+ (rx.unicode ? 'u' : '') +
+ (UNSUPPORTED_Y ? 'g' : 'y');
+
+ // ^(? + rx + ) is needed, in combination with some S slicing, to
+ // simulate the 'y' flag.
+ var splitter = new C(UNSUPPORTED_Y ? '^(?:' + rx.source + ')' : rx, flags);
+ var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
+ if (lim === 0) return [];
+ if (S.length === 0) return regexpExecAbstract(splitter, S) === null ? [S] : [];
+ var p = 0;
+ var q = 0;
+ var A = [];
+ while (q < S.length) {
+ splitter.lastIndex = UNSUPPORTED_Y ? 0 : q;
+ var z = regexpExecAbstract(splitter, UNSUPPORTED_Y ? S.slice(q) : S);
+ var e;
+ if (
+ z === null ||
+ (e = min$3(toLength(splitter.lastIndex + (UNSUPPORTED_Y ? q : 0)), S.length)) === p
+ ) {
+ q = advanceStringIndex(S, q, unicodeMatching);
+ } else {
+ A.push(S.slice(p, q));
+ if (A.length === lim) return A;
+ for (var i = 1; i <= z.length - 1; i++) {
+ A.push(z[i]);
+ if (A.length === lim) return A;
+ }
+ q = p = e;
+ }
+ }
+ A.push(S.slice(p));
+ return A;
+ }
+ ];
+ }, !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC, UNSUPPORTED_Y);
+
+ var UNSCOPABLES = wellKnownSymbol('unscopables');
+ var ArrayPrototype$1 = Array.prototype;
+
+ // Array.prototype[@@unscopables]
+ // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
+ if (ArrayPrototype$1[UNSCOPABLES] == undefined) {
+ objectDefineProperty.f(ArrayPrototype$1, UNSCOPABLES, {
+ configurable: true,
+ value: objectCreate(null)
+ });
+ }
+
+ // add a key to Array.prototype[@@unscopables]
+ var addToUnscopables = function (key) {
+ ArrayPrototype$1[UNSCOPABLES][key] = true;
+ };
+
+ var iterators = {};
+
+ var ITERATOR$6 = wellKnownSymbol('iterator');
+ var BUGGY_SAFARI_ITERATORS$1 = false;
+
+ // `%IteratorPrototype%` object
+ // https://tc39.es/ecma262/#sec-%iteratorprototype%-object
+ var IteratorPrototype$2, PrototypeOfArrayIteratorPrototype, arrayIterator;
+
+ /* eslint-disable es/no-array-prototype-keys -- safe */
+ if ([].keys) {
+ arrayIterator = [].keys();
+ // Safari 8 has buggy iterators w/o `next`
+ if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS$1 = true;
+ else {
+ PrototypeOfArrayIteratorPrototype = objectGetPrototypeOf(objectGetPrototypeOf(arrayIterator));
+ if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype$2 = PrototypeOfArrayIteratorPrototype;
+ }
+ }
+
+ var NEW_ITERATOR_PROTOTYPE = IteratorPrototype$2 == undefined || fails(function () {
+ var test = {};
+ // FF44- legacy iterators case
+ return IteratorPrototype$2[ITERATOR$6].call(test) !== test;
+ });
+
+ if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype$2 = {};
+
+ // `%IteratorPrototype%[@@iterator]()` method
+ // https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
+ if (!isCallable(IteratorPrototype$2[ITERATOR$6])) {
+ redefine(IteratorPrototype$2, ITERATOR$6, function () {
+ return this;
+ });
+ }
+
+ var iteratorsCore = {
+ IteratorPrototype: IteratorPrototype$2,
+ BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS$1
+ };
+
+ var defineProperty$6 = objectDefineProperty.f;
+
+
+
+ var TO_STRING_TAG$2 = wellKnownSymbol('toStringTag');
+
+ var setToStringTag = function (it, TAG, STATIC) {
+ if (it && !has$1(it = STATIC ? it : it.prototype, TO_STRING_TAG$2)) {
+ defineProperty$6(it, TO_STRING_TAG$2, { configurable: true, value: TAG });
+ }
+ };
+
+ var IteratorPrototype$1 = iteratorsCore.IteratorPrototype;
+
+
+
+
+
+ var returnThis$1 = function () { return this; };
+
+ var createIteratorConstructor = function (IteratorConstructor, NAME, next) {
+ var TO_STRING_TAG = NAME + ' Iterator';
+ IteratorConstructor.prototype = objectCreate(IteratorPrototype$1, { next: createPropertyDescriptor(1, next) });
+ setToStringTag(IteratorConstructor, TO_STRING_TAG, false);
+ iterators[TO_STRING_TAG] = returnThis$1;
+ return IteratorConstructor;
+ };
+
+ var PROPER_FUNCTION_NAME$3 = functionName.PROPER;
+ var CONFIGURABLE_FUNCTION_NAME$1 = functionName.CONFIGURABLE;
+ var IteratorPrototype = iteratorsCore.IteratorPrototype;
+ var BUGGY_SAFARI_ITERATORS = iteratorsCore.BUGGY_SAFARI_ITERATORS;
+ var ITERATOR$5 = wellKnownSymbol('iterator');
+ var KEYS = 'keys';
+ var VALUES = 'values';
+ var ENTRIES = 'entries';
+
+ var returnThis = function () { return this; };
+
+ var defineIterator = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
+ createIteratorConstructor(IteratorConstructor, NAME, next);
+
+ var getIterationMethod = function (KIND) {
+ if (KIND === DEFAULT && defaultIterator) return defaultIterator;
+ if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND];
+ switch (KIND) {
+ case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };
+ case VALUES: return function values() { return new IteratorConstructor(this, KIND); };
+ case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };
+ } return function () { return new IteratorConstructor(this); };
+ };
+
+ var TO_STRING_TAG = NAME + ' Iterator';
+ var INCORRECT_VALUES_NAME = false;
+ var IterablePrototype = Iterable.prototype;
+ var nativeIterator = IterablePrototype[ITERATOR$5]
+ || IterablePrototype['@@iterator']
+ || DEFAULT && IterablePrototype[DEFAULT];
+ var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);
+ var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
+ var CurrentIteratorPrototype, methods, KEY;
+
+ // fix native
+ if (anyNativeIterator) {
+ CurrentIteratorPrototype = objectGetPrototypeOf(anyNativeIterator.call(new Iterable()));
+ if (CurrentIteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {
+ if (objectGetPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) {
+ if (objectSetPrototypeOf) {
+ objectSetPrototypeOf(CurrentIteratorPrototype, IteratorPrototype);
+ } else if (!isCallable(CurrentIteratorPrototype[ITERATOR$5])) {
+ redefine(CurrentIteratorPrototype, ITERATOR$5, returnThis);
+ }
+ }
+ // Set @@toStringTag to native iterators
+ setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true);
+ }
+ }
+
+ // fix Array.prototype.{ values, @@iterator }.name in V8 / FF
+ if (PROPER_FUNCTION_NAME$3 && DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
+ if (CONFIGURABLE_FUNCTION_NAME$1) {
+ createNonEnumerableProperty(IterablePrototype, 'name', VALUES);
+ } else {
+ INCORRECT_VALUES_NAME = true;
+ defaultIterator = function values() { return nativeIterator.call(this); };
+ }
+ }
+
+ // export additional methods
+ if (DEFAULT) {
+ methods = {
+ values: getIterationMethod(VALUES),
+ keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
+ entries: getIterationMethod(ENTRIES)
+ };
+ if (FORCED) for (KEY in methods) {
+ if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
+ redefine(IterablePrototype, KEY, methods[KEY]);
+ }
+ } else _export({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods);
+ }
+
+ // define iterator
+ if (IterablePrototype[ITERATOR$5] !== defaultIterator) {
+ redefine(IterablePrototype, ITERATOR$5, defaultIterator, { name: DEFAULT });
+ }
+ iterators[NAME] = defaultIterator;
+
+ return methods;
+ };
+
+ var ARRAY_ITERATOR = 'Array Iterator';
+ var setInternalState$5 = internalState.set;
+ var getInternalState$4 = internalState.getterFor(ARRAY_ITERATOR);
+
+ // `Array.prototype.entries` method
+ // https://tc39.es/ecma262/#sec-array.prototype.entries
+ // `Array.prototype.keys` method
+ // https://tc39.es/ecma262/#sec-array.prototype.keys
+ // `Array.prototype.values` method
+ // https://tc39.es/ecma262/#sec-array.prototype.values
+ // `Array.prototype[@@iterator]` method
+ // https://tc39.es/ecma262/#sec-array.prototype-@@iterator
+ // `CreateArrayIterator` internal method
+ // https://tc39.es/ecma262/#sec-createarrayiterator
+ var es_array_iterator = defineIterator(Array, 'Array', function (iterated, kind) {
+ setInternalState$5(this, {
+ type: ARRAY_ITERATOR,
+ target: toIndexedObject(iterated), // target
+ index: 0, // next index
+ kind: kind // kind
+ });
+ // `%ArrayIteratorPrototype%.next` method
+ // https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next
+ }, function () {
+ var state = getInternalState$4(this);
+ var target = state.target;
+ var kind = state.kind;
+ var index = state.index++;
+ if (!target || index >= target.length) {
+ state.target = undefined;
+ return { value: undefined, done: true };
+ }
+ if (kind == 'keys') return { value: index, done: false };
+ if (kind == 'values') return { value: target[index], done: false };
+ return { value: [index, target[index]], done: false };
+ }, 'values');
+
+ // argumentsList[@@iterator] is %ArrayProto_values%
+ // https://tc39.es/ecma262/#sec-createunmappedargumentsobject
+ // https://tc39.es/ecma262/#sec-createmappedargumentsobject
+ iterators.Arguments = iterators.Array;
+
+ // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
+ addToUnscopables('keys');
+ addToUnscopables('values');
+ addToUnscopables('entries');
+
+ var ITERATOR$4 = wellKnownSymbol('iterator');
+ var SAFE_CLOSING = false;
+
+ try {
+ var called = 0;
+ var iteratorWithReturn = {
+ next: function () {
+ return { done: !!called++ };
+ },
+ 'return': function () {
+ SAFE_CLOSING = true;
+ }
+ };
+ iteratorWithReturn[ITERATOR$4] = function () {
+ return this;
+ };
+ // eslint-disable-next-line es/no-array-from, no-throw-literal -- required for testing
+ Array.from(iteratorWithReturn, function () { throw 2; });
+ } catch (error) { /* empty */ }
+
+ var checkCorrectnessOfIteration = function (exec, SKIP_CLOSING) {
+ if (!SKIP_CLOSING && !SAFE_CLOSING) return false;
+ var ITERATION_SUPPORT = false;
+ try {
+ var object = {};
+ object[ITERATOR$4] = function () {
+ return {
+ next: function () {
+ return { done: ITERATION_SUPPORT = true };
+ }
+ };
+ };
+ exec(object);
+ } catch (error) { /* empty */ }
+ return ITERATION_SUPPORT;
+ };
+
+ // eslint-disable-next-line es/no-typed-arrays -- safe
+ var arrayBufferNative = typeof ArrayBuffer !== 'undefined' && typeof DataView !== 'undefined';
+
+ var defineProperty$5 = objectDefineProperty.f;
+
+
+
+
+
+ var Int8Array$3 = global_1.Int8Array;
+ var Int8ArrayPrototype = Int8Array$3 && Int8Array$3.prototype;
+ var Uint8ClampedArray = global_1.Uint8ClampedArray;
+ var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;
+ var TypedArray = Int8Array$3 && objectGetPrototypeOf(Int8Array$3);
+ var TypedArrayPrototype = Int8ArrayPrototype && objectGetPrototypeOf(Int8ArrayPrototype);
+ var ObjectPrototype$2 = Object.prototype;
+ var isPrototypeOf = ObjectPrototype$2.isPrototypeOf;
+
+ var TO_STRING_TAG$1 = wellKnownSymbol('toStringTag');
+ var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG');
+ var TYPED_ARRAY_CONSTRUCTOR$1 = uid('TYPED_ARRAY_CONSTRUCTOR');
+ // Fixing native typed arrays in Opera Presto crashes the browser, see #595
+ var NATIVE_ARRAY_BUFFER_VIEWS$1 = arrayBufferNative && !!objectSetPrototypeOf && classof(global_1.opera) !== 'Opera';
+ var TYPED_ARRAY_TAG_REQIRED = false;
+ var NAME, Constructor, Prototype;
+
+ var TypedArrayConstructorsList = {
+ Int8Array: 1,
+ Uint8Array: 1,
+ Uint8ClampedArray: 1,
+ Int16Array: 2,
+ Uint16Array: 2,
+ Int32Array: 4,
+ Uint32Array: 4,
+ Float32Array: 4,
+ Float64Array: 8
+ };
+
+ var BigIntArrayConstructorsList = {
+ BigInt64Array: 8,
+ BigUint64Array: 8
+ };
+
+ var isView = function isView(it) {
+ if (!isObject$1(it)) return false;
+ var klass = classof(it);
+ return klass === 'DataView'
+ || has$1(TypedArrayConstructorsList, klass)
+ || has$1(BigIntArrayConstructorsList, klass);
+ };
+
+ var isTypedArray = function (it) {
+ if (!isObject$1(it)) return false;
+ var klass = classof(it);
+ return has$1(TypedArrayConstructorsList, klass)
+ || has$1(BigIntArrayConstructorsList, klass);
+ };
+
+ var aTypedArray$m = function (it) {
+ if (isTypedArray(it)) return it;
+ throw TypeError('Target is not a typed array');
+ };
+
+ var aTypedArrayConstructor$2 = function (C) {
+ if (isCallable(C) && (!objectSetPrototypeOf || isPrototypeOf.call(TypedArray, C))) return C;
+ throw TypeError(tryToString(C) + ' is not a typed array constructor');
+ };
+
+ var exportTypedArrayMethod$n = function (KEY, property, forced) {
+ if (!descriptors) return;
+ if (forced) for (var ARRAY in TypedArrayConstructorsList) {
+ var TypedArrayConstructor = global_1[ARRAY];
+ if (TypedArrayConstructor && has$1(TypedArrayConstructor.prototype, KEY)) try {
+ delete TypedArrayConstructor.prototype[KEY];
+ } catch (error) { /* empty */ }
+ }
+ if (!TypedArrayPrototype[KEY] || forced) {
+ redefine(TypedArrayPrototype, KEY, forced ? property
+ : NATIVE_ARRAY_BUFFER_VIEWS$1 && Int8ArrayPrototype[KEY] || property);
+ }
+ };
+
+ var exportTypedArrayStaticMethod = function (KEY, property, forced) {
+ var ARRAY, TypedArrayConstructor;
+ if (!descriptors) return;
+ if (objectSetPrototypeOf) {
+ if (forced) for (ARRAY in TypedArrayConstructorsList) {
+ TypedArrayConstructor = global_1[ARRAY];
+ if (TypedArrayConstructor && has$1(TypedArrayConstructor, KEY)) try {
+ delete TypedArrayConstructor[KEY];
+ } catch (error) { /* empty */ }
+ }
+ if (!TypedArray[KEY] || forced) {
+ // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable
+ try {
+ return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS$1 && TypedArray[KEY] || property);
+ } catch (error) { /* empty */ }
+ } else return;
+ }
+ for (ARRAY in TypedArrayConstructorsList) {
+ TypedArrayConstructor = global_1[ARRAY];
+ if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {
+ redefine(TypedArrayConstructor, KEY, property);
+ }
+ }
+ };
+
+ for (NAME in TypedArrayConstructorsList) {
+ Constructor = global_1[NAME];
+ Prototype = Constructor && Constructor.prototype;
+ if (Prototype) createNonEnumerableProperty(Prototype, TYPED_ARRAY_CONSTRUCTOR$1, Constructor);
+ else NATIVE_ARRAY_BUFFER_VIEWS$1 = false;
+ }
+
+ for (NAME in BigIntArrayConstructorsList) {
+ Constructor = global_1[NAME];
+ Prototype = Constructor && Constructor.prototype;
+ if (Prototype) createNonEnumerableProperty(Prototype, TYPED_ARRAY_CONSTRUCTOR$1, Constructor);
+ }
+
+ // WebKit bug - typed arrays constructors prototype is Object.prototype
+ if (!NATIVE_ARRAY_BUFFER_VIEWS$1 || !isCallable(TypedArray) || TypedArray === Function.prototype) {
+ // eslint-disable-next-line no-shadow -- safe
+ TypedArray = function TypedArray() {
+ throw TypeError('Incorrect invocation');
+ };
+ if (NATIVE_ARRAY_BUFFER_VIEWS$1) for (NAME in TypedArrayConstructorsList) {
+ if (global_1[NAME]) objectSetPrototypeOf(global_1[NAME], TypedArray);
+ }
+ }
+
+ if (!NATIVE_ARRAY_BUFFER_VIEWS$1 || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype$2) {
+ TypedArrayPrototype = TypedArray.prototype;
+ if (NATIVE_ARRAY_BUFFER_VIEWS$1) for (NAME in TypedArrayConstructorsList) {
+ if (global_1[NAME]) objectSetPrototypeOf(global_1[NAME].prototype, TypedArrayPrototype);
+ }
+ }
+
+ // WebKit bug - one more object in Uint8ClampedArray prototype chain
+ if (NATIVE_ARRAY_BUFFER_VIEWS$1 && objectGetPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {
+ objectSetPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);
+ }
+
+ if (descriptors && !has$1(TypedArrayPrototype, TO_STRING_TAG$1)) {
+ TYPED_ARRAY_TAG_REQIRED = true;
+ defineProperty$5(TypedArrayPrototype, TO_STRING_TAG$1, { get: function () {
+ return isObject$1(this) ? this[TYPED_ARRAY_TAG] : undefined;
+ } });
+ for (NAME in TypedArrayConstructorsList) if (global_1[NAME]) {
+ createNonEnumerableProperty(global_1[NAME], TYPED_ARRAY_TAG, NAME);
+ }
+ }
+
+ var arrayBufferViewCore = {
+ NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS$1,
+ TYPED_ARRAY_CONSTRUCTOR: TYPED_ARRAY_CONSTRUCTOR$1,
+ TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG,
+ aTypedArray: aTypedArray$m,
+ aTypedArrayConstructor: aTypedArrayConstructor$2,
+ exportTypedArrayMethod: exportTypedArrayMethod$n,
+ exportTypedArrayStaticMethod: exportTypedArrayStaticMethod,
+ isView: isView,
+ isTypedArray: isTypedArray,
+ TypedArray: TypedArray,
+ TypedArrayPrototype: TypedArrayPrototype
+ };
+
+ /* eslint-disable no-new -- required for testing */
+
+
+
+ var NATIVE_ARRAY_BUFFER_VIEWS = arrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS;
+
+ var ArrayBuffer$2 = global_1.ArrayBuffer;
+ var Int8Array$2 = global_1.Int8Array;
+
+ var typedArrayConstructorsRequireWrappers = !NATIVE_ARRAY_BUFFER_VIEWS || !fails(function () {
+ Int8Array$2(1);
+ }) || !fails(function () {
+ new Int8Array$2(-1);
+ }) || !checkCorrectnessOfIteration(function (iterable) {
+ new Int8Array$2();
+ new Int8Array$2(null);
+ new Int8Array$2(1.5);
+ new Int8Array$2(iterable);
+ }, true) || fails(function () {
+ // Safari (11+) bug - a reason why even Safari 13 should load a typed array polyfill
+ return new Int8Array$2(new ArrayBuffer$2(2), 1, undefined).length !== 1;
+ });
+
+ var redefineAll = function (target, src, options) {
+ for (var key in src) redefine(target, key, src[key], options);
+ return target;
+ };
+
+ var anInstance = function (it, Constructor, name) {
+ if (it instanceof Constructor) return it;
+ throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation');
+ };
+
+ // `ToIndex` abstract operation
+ // https://tc39.es/ecma262/#sec-toindex
+ var toIndex = function (it) {
+ if (it === undefined) return 0;
+ var number = toInteger(it);
+ var length = toLength(number);
+ if (number !== length) throw RangeError('Wrong length or index');
+ return length;
+ };
+
+ // IEEE754 conversions based on https://github.com/feross/ieee754
+ var abs = Math.abs;
+ var pow$1 = Math.pow;
+ var floor$4 = Math.floor;
+ var log$2 = Math.log;
+ var LN2 = Math.LN2;
+
+ var pack = function (number, mantissaLength, bytes) {
+ var buffer = new Array(bytes);
+ var exponentLength = bytes * 8 - mantissaLength - 1;
+ var eMax = (1 << exponentLength) - 1;
+ var eBias = eMax >> 1;
+ var rt = mantissaLength === 23 ? pow$1(2, -24) - pow$1(2, -77) : 0;
+ var sign = number < 0 || number === 0 && 1 / number < 0 ? 1 : 0;
+ var index = 0;
+ var exponent, mantissa, c;
+ number = abs(number);
+ // eslint-disable-next-line no-self-compare -- NaN check
+ if (number != number || number === Infinity) {
+ // eslint-disable-next-line no-self-compare -- NaN check
+ mantissa = number != number ? 1 : 0;
+ exponent = eMax;
+ } else {
+ exponent = floor$4(log$2(number) / LN2);
+ if (number * (c = pow$1(2, -exponent)) < 1) {
+ exponent--;
+ c *= 2;
+ }
+ if (exponent + eBias >= 1) {
+ number += rt / c;
+ } else {
+ number += rt * pow$1(2, 1 - eBias);
+ }
+ if (number * c >= 2) {
+ exponent++;
+ c /= 2;
+ }
+ if (exponent + eBias >= eMax) {
+ mantissa = 0;
+ exponent = eMax;
+ } else if (exponent + eBias >= 1) {
+ mantissa = (number * c - 1) * pow$1(2, mantissaLength);
+ exponent = exponent + eBias;
+ } else {
+ mantissa = number * pow$1(2, eBias - 1) * pow$1(2, mantissaLength);
+ exponent = 0;
+ }
+ }
+ for (; mantissaLength >= 8; buffer[index++] = mantissa & 255, mantissa /= 256, mantissaLength -= 8);
+ exponent = exponent << mantissaLength | mantissa;
+ exponentLength += mantissaLength;
+ for (; exponentLength > 0; buffer[index++] = exponent & 255, exponent /= 256, exponentLength -= 8);
+ buffer[--index] |= sign * 128;
+ return buffer;
+ };
+
+ var unpack = function (buffer, mantissaLength) {
+ var bytes = buffer.length;
+ var exponentLength = bytes * 8 - mantissaLength - 1;
+ var eMax = (1 << exponentLength) - 1;
+ var eBias = eMax >> 1;
+ var nBits = exponentLength - 7;
+ var index = bytes - 1;
+ var sign = buffer[index--];
+ var exponent = sign & 127;
+ var mantissa;
+ sign >>= 7;
+ for (; nBits > 0; exponent = exponent * 256 + buffer[index], index--, nBits -= 8);
+ mantissa = exponent & (1 << -nBits) - 1;
+ exponent >>= -nBits;
+ nBits += mantissaLength;
+ for (; nBits > 0; mantissa = mantissa * 256 + buffer[index], index--, nBits -= 8);
+ if (exponent === 0) {
+ exponent = 1 - eBias;
+ } else if (exponent === eMax) {
+ return mantissa ? NaN : sign ? -Infinity : Infinity;
+ } else {
+ mantissa = mantissa + pow$1(2, mantissaLength);
+ exponent = exponent - eBias;
+ } return (sign ? -1 : 1) * mantissa * pow$1(2, exponent - mantissaLength);
+ };
+
+ var ieee754 = {
+ pack: pack,
+ unpack: unpack
+ };
+
+ // `Array.prototype.fill` method implementation
+ // https://tc39.es/ecma262/#sec-array.prototype.fill
+ var arrayFill = function fill(value /* , start = 0, end = @length */) {
+ var O = toObject(this);
+ var length = toLength(O.length);
+ var argumentsLength = arguments.length;
+ var index = toAbsoluteIndex(argumentsLength > 1 ? arguments[1] : undefined, length);
+ var end = argumentsLength > 2 ? arguments[2] : undefined;
+ var endPos = end === undefined ? length : toAbsoluteIndex(end, length);
+ while (endPos > index) O[index++] = value;
+ return O;
+ };
+
+ var getOwnPropertyNames = objectGetOwnPropertyNames.f;
+ var defineProperty$4 = objectDefineProperty.f;
+
+
+
+
+ var PROPER_FUNCTION_NAME$2 = functionName.PROPER;
+ var CONFIGURABLE_FUNCTION_NAME = functionName.CONFIGURABLE;
+ var getInternalState$3 = internalState.get;
+ var setInternalState$4 = internalState.set;
+ var ARRAY_BUFFER$1 = 'ArrayBuffer';
+ var DATA_VIEW = 'DataView';
+ var PROTOTYPE$1 = 'prototype';
+ var WRONG_LENGTH = 'Wrong length';
+ var WRONG_INDEX = 'Wrong index';
+ var NativeArrayBuffer$1 = global_1[ARRAY_BUFFER$1];
+ var $ArrayBuffer = NativeArrayBuffer$1;
+ var $DataView = global_1[DATA_VIEW];
+ var $DataViewPrototype = $DataView && $DataView[PROTOTYPE$1];
+ var ObjectPrototype$1 = Object.prototype;
+ var RangeError$1 = global_1.RangeError;
+
+ var packIEEE754 = ieee754.pack;
+ var unpackIEEE754 = ieee754.unpack;
+
+ var packInt8 = function (number) {
+ return [number & 0xFF];
+ };
+
+ var packInt16 = function (number) {
+ return [number & 0xFF, number >> 8 & 0xFF];
+ };
+
+ var packInt32 = function (number) {
+ return [number & 0xFF, number >> 8 & 0xFF, number >> 16 & 0xFF, number >> 24 & 0xFF];
+ };
+
+ var unpackInt32 = function (buffer) {
+ return buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
+ };
+
+ var packFloat32 = function (number) {
+ return packIEEE754(number, 23, 4);
+ };
+
+ var packFloat64 = function (number) {
+ return packIEEE754(number, 52, 8);
+ };
+
+ var addGetter = function (Constructor, key) {
+ defineProperty$4(Constructor[PROTOTYPE$1], key, { get: function () { return getInternalState$3(this)[key]; } });
+ };
+
+ var get = function (view, count, index, isLittleEndian) {
+ var intIndex = toIndex(index);
+ var store = getInternalState$3(view);
+ if (intIndex + count > store.byteLength) throw RangeError$1(WRONG_INDEX);
+ var bytes = getInternalState$3(store.buffer).bytes;
+ var start = intIndex + store.byteOffset;
+ var pack = bytes.slice(start, start + count);
+ return isLittleEndian ? pack : pack.reverse();
+ };
+
+ var set$1 = function (view, count, index, conversion, value, isLittleEndian) {
+ var intIndex = toIndex(index);
+ var store = getInternalState$3(view);
+ if (intIndex + count > store.byteLength) throw RangeError$1(WRONG_INDEX);
+ var bytes = getInternalState$3(store.buffer).bytes;
+ var start = intIndex + store.byteOffset;
+ var pack = conversion(+value);
+ for (var i = 0; i < count; i++) bytes[start + i] = pack[isLittleEndian ? i : count - i - 1];
+ };
+
+ if (!arrayBufferNative) {
+ $ArrayBuffer = function ArrayBuffer(length) {
+ anInstance(this, $ArrayBuffer, ARRAY_BUFFER$1);
+ var byteLength = toIndex(length);
+ setInternalState$4(this, {
+ bytes: arrayFill.call(new Array(byteLength), 0),
+ byteLength: byteLength
+ });
+ if (!descriptors) this.byteLength = byteLength;
+ };
+
+ $DataView = function DataView(buffer, byteOffset, byteLength) {
+ anInstance(this, $DataView, DATA_VIEW);
+ anInstance(buffer, $ArrayBuffer, DATA_VIEW);
+ var bufferLength = getInternalState$3(buffer).byteLength;
+ var offset = toInteger(byteOffset);
+ if (offset < 0 || offset > bufferLength) throw RangeError$1('Wrong offset');
+ byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
+ if (offset + byteLength > bufferLength) throw RangeError$1(WRONG_LENGTH);
+ setInternalState$4(this, {
+ buffer: buffer,
+ byteLength: byteLength,
+ byteOffset: offset
+ });
+ if (!descriptors) {
+ this.buffer = buffer;
+ this.byteLength = byteLength;
+ this.byteOffset = offset;
+ }
+ };
+
+ if (descriptors) {
+ addGetter($ArrayBuffer, 'byteLength');
+ addGetter($DataView, 'buffer');
+ addGetter($DataView, 'byteLength');
+ addGetter($DataView, 'byteOffset');
+ }
+
+ redefineAll($DataView[PROTOTYPE$1], {
+ getInt8: function getInt8(byteOffset) {
+ return get(this, 1, byteOffset)[0] << 24 >> 24;
+ },
+ getUint8: function getUint8(byteOffset) {
+ return get(this, 1, byteOffset)[0];
+ },
+ getInt16: function getInt16(byteOffset /* , littleEndian */) {
+ var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined);
+ return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
+ },
+ getUint16: function getUint16(byteOffset /* , littleEndian */) {
+ var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined);
+ return bytes[1] << 8 | bytes[0];
+ },
+ getInt32: function getInt32(byteOffset /* , littleEndian */) {
+ return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined));
+ },
+ getUint32: function getUint32(byteOffset /* , littleEndian */) {
+ return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)) >>> 0;
+ },
+ getFloat32: function getFloat32(byteOffset /* , littleEndian */) {
+ return unpackIEEE754(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 23);
+ },
+ getFloat64: function getFloat64(byteOffset /* , littleEndian */) {
+ return unpackIEEE754(get(this, 8, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 52);
+ },
+ setInt8: function setInt8(byteOffset, value) {
+ set$1(this, 1, byteOffset, packInt8, value);
+ },
+ setUint8: function setUint8(byteOffset, value) {
+ set$1(this, 1, byteOffset, packInt8, value);
+ },
+ setInt16: function setInt16(byteOffset, value /* , littleEndian */) {
+ set$1(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined);
+ },
+ setUint16: function setUint16(byteOffset, value /* , littleEndian */) {
+ set$1(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined);
+ },
+ setInt32: function setInt32(byteOffset, value /* , littleEndian */) {
+ set$1(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined);
+ },
+ setUint32: function setUint32(byteOffset, value /* , littleEndian */) {
+ set$1(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined);
+ },
+ setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) {
+ set$1(this, 4, byteOffset, packFloat32, value, arguments.length > 2 ? arguments[2] : undefined);
+ },
+ setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) {
+ set$1(this, 8, byteOffset, packFloat64, value, arguments.length > 2 ? arguments[2] : undefined);
+ }
+ });
+ } else {
+ var INCORRECT_ARRAY_BUFFER_NAME = PROPER_FUNCTION_NAME$2 && NativeArrayBuffer$1.name !== ARRAY_BUFFER$1;
+ /* eslint-disable no-new -- required for testing */
+ if (!fails(function () {
+ NativeArrayBuffer$1(1);
+ }) || !fails(function () {
+ new NativeArrayBuffer$1(-1);
+ }) || fails(function () {
+ new NativeArrayBuffer$1();
+ new NativeArrayBuffer$1(1.5);
+ new NativeArrayBuffer$1(NaN);
+ return INCORRECT_ARRAY_BUFFER_NAME && !CONFIGURABLE_FUNCTION_NAME;
+ })) {
+ /* eslint-enable no-new -- required for testing */
+ $ArrayBuffer = function ArrayBuffer(length) {
+ anInstance(this, $ArrayBuffer);
+ return new NativeArrayBuffer$1(toIndex(length));
+ };
+ var ArrayBufferPrototype = $ArrayBuffer[PROTOTYPE$1] = NativeArrayBuffer$1[PROTOTYPE$1];
+ for (var keys$1 = getOwnPropertyNames(NativeArrayBuffer$1), j = 0, key; keys$1.length > j;) {
+ if (!((key = keys$1[j++]) in $ArrayBuffer)) {
+ createNonEnumerableProperty($ArrayBuffer, key, NativeArrayBuffer$1[key]);
+ }
+ }
+ ArrayBufferPrototype.constructor = $ArrayBuffer;
+ } else if (INCORRECT_ARRAY_BUFFER_NAME && CONFIGURABLE_FUNCTION_NAME) {
+ createNonEnumerableProperty(NativeArrayBuffer$1, 'name', ARRAY_BUFFER$1);
+ }
+
+ // WebKit bug - the same parent prototype for typed arrays and data view
+ if (objectSetPrototypeOf && objectGetPrototypeOf($DataViewPrototype) !== ObjectPrototype$1) {
+ objectSetPrototypeOf($DataViewPrototype, ObjectPrototype$1);
+ }
+
+ // iOS Safari 7.x bug
+ var testView = new $DataView(new $ArrayBuffer(2));
+ var $setInt8 = $DataViewPrototype.setInt8;
+ testView.setInt8(0, 2147483648);
+ testView.setInt8(1, 2147483649);
+ if (testView.getInt8(0) || !testView.getInt8(1)) redefineAll($DataViewPrototype, {
+ setInt8: function setInt8(byteOffset, value) {
+ $setInt8.call(this, byteOffset, value << 24 >> 24);
+ },
+ setUint8: function setUint8(byteOffset, value) {
+ $setInt8.call(this, byteOffset, value << 24 >> 24);
+ }
+ }, { unsafe: true });
+ }
+
+ setToStringTag($ArrayBuffer, ARRAY_BUFFER$1);
+ setToStringTag($DataView, DATA_VIEW);
+
+ var arrayBuffer = {
+ ArrayBuffer: $ArrayBuffer,
+ DataView: $DataView
+ };
+
+ var floor$3 = Math.floor;
+
+ // `Number.isInteger` method implementation
+ // https://tc39.es/ecma262/#sec-number.isinteger
+ var isInteger = function isInteger(it) {
+ return !isObject$1(it) && isFinite(it) && floor$3(it) === it;
+ };
+
+ var toPositiveInteger = function (it) {
+ var result = toInteger(it);
+ if (result < 0) throw RangeError("The argument can't be less than 0");
+ return result;
+ };
+
+ var toOffset = function (it, BYTES) {
+ var offset = toPositiveInteger(it);
+ if (offset % BYTES) throw RangeError('Wrong offset');
+ return offset;
+ };
+
+ var ITERATOR$3 = wellKnownSymbol('iterator');
+
+ var getIteratorMethod = function (it) {
+ if (it != undefined) return getMethod(it, ITERATOR$3)
+ || getMethod(it, '@@iterator')
+ || iterators[classof(it)];
+ };
+
+ var getIterator = function (argument, usingIterator) {
+ var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;
+ if (aCallable(iteratorMethod)) return anObject(iteratorMethod.call(argument));
+ throw TypeError(String(argument) + ' is not iterable');
+ };
+
+ var ITERATOR$2 = wellKnownSymbol('iterator');
+ var ArrayPrototype = Array.prototype;
+
+ // check on default Array iterator
+ var isArrayIteratorMethod = function (it) {
+ return it !== undefined && (iterators.Array === it || ArrayPrototype[ITERATOR$2] === it);
+ };
+
+ var aTypedArrayConstructor$1 = arrayBufferViewCore.aTypedArrayConstructor;
+
+ var typedArrayFrom = function from(source /* , mapfn, thisArg */) {
+ var C = aConstructor(this);
+ var O = toObject(source);
+ var argumentsLength = arguments.length;
+ var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
+ var mapping = mapfn !== undefined;
+ var iteratorMethod = getIteratorMethod(O);
+ var i, length, result, step, iterator, next;
+ if (iteratorMethod && !isArrayIteratorMethod(iteratorMethod)) {
+ iterator = getIterator(O, iteratorMethod);
+ next = iterator.next;
+ O = [];
+ while (!(step = next.call(iterator)).done) {
+ O.push(step.value);
+ }
+ }
+ if (mapping && argumentsLength > 2) {
+ mapfn = functionBindContext(mapfn, arguments[2], 2);
+ }
+ length = toLength(O.length);
+ result = new (aTypedArrayConstructor$1(C))(length);
+ for (i = 0; length > i; i++) {
+ result[i] = mapping ? mapfn(O[i], i) : O[i];
+ }
+ return result;
+ };
+
+ var typedArrayConstructor = createCommonjsModule(function (module) {
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ var getOwnPropertyNames = objectGetOwnPropertyNames.f;
+
+ var forEach = arrayIteration.forEach;
+
+
+
+
+
+
+ var getInternalState = internalState.get;
+ var setInternalState = internalState.set;
+ var nativeDefineProperty = objectDefineProperty.f;
+ var nativeGetOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
+ var round = Math.round;
+ var RangeError = global_1.RangeError;
+ var ArrayBuffer = arrayBuffer.ArrayBuffer;
+ var DataView = arrayBuffer.DataView;
+ var NATIVE_ARRAY_BUFFER_VIEWS = arrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS;
+ var TYPED_ARRAY_CONSTRUCTOR = arrayBufferViewCore.TYPED_ARRAY_CONSTRUCTOR;
+ var TYPED_ARRAY_TAG = arrayBufferViewCore.TYPED_ARRAY_TAG;
+ var TypedArray = arrayBufferViewCore.TypedArray;
+ var TypedArrayPrototype = arrayBufferViewCore.TypedArrayPrototype;
+ var aTypedArrayConstructor = arrayBufferViewCore.aTypedArrayConstructor;
+ var isTypedArray = arrayBufferViewCore.isTypedArray;
+ var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT';
+ var WRONG_LENGTH = 'Wrong length';
+
+ var fromList = function (C, list) {
+ var index = 0;
+ var length = list.length;
+ var result = new (aTypedArrayConstructor(C))(length);
+ while (length > index) result[index] = list[index++];
+ return result;
+ };
+
+ var addGetter = function (it, key) {
+ nativeDefineProperty(it, key, { get: function () {
+ return getInternalState(this)[key];
+ } });
+ };
+
+ var isArrayBuffer = function (it) {
+ var klass;
+ return it instanceof ArrayBuffer || (klass = classof(it)) == 'ArrayBuffer' || klass == 'SharedArrayBuffer';
+ };
+
+ var isTypedArrayIndex = function (target, key) {
+ return isTypedArray(target)
+ && !isSymbol$1(key)
+ && key in target
+ && isInteger(+key)
+ && key >= 0;
+ };
+
+ var wrappedGetOwnPropertyDescriptor = function getOwnPropertyDescriptor(target, key) {
+ key = toPropertyKey(key);
+ return isTypedArrayIndex(target, key)
+ ? createPropertyDescriptor(2, target[key])
+ : nativeGetOwnPropertyDescriptor(target, key);
+ };
+
+ var wrappedDefineProperty = function defineProperty(target, key, descriptor) {
+ key = toPropertyKey(key);
+ if (isTypedArrayIndex(target, key)
+ && isObject$1(descriptor)
+ && has$1(descriptor, 'value')
+ && !has$1(descriptor, 'get')
+ && !has$1(descriptor, 'set')
+ // TODO: add validation descriptor w/o calling accessors
+ && !descriptor.configurable
+ && (!has$1(descriptor, 'writable') || descriptor.writable)
+ && (!has$1(descriptor, 'enumerable') || descriptor.enumerable)
+ ) {
+ target[key] = descriptor.value;
+ return target;
+ } return nativeDefineProperty(target, key, descriptor);
+ };
+
+ if (descriptors) {
+ if (!NATIVE_ARRAY_BUFFER_VIEWS) {
+ objectGetOwnPropertyDescriptor.f = wrappedGetOwnPropertyDescriptor;
+ objectDefineProperty.f = wrappedDefineProperty;
+ addGetter(TypedArrayPrototype, 'buffer');
+ addGetter(TypedArrayPrototype, 'byteOffset');
+ addGetter(TypedArrayPrototype, 'byteLength');
+ addGetter(TypedArrayPrototype, 'length');
+ }
+
+ _export({ target: 'Object', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS }, {
+ getOwnPropertyDescriptor: wrappedGetOwnPropertyDescriptor,
+ defineProperty: wrappedDefineProperty
+ });
+
+ module.exports = function (TYPE, wrapper, CLAMPED) {
+ var BYTES = TYPE.match(/\d+$/)[0] / 8;
+ var CONSTRUCTOR_NAME = TYPE + (CLAMPED ? 'Clamped' : '') + 'Array';
+ var GETTER = 'get' + TYPE;
+ var SETTER = 'set' + TYPE;
+ var NativeTypedArrayConstructor = global_1[CONSTRUCTOR_NAME];
+ var TypedArrayConstructor = NativeTypedArrayConstructor;
+ var TypedArrayConstructorPrototype = TypedArrayConstructor && TypedArrayConstructor.prototype;
+ var exported = {};
+
+ var getter = function (that, index) {
+ var data = getInternalState(that);
+ return data.view[GETTER](index * BYTES + data.byteOffset, true);
+ };
+
+ var setter = function (that, index, value) {
+ var data = getInternalState(that);
+ if (CLAMPED) value = (value = round(value)) < 0 ? 0 : value > 0xFF ? 0xFF : value & 0xFF;
+ data.view[SETTER](index * BYTES + data.byteOffset, value, true);
+ };
+
+ var addElement = function (that, index) {
+ nativeDefineProperty(that, index, {
+ get: function () {
+ return getter(this, index);
+ },
+ set: function (value) {
+ return setter(this, index, value);
+ },
+ enumerable: true
+ });
+ };
+
+ if (!NATIVE_ARRAY_BUFFER_VIEWS) {
+ TypedArrayConstructor = wrapper(function (that, data, offset, $length) {
+ anInstance(that, TypedArrayConstructor, CONSTRUCTOR_NAME);
+ var index = 0;
+ var byteOffset = 0;
+ var buffer, byteLength, length;
+ if (!isObject$1(data)) {
+ length = toIndex(data);
+ byteLength = length * BYTES;
+ buffer = new ArrayBuffer(byteLength);
+ } else if (isArrayBuffer(data)) {
+ buffer = data;
+ byteOffset = toOffset(offset, BYTES);
+ var $len = data.byteLength;
+ if ($length === undefined) {
+ if ($len % BYTES) throw RangeError(WRONG_LENGTH);
+ byteLength = $len - byteOffset;
+ if (byteLength < 0) throw RangeError(WRONG_LENGTH);
+ } else {
+ byteLength = toLength($length) * BYTES;
+ if (byteLength + byteOffset > $len) throw RangeError(WRONG_LENGTH);
+ }
+ length = byteLength / BYTES;
+ } else if (isTypedArray(data)) {
+ return fromList(TypedArrayConstructor, data);
+ } else {
+ return typedArrayFrom.call(TypedArrayConstructor, data);
+ }
+ setInternalState(that, {
+ buffer: buffer,
+ byteOffset: byteOffset,
+ byteLength: byteLength,
+ length: length,
+ view: new DataView(buffer)
+ });
+ while (index < length) addElement(that, index++);
+ });
+
+ if (objectSetPrototypeOf) objectSetPrototypeOf(TypedArrayConstructor, TypedArray);
+ TypedArrayConstructorPrototype = TypedArrayConstructor.prototype = objectCreate(TypedArrayPrototype);
+ } else if (typedArrayConstructorsRequireWrappers) {
+ TypedArrayConstructor = wrapper(function (dummy, data, typedArrayOffset, $length) {
+ anInstance(dummy, TypedArrayConstructor, CONSTRUCTOR_NAME);
+ return inheritIfRequired(function () {
+ if (!isObject$1(data)) return new NativeTypedArrayConstructor(toIndex(data));
+ if (isArrayBuffer(data)) return $length !== undefined
+ ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES), $length)
+ : typedArrayOffset !== undefined
+ ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES))
+ : new NativeTypedArrayConstructor(data);
+ if (isTypedArray(data)) return fromList(TypedArrayConstructor, data);
+ return typedArrayFrom.call(TypedArrayConstructor, data);
+ }(), dummy, TypedArrayConstructor);
+ });
+
+ if (objectSetPrototypeOf) objectSetPrototypeOf(TypedArrayConstructor, TypedArray);
+ forEach(getOwnPropertyNames(NativeTypedArrayConstructor), function (key) {
+ if (!(key in TypedArrayConstructor)) {
+ createNonEnumerableProperty(TypedArrayConstructor, key, NativeTypedArrayConstructor[key]);
+ }
+ });
+ TypedArrayConstructor.prototype = TypedArrayConstructorPrototype;
+ }
+
+ if (TypedArrayConstructorPrototype.constructor !== TypedArrayConstructor) {
+ createNonEnumerableProperty(TypedArrayConstructorPrototype, 'constructor', TypedArrayConstructor);
+ }
+
+ createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_CONSTRUCTOR, TypedArrayConstructor);
+
+ if (TYPED_ARRAY_TAG) {
+ createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_TAG, CONSTRUCTOR_NAME);
+ }
+
+ exported[CONSTRUCTOR_NAME] = TypedArrayConstructor;
+
+ _export({
+ global: true, forced: TypedArrayConstructor != NativeTypedArrayConstructor, sham: !NATIVE_ARRAY_BUFFER_VIEWS
+ }, exported);
+
+ if (!(BYTES_PER_ELEMENT in TypedArrayConstructor)) {
+ createNonEnumerableProperty(TypedArrayConstructor, BYTES_PER_ELEMENT, BYTES);
+ }
+
+ if (!(BYTES_PER_ELEMENT in TypedArrayConstructorPrototype)) {
+ createNonEnumerableProperty(TypedArrayConstructorPrototype, BYTES_PER_ELEMENT, BYTES);
+ }
+
+ setSpecies(CONSTRUCTOR_NAME);
+ };
+ } else module.exports = function () { /* empty */ };
+ });
+
+ // `Uint8Array` constructor
+ // https://tc39.es/ecma262/#sec-typedarray-objects
+ typedArrayConstructor('Uint8', function (init) {
+ return function Uint8Array(data, byteOffset, length) {
+ return init(this, data, byteOffset, length);
+ };
+ });
+
+ var min$2 = Math.min;
+
+ // `Array.prototype.copyWithin` method implementation
+ // https://tc39.es/ecma262/#sec-array.prototype.copywithin
+ // eslint-disable-next-line es/no-array-prototype-copywithin -- safe
+ var arrayCopyWithin = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) {
+ var O = toObject(this);
+ var len = toLength(O.length);
+ var to = toAbsoluteIndex(target, len);
+ var from = toAbsoluteIndex(start, len);
+ var end = arguments.length > 2 ? arguments[2] : undefined;
+ var count = min$2((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to);
+ var inc = 1;
+ if (from < to && to < from + count) {
+ inc = -1;
+ from += count - 1;
+ to += count - 1;
+ }
+ while (count-- > 0) {
+ if (from in O) O[to] = O[from];
+ else delete O[to];
+ to += inc;
+ from += inc;
+ } return O;
+ };
+
+ var aTypedArray$l = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$m = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.copyWithin` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.copywithin
+ exportTypedArrayMethod$m('copyWithin', function copyWithin(target, start /* , end */) {
+ return arrayCopyWithin.call(aTypedArray$l(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
+ });
+
+ var $every = arrayIteration.every;
+
+ var aTypedArray$k = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$l = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.every` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.every
+ exportTypedArrayMethod$l('every', function every(callbackfn /* , thisArg */) {
+ return $every(aTypedArray$k(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
+ });
+
+ var aTypedArray$j = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$k = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.fill` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.fill
+ // eslint-disable-next-line no-unused-vars -- required for `.length`
+ exportTypedArrayMethod$k('fill', function fill(value /* , start, end */) {
+ return arrayFill.apply(aTypedArray$j(this), arguments);
+ });
+
+ var arrayFromConstructorAndList = function (Constructor, list) {
+ var index = 0;
+ var length = list.length;
+ var result = new Constructor(length);
+ while (length > index) result[index] = list[index++];
+ return result;
+ };
+
+ var TYPED_ARRAY_CONSTRUCTOR = arrayBufferViewCore.TYPED_ARRAY_CONSTRUCTOR;
+ var aTypedArrayConstructor = arrayBufferViewCore.aTypedArrayConstructor;
+
+ // a part of `TypedArraySpeciesCreate` abstract operation
+ // https://tc39.es/ecma262/#typedarray-species-create
+ var typedArraySpeciesConstructor = function (originalArray) {
+ return aTypedArrayConstructor(speciesConstructor(originalArray, originalArray[TYPED_ARRAY_CONSTRUCTOR]));
+ };
+
+ var typedArrayFromSpeciesAndList = function (instance, list) {
+ return arrayFromConstructorAndList(typedArraySpeciesConstructor(instance), list);
+ };
+
+ var $filter = arrayIteration.filter;
+
+
+ var aTypedArray$i = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$j = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.filter` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.filter
+ exportTypedArrayMethod$j('filter', function filter(callbackfn /* , thisArg */) {
+ var list = $filter(aTypedArray$i(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
+ return typedArrayFromSpeciesAndList(this, list);
+ });
+
+ var $find = arrayIteration.find;
+
+ var aTypedArray$h = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$i = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.find` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.find
+ exportTypedArrayMethod$i('find', function find(predicate /* , thisArg */) {
+ return $find(aTypedArray$h(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
+ });
+
+ var $findIndex = arrayIteration.findIndex;
+
+ var aTypedArray$g = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$h = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.findIndex` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.findindex
+ exportTypedArrayMethod$h('findIndex', function findIndex(predicate /* , thisArg */) {
+ return $findIndex(aTypedArray$g(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
+ });
+
+ var $forEach$1 = arrayIteration.forEach;
+
+ var aTypedArray$f = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$g = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.forEach` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.foreach
+ exportTypedArrayMethod$g('forEach', function forEach(callbackfn /* , thisArg */) {
+ $forEach$1(aTypedArray$f(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
+ });
+
+ var $includes$1 = arrayIncludes.includes;
+
+ var aTypedArray$e = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$f = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.includes` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.includes
+ exportTypedArrayMethod$f('includes', function includes(searchElement /* , fromIndex */) {
+ return $includes$1(aTypedArray$e(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
+ });
+
+ var $indexOf = arrayIncludes.indexOf;
+
+ var aTypedArray$d = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$e = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.indexOf` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.indexof
+ exportTypedArrayMethod$e('indexOf', function indexOf(searchElement /* , fromIndex */) {
+ return $indexOf(aTypedArray$d(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
+ });
+
+ var PROPER_FUNCTION_NAME$1 = functionName.PROPER;
+
+
+
+
+ var ITERATOR$1 = wellKnownSymbol('iterator');
+ var Uint8Array$2 = global_1.Uint8Array;
+ var arrayValues = es_array_iterator.values;
+ var arrayKeys = es_array_iterator.keys;
+ var arrayEntries = es_array_iterator.entries;
+ var aTypedArray$c = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$d = arrayBufferViewCore.exportTypedArrayMethod;
+ var nativeTypedArrayIterator = Uint8Array$2 && Uint8Array$2.prototype[ITERATOR$1];
+
+ var PROPER_ARRAY_VALUES_NAME = !!nativeTypedArrayIterator && nativeTypedArrayIterator.name === 'values';
+
+ var typedArrayValues = function values() {
+ return arrayValues.call(aTypedArray$c(this));
+ };
+
+ // `%TypedArray%.prototype.entries` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.entries
+ exportTypedArrayMethod$d('entries', function entries() {
+ return arrayEntries.call(aTypedArray$c(this));
+ });
+ // `%TypedArray%.prototype.keys` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.keys
+ exportTypedArrayMethod$d('keys', function keys() {
+ return arrayKeys.call(aTypedArray$c(this));
+ });
+ // `%TypedArray%.prototype.values` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.values
+ exportTypedArrayMethod$d('values', typedArrayValues, PROPER_FUNCTION_NAME$1 && !PROPER_ARRAY_VALUES_NAME);
+ // `%TypedArray%.prototype[@@iterator]` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype-@@iterator
+ exportTypedArrayMethod$d(ITERATOR$1, typedArrayValues, PROPER_FUNCTION_NAME$1 && !PROPER_ARRAY_VALUES_NAME);
+
+ var aTypedArray$b = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$c = arrayBufferViewCore.exportTypedArrayMethod;
+ var $join = [].join;
+
+ // `%TypedArray%.prototype.join` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.join
+ // eslint-disable-next-line no-unused-vars -- required for `.length`
+ exportTypedArrayMethod$c('join', function join(separator) {
+ return $join.apply(aTypedArray$b(this), arguments);
+ });
+
+ /* eslint-disable es/no-array-prototype-lastindexof -- safe */
+
+
+
+
+
+ var min$1 = Math.min;
+ var $lastIndexOf = [].lastIndexOf;
+ var NEGATIVE_ZERO = !!$lastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0;
+ var STRICT_METHOD$1 = arrayMethodIsStrict('lastIndexOf');
+ var FORCED$6 = NEGATIVE_ZERO || !STRICT_METHOD$1;
+
+ // `Array.prototype.lastIndexOf` method implementation
+ // https://tc39.es/ecma262/#sec-array.prototype.lastindexof
+ var arrayLastIndexOf = FORCED$6 ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {
+ // convert -0 to +0
+ if (NEGATIVE_ZERO) return $lastIndexOf.apply(this, arguments) || 0;
+ var O = toIndexedObject(this);
+ var length = toLength(O.length);
+ var index = length - 1;
+ if (arguments.length > 1) index = min$1(index, toInteger(arguments[1]));
+ if (index < 0) index = length + index;
+ for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0;
+ return -1;
+ } : $lastIndexOf;
+
+ var aTypedArray$a = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$b = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.lastIndexOf` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.lastindexof
+ // eslint-disable-next-line no-unused-vars -- required for `.length`
+ exportTypedArrayMethod$b('lastIndexOf', function lastIndexOf(searchElement /* , fromIndex */) {
+ return arrayLastIndexOf.apply(aTypedArray$a(this), arguments);
+ });
+
+ var $map = arrayIteration.map;
+
+
+ var aTypedArray$9 = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$a = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.map` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.map
+ exportTypedArrayMethod$a('map', function map(mapfn /* , thisArg */) {
+ return $map(aTypedArray$9(this), mapfn, arguments.length > 1 ? arguments[1] : undefined, function (O, length) {
+ return new (typedArraySpeciesConstructor(O))(length);
+ });
+ });
+
+ // `Array.prototype.{ reduce, reduceRight }` methods implementation
+ var createMethod$1 = function (IS_RIGHT) {
+ return function (that, callbackfn, argumentsLength, memo) {
+ aCallable(callbackfn);
+ var O = toObject(that);
+ var self = indexedObject(O);
+ var length = toLength(O.length);
+ var index = IS_RIGHT ? length - 1 : 0;
+ var i = IS_RIGHT ? -1 : 1;
+ if (argumentsLength < 2) while (true) {
+ if (index in self) {
+ memo = self[index];
+ index += i;
+ break;
+ }
+ index += i;
+ if (IS_RIGHT ? index < 0 : length <= index) {
+ throw TypeError('Reduce of empty array with no initial value');
+ }
+ }
+ for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) {
+ memo = callbackfn(memo, self[index], index, O);
+ }
+ return memo;
+ };
+ };
+
+ var arrayReduce = {
+ // `Array.prototype.reduce` method
+ // https://tc39.es/ecma262/#sec-array.prototype.reduce
+ left: createMethod$1(false),
+ // `Array.prototype.reduceRight` method
+ // https://tc39.es/ecma262/#sec-array.prototype.reduceright
+ right: createMethod$1(true)
+ };
+
+ var $reduce = arrayReduce.left;
+
+ var aTypedArray$8 = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$9 = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.reduce` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduce
+ exportTypedArrayMethod$9('reduce', function reduce(callbackfn /* , initialValue */) {
+ return $reduce(aTypedArray$8(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);
+ });
+
+ var $reduceRight = arrayReduce.right;
+
+ var aTypedArray$7 = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$8 = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.reduceRicht` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduceright
+ exportTypedArrayMethod$8('reduceRight', function reduceRight(callbackfn /* , initialValue */) {
+ return $reduceRight(aTypedArray$7(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);
+ });
+
+ var aTypedArray$6 = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$7 = arrayBufferViewCore.exportTypedArrayMethod;
+ var floor$2 = Math.floor;
+
+ // `%TypedArray%.prototype.reverse` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.reverse
+ exportTypedArrayMethod$7('reverse', function reverse() {
+ var that = this;
+ var length = aTypedArray$6(that).length;
+ var middle = floor$2(length / 2);
+ var index = 0;
+ var value;
+ while (index < middle) {
+ value = that[index];
+ that[index++] = that[--length];
+ that[length] = value;
+ } return that;
+ });
+
+ var aTypedArray$5 = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$6 = arrayBufferViewCore.exportTypedArrayMethod;
+
+ var FORCED$5 = fails(function () {
+ // eslint-disable-next-line es/no-typed-arrays -- required for testing
+ new Int8Array(1).set({});
+ });
+
+ // `%TypedArray%.prototype.set` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.set
+ exportTypedArrayMethod$6('set', function set(arrayLike /* , offset */) {
+ aTypedArray$5(this);
+ var offset = toOffset(arguments.length > 1 ? arguments[1] : undefined, 1);
+ var length = this.length;
+ var src = toObject(arrayLike);
+ var len = toLength(src.length);
+ var index = 0;
+ if (len + offset > length) throw RangeError('Wrong length');
+ while (index < len) this[offset + index] = src[index++];
+ }, FORCED$5);
+
+ var aTypedArray$4 = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$5 = arrayBufferViewCore.exportTypedArrayMethod;
+ var $slice$1 = [].slice;
+
+ var FORCED$4 = fails(function () {
+ // eslint-disable-next-line es/no-typed-arrays -- required for testing
+ new Int8Array(1).slice();
+ });
+
+ // `%TypedArray%.prototype.slice` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.slice
+ exportTypedArrayMethod$5('slice', function slice(start, end) {
+ var list = $slice$1.call(aTypedArray$4(this), start, end);
+ var C = typedArraySpeciesConstructor(this);
+ var index = 0;
+ var length = list.length;
+ var result = new C(length);
+ while (length > index) result[index] = list[index++];
+ return result;
+ }, FORCED$4);
+
+ var $some = arrayIteration.some;
+
+ var aTypedArray$3 = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$4 = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.some` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.some
+ exportTypedArrayMethod$4('some', function some(callbackfn /* , thisArg */) {
+ return $some(aTypedArray$3(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
+ });
+
+ // TODO: use something more complex like timsort?
+ var floor$1 = Math.floor;
+
+ var mergeSort = function (array, comparefn) {
+ var length = array.length;
+ var middle = floor$1(length / 2);
+ return length < 8 ? insertionSort(array, comparefn) : merge(
+ mergeSort(array.slice(0, middle), comparefn),
+ mergeSort(array.slice(middle), comparefn),
+ comparefn
+ );
+ };
+
+ var insertionSort = function (array, comparefn) {
+ var length = array.length;
+ var i = 1;
+ var element, j;
+
+ while (i < length) {
+ j = i;
+ element = array[i];
+ while (j && comparefn(array[j - 1], element) > 0) {
+ array[j] = array[--j];
+ }
+ if (j !== i++) array[j] = element;
+ } return array;
+ };
+
+ var merge = function (left, right, comparefn) {
+ var llength = left.length;
+ var rlength = right.length;
+ var lindex = 0;
+ var rindex = 0;
+ var result = [];
+
+ while (lindex < llength || rindex < rlength) {
+ if (lindex < llength && rindex < rlength) {
+ result.push(comparefn(left[lindex], right[rindex]) <= 0 ? left[lindex++] : right[rindex++]);
+ } else {
+ result.push(lindex < llength ? left[lindex++] : right[rindex++]);
+ }
+ } return result;
+ };
+
+ var arraySort = mergeSort;
+
+ var firefox = engineUserAgent.match(/firefox\/(\d+)/i);
+
+ var engineFfVersion = !!firefox && +firefox[1];
+
+ var engineIsIeOrEdge = /MSIE|Trident/.test(engineUserAgent);
+
+ var webkit = engineUserAgent.match(/AppleWebKit\/(\d+)\./);
+
+ var engineWebkitVersion = !!webkit && +webkit[1];
+
+ var aTypedArray$2 = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$3 = arrayBufferViewCore.exportTypedArrayMethod;
+ var Uint16Array = global_1.Uint16Array;
+ var nativeSort$1 = Uint16Array && Uint16Array.prototype.sort;
+
+ // WebKit
+ var ACCEPT_INCORRECT_ARGUMENTS = !!nativeSort$1 && !fails(function () {
+ var array = new Uint16Array(2);
+ array.sort(null);
+ array.sort({});
+ });
+
+ var STABLE_SORT$1 = !!nativeSort$1 && !fails(function () {
+ // feature detection can be too slow, so check engines versions
+ if (engineV8Version) return engineV8Version < 74;
+ if (engineFfVersion) return engineFfVersion < 67;
+ if (engineIsIeOrEdge) return true;
+ if (engineWebkitVersion) return engineWebkitVersion < 602;
+
+ var array = new Uint16Array(516);
+ var expected = Array(516);
+ var index, mod;
+
+ for (index = 0; index < 516; index++) {
+ mod = index % 4;
+ array[index] = 515 - index;
+ expected[index] = index - 2 * mod + 3;
+ }
+
+ array.sort(function (a, b) {
+ return (a / 4 | 0) - (b / 4 | 0);
+ });
+
+ for (index = 0; index < 516; index++) {
+ if (array[index] !== expected[index]) return true;
+ }
+ });
+
+ var getSortCompare$1 = function (comparefn) {
+ return function (x, y) {
+ if (comparefn !== undefined) return +comparefn(x, y) || 0;
+ // eslint-disable-next-line no-self-compare -- NaN check
+ if (y !== y) return -1;
+ // eslint-disable-next-line no-self-compare -- NaN check
+ if (x !== x) return 1;
+ if (x === 0 && y === 0) return 1 / x > 0 && 1 / y < 0 ? 1 : -1;
+ return x > y;
+ };
+ };
+
+ // `%TypedArray%.prototype.sort` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.sort
+ exportTypedArrayMethod$3('sort', function sort(comparefn) {
+ var array = this;
+ if (comparefn !== undefined) aCallable(comparefn);
+ if (STABLE_SORT$1) return nativeSort$1.call(array, comparefn);
+
+ aTypedArray$2(array);
+ var arrayLength = toLength(array.length);
+ var items = Array(arrayLength);
+ var index;
+
+ for (index = 0; index < arrayLength; index++) {
+ items[index] = array[index];
+ }
+
+ items = arraySort(array, getSortCompare$1(comparefn));
+
+ for (index = 0; index < arrayLength; index++) {
+ array[index] = items[index];
+ }
+
+ return array;
+ }, !STABLE_SORT$1 || ACCEPT_INCORRECT_ARGUMENTS);
+
+ var aTypedArray$1 = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$2 = arrayBufferViewCore.exportTypedArrayMethod;
+
+ // `%TypedArray%.prototype.subarray` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.subarray
+ exportTypedArrayMethod$2('subarray', function subarray(begin, end) {
+ var O = aTypedArray$1(this);
+ var length = O.length;
+ var beginIndex = toAbsoluteIndex(begin, length);
+ var C = typedArraySpeciesConstructor(O);
+ return new C(
+ O.buffer,
+ O.byteOffset + beginIndex * O.BYTES_PER_ELEMENT,
+ toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - beginIndex)
+ );
+ });
+
+ var Int8Array$1 = global_1.Int8Array;
+ var aTypedArray = arrayBufferViewCore.aTypedArray;
+ var exportTypedArrayMethod$1 = arrayBufferViewCore.exportTypedArrayMethod;
+ var $toLocaleString = [].toLocaleString;
+ var $slice = [].slice;
+
+ // iOS Safari 6.x fails here
+ var TO_LOCALE_STRING_BUG = !!Int8Array$1 && fails(function () {
+ $toLocaleString.call(new Int8Array$1(1));
+ });
+
+ var FORCED$3 = fails(function () {
+ return [1, 2].toLocaleString() != new Int8Array$1([1, 2]).toLocaleString();
+ }) || !fails(function () {
+ Int8Array$1.prototype.toLocaleString.call([1, 2]);
+ });
+
+ // `%TypedArray%.prototype.toLocaleString` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.tolocalestring
+ exportTypedArrayMethod$1('toLocaleString', function toLocaleString() {
+ return $toLocaleString.apply(TO_LOCALE_STRING_BUG ? $slice.call(aTypedArray(this)) : aTypedArray(this), arguments);
+ }, FORCED$3);
+
+ var exportTypedArrayMethod = arrayBufferViewCore.exportTypedArrayMethod;
+
+
+
+ var Uint8Array$1 = global_1.Uint8Array;
+ var Uint8ArrayPrototype = Uint8Array$1 && Uint8Array$1.prototype || {};
+ var arrayToString = [].toString;
+ var arrayJoin = [].join;
+
+ if (fails(function () { arrayToString.call({}); })) {
+ arrayToString = function toString() {
+ return arrayJoin.call(this);
+ };
+ }
+
+ var IS_NOT_ARRAY_METHOD = Uint8ArrayPrototype.toString != arrayToString;
+
+ // `%TypedArray%.prototype.toString` method
+ // https://tc39.es/ecma262/#sec-%typedarray%.prototype.tostring
+ exportTypedArrayMethod('toString', arrayToString, IS_NOT_ARRAY_METHOD);
+
+ var ARRAY_BUFFER = 'ArrayBuffer';
+ var ArrayBuffer$1 = arrayBuffer[ARRAY_BUFFER];
+ var NativeArrayBuffer = global_1[ARRAY_BUFFER];
+
+ // `ArrayBuffer` constructor
+ // https://tc39.es/ecma262/#sec-arraybuffer-constructor
+ _export({ global: true, forced: NativeArrayBuffer !== ArrayBuffer$1 }, {
+ ArrayBuffer: ArrayBuffer$1
+ });
+
+ setSpecies(ARRAY_BUFFER);
+
+ var f$1 = wellKnownSymbol;
+
+ var wellKnownSymbolWrapped = {
+ f: f$1
+ };
+
+ var path$1 = global_1;
+
+ var defineProperty$3 = objectDefineProperty.f;
+
+ var defineWellKnownSymbol = function (NAME) {
+ var Symbol = path$1.Symbol || (path$1.Symbol = {});
+ if (!has$1(Symbol, NAME)) defineProperty$3(Symbol, NAME, {
+ value: wellKnownSymbolWrapped.f(NAME)
+ });
+ };
+
+ var $forEach = arrayIteration.forEach;
+
+ var HIDDEN = sharedKey('hidden');
+ var SYMBOL = 'Symbol';
+ var PROTOTYPE = 'prototype';
+ var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
+ var setInternalState$3 = internalState.set;
+ var getInternalState$2 = internalState.getterFor(SYMBOL);
+ var ObjectPrototype = Object[PROTOTYPE];
+ var $Symbol = global_1.Symbol;
+ var $stringify = getBuiltIn('JSON', 'stringify');
+ var nativeGetOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
+ var nativeDefineProperty = objectDefineProperty.f;
+ var nativeGetOwnPropertyNames = objectGetOwnPropertyNamesExternal.f;
+ var nativePropertyIsEnumerable = objectPropertyIsEnumerable.f;
+ var AllSymbols = shared('symbols');
+ var ObjectPrototypeSymbols = shared('op-symbols');
+ var StringToSymbolRegistry = shared('string-to-symbol-registry');
+ var SymbolToStringRegistry = shared('symbol-to-string-registry');
+ var WellKnownSymbolsStore = shared('wks');
+ var QObject = global_1.QObject;
+ // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
+ var USE_SETTER = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
+
+ // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
+ var setSymbolDescriptor = descriptors && fails(function () {
+ return objectCreate(nativeDefineProperty({}, 'a', {
+ get: function () { return nativeDefineProperty(this, 'a', { value: 7 }).a; }
+ })).a != 7;
+ }) ? function (O, P, Attributes) {
+ var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor(ObjectPrototype, P);
+ if (ObjectPrototypeDescriptor) delete ObjectPrototype[P];
+ nativeDefineProperty(O, P, Attributes);
+ if (ObjectPrototypeDescriptor && O !== ObjectPrototype) {
+ nativeDefineProperty(ObjectPrototype, P, ObjectPrototypeDescriptor);
+ }
+ } : nativeDefineProperty;
+
+ var wrap = function (tag, description) {
+ var symbol = AllSymbols[tag] = objectCreate($Symbol[PROTOTYPE]);
+ setInternalState$3(symbol, {
+ type: SYMBOL,
+ tag: tag,
+ description: description
+ });
+ if (!descriptors) symbol.description = description;
+ return symbol;
+ };
+
+ var $defineProperty = function defineProperty(O, P, Attributes) {
+ if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes);
+ anObject(O);
+ var key = toPropertyKey(P);
+ anObject(Attributes);
+ if (has$1(AllSymbols, key)) {
+ if (!Attributes.enumerable) {
+ if (!has$1(O, HIDDEN)) nativeDefineProperty(O, HIDDEN, createPropertyDescriptor(1, {}));
+ O[HIDDEN][key] = true;
+ } else {
+ if (has$1(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false;
+ Attributes = objectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) });
+ } return setSymbolDescriptor(O, key, Attributes);
+ } return nativeDefineProperty(O, key, Attributes);
+ };
+
+ var $defineProperties = function defineProperties(O, Properties) {
+ anObject(O);
+ var properties = toIndexedObject(Properties);
+ var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties));
+ $forEach(keys, function (key) {
+ if (!descriptors || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]);
+ });
+ return O;
+ };
+
+ var $create = function create(O, Properties) {
+ return Properties === undefined ? objectCreate(O) : $defineProperties(objectCreate(O), Properties);
+ };
+
+ var $propertyIsEnumerable = function propertyIsEnumerable(V) {
+ var P = toPropertyKey(V);
+ var enumerable = nativePropertyIsEnumerable.call(this, P);
+ if (this === ObjectPrototype && has$1(AllSymbols, P) && !has$1(ObjectPrototypeSymbols, P)) return false;
+ return enumerable || !has$1(this, P) || !has$1(AllSymbols, P) || has$1(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true;
+ };
+
+ var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) {
+ var it = toIndexedObject(O);
+ var key = toPropertyKey(P);
+ if (it === ObjectPrototype && has$1(AllSymbols, key) && !has$1(ObjectPrototypeSymbols, key)) return;
+ var descriptor = nativeGetOwnPropertyDescriptor(it, key);
+ if (descriptor && has$1(AllSymbols, key) && !(has$1(it, HIDDEN) && it[HIDDEN][key])) {
+ descriptor.enumerable = true;
+ }
+ return descriptor;
+ };
+
+ var $getOwnPropertyNames = function getOwnPropertyNames(O) {
+ var names = nativeGetOwnPropertyNames(toIndexedObject(O));
+ var result = [];
+ $forEach(names, function (key) {
+ if (!has$1(AllSymbols, key) && !has$1(hiddenKeys$1, key)) result.push(key);
+ });
+ return result;
+ };
+
+ var $getOwnPropertySymbols = function getOwnPropertySymbols(O) {
+ var IS_OBJECT_PROTOTYPE = O === ObjectPrototype;
+ var names = nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O));
+ var result = [];
+ $forEach(names, function (key) {
+ if (has$1(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has$1(ObjectPrototype, key))) {
+ result.push(AllSymbols[key]);
+ }
+ });
+ return result;
+ };
+
+ // `Symbol` constructor
+ // https://tc39.es/ecma262/#sec-symbol-constructor
+ if (!nativeSymbol$1) {
+ $Symbol = function Symbol() {
+ if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor');
+ var description = !arguments.length || arguments[0] === undefined ? undefined : toString_1(arguments[0]);
+ var tag = uid(description);
+ var setter = function (value) {
+ if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value);
+ if (has$1(this, HIDDEN) && has$1(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
+ setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value));
+ };
+ if (descriptors && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, { configurable: true, set: setter });
+ return wrap(tag, description);
+ };
+
+ redefine($Symbol[PROTOTYPE], 'toString', function toString() {
+ return getInternalState$2(this).tag;
+ });
+
+ redefine($Symbol, 'withoutSetter', function (description) {
+ return wrap(uid(description), description);
+ });
+
+ objectPropertyIsEnumerable.f = $propertyIsEnumerable;
+ objectDefineProperty.f = $defineProperty;
+ objectGetOwnPropertyDescriptor.f = $getOwnPropertyDescriptor;
+ objectGetOwnPropertyNames.f = objectGetOwnPropertyNamesExternal.f = $getOwnPropertyNames;
+ objectGetOwnPropertySymbols.f = $getOwnPropertySymbols;
+
+ wellKnownSymbolWrapped.f = function (name) {
+ return wrap(wellKnownSymbol(name), name);
+ };
+
+ if (descriptors) {
+ // https://github.com/tc39/proposal-Symbol-description
+ nativeDefineProperty($Symbol[PROTOTYPE], 'description', {
+ configurable: true,
+ get: function description() {
+ return getInternalState$2(this).description;
+ }
+ });
+ {
+ redefine(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true });
+ }
+ }
+ }
+
+ _export({ global: true, wrap: true, forced: !nativeSymbol$1, sham: !nativeSymbol$1 }, {
+ Symbol: $Symbol
+ });
+
+ $forEach(objectKeys(WellKnownSymbolsStore), function (name) {
+ defineWellKnownSymbol(name);
+ });
+
+ _export({ target: SYMBOL, stat: true, forced: !nativeSymbol$1 }, {
+ // `Symbol.for` method
+ // https://tc39.es/ecma262/#sec-symbol.for
+ 'for': function (key) {
+ var string = toString_1(key);
+ if (has$1(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string];
+ var symbol = $Symbol(string);
+ StringToSymbolRegistry[string] = symbol;
+ SymbolToStringRegistry[symbol] = string;
+ return symbol;
+ },
+ // `Symbol.keyFor` method
+ // https://tc39.es/ecma262/#sec-symbol.keyfor
+ keyFor: function keyFor(sym) {
+ if (!isSymbol$1(sym)) throw TypeError(sym + ' is not a symbol');
+ if (has$1(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym];
+ },
+ useSetter: function () { USE_SETTER = true; },
+ useSimple: function () { USE_SETTER = false; }
+ });
+
+ _export({ target: 'Object', stat: true, forced: !nativeSymbol$1, sham: !descriptors }, {
+ // `Object.create` method
+ // https://tc39.es/ecma262/#sec-object.create
+ create: $create,
+ // `Object.defineProperty` method
+ // https://tc39.es/ecma262/#sec-object.defineproperty
+ defineProperty: $defineProperty,
+ // `Object.defineProperties` method
+ // https://tc39.es/ecma262/#sec-object.defineproperties
+ defineProperties: $defineProperties,
+ // `Object.getOwnPropertyDescriptor` method
+ // https://tc39.es/ecma262/#sec-object.getownpropertydescriptors
+ getOwnPropertyDescriptor: $getOwnPropertyDescriptor
+ });
+
+ _export({ target: 'Object', stat: true, forced: !nativeSymbol$1 }, {
+ // `Object.getOwnPropertyNames` method
+ // https://tc39.es/ecma262/#sec-object.getownpropertynames
+ getOwnPropertyNames: $getOwnPropertyNames,
+ // `Object.getOwnPropertySymbols` method
+ // https://tc39.es/ecma262/#sec-object.getownpropertysymbols
+ getOwnPropertySymbols: $getOwnPropertySymbols
+ });
+
+ // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
+ // https://bugs.chromium.org/p/v8/issues/detail?id=3443
+ _export({ target: 'Object', stat: true, forced: fails(function () { objectGetOwnPropertySymbols.f(1); }) }, {
+ getOwnPropertySymbols: function getOwnPropertySymbols(it) {
+ return objectGetOwnPropertySymbols.f(toObject(it));
+ }
+ });
+
+ // `JSON.stringify` method behavior with symbols
+ // https://tc39.es/ecma262/#sec-json.stringify
+ if ($stringify) {
+ var FORCED_JSON_STRINGIFY = !nativeSymbol$1 || fails(function () {
+ var symbol = $Symbol();
+ // MS Edge converts symbol values to JSON as {}
+ return $stringify([symbol]) != '[null]'
+ // WebKit converts symbol values to JSON as null
+ || $stringify({ a: symbol }) != '{}'
+ // V8 throws on boxed symbols
+ || $stringify(Object(symbol)) != '{}';
+ });
+
+ _export({ target: 'JSON', stat: true, forced: FORCED_JSON_STRINGIFY }, {
+ // eslint-disable-next-line no-unused-vars -- required for `.length`
+ stringify: function stringify(it, replacer, space) {
+ var args = [it];
+ var index = 1;
+ var $replacer;
+ while (arguments.length > index) args.push(arguments[index++]);
+ $replacer = replacer;
+ if (!isObject$1(replacer) && it === undefined || isSymbol$1(it)) return; // IE8 returns string on undefined
+ if (!isArray$3(replacer)) replacer = function (key, value) {
+ if (isCallable($replacer)) value = $replacer.call(this, key, value);
+ if (!isSymbol$1(value)) return value;
+ };
+ args[1] = replacer;
+ return $stringify.apply(null, args);
+ }
+ });
+ }
+
+ // `Symbol.prototype[@@toPrimitive]` method
+ // https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive
+ if (!$Symbol[PROTOTYPE][TO_PRIMITIVE]) {
+ var valueOf$1 = $Symbol[PROTOTYPE].valueOf;
+ redefine($Symbol[PROTOTYPE], TO_PRIMITIVE, function () {
+ return valueOf$1.apply(this, arguments);
+ });
+ }
+ // `Symbol.prototype[@@toStringTag]` property
+ // https://tc39.es/ecma262/#sec-symbol.prototype-@@tostringtag
+ setToStringTag($Symbol, SYMBOL);
+
+ hiddenKeys$1[HIDDEN] = true;
+
+ var defineProperty$2 = objectDefineProperty.f;
+
+
+ var NativeSymbol = global_1.Symbol;
+
+ if (descriptors && isCallable(NativeSymbol) && (!('description' in NativeSymbol.prototype) ||
+ // Safari 12 bug
+ NativeSymbol().description !== undefined
+ )) {
+ var EmptyStringDescriptionStore = {};
+ // wrap Symbol constructor for correct work with undefined description
+ var SymbolWrapper = function Symbol() {
+ var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]);
+ var result = this instanceof SymbolWrapper
+ ? new NativeSymbol(description)
+ // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)'
+ : description === undefined ? NativeSymbol() : NativeSymbol(description);
+ if (description === '') EmptyStringDescriptionStore[result] = true;
+ return result;
+ };
+ copyConstructorProperties(SymbolWrapper, NativeSymbol);
+ var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype;
+ symbolPrototype.constructor = SymbolWrapper;
+
+ var symbolToString = symbolPrototype.toString;
+ var nativeSymbol = String(NativeSymbol('test')) == 'Symbol(test)';
+ var regexp = /^Symbol\((.*)\)[^)]+$/;
+ defineProperty$2(symbolPrototype, 'description', {
+ configurable: true,
+ get: function description() {
+ var symbol = isObject$1(this) ? this.valueOf() : this;
+ var string = symbolToString.call(symbol);
+ if (has$1(EmptyStringDescriptionStore, symbol)) return '';
+ var desc = nativeSymbol ? string.slice(7, -1) : string.replace(regexp, '$1');
+ return desc === '' ? undefined : desc;
+ }
+ });
+
+ _export({ global: true, forced: true }, {
+ Symbol: SymbolWrapper
+ });
+ }
+
+ // `Symbol.species` well-known symbol
+ // https://tc39.es/ecma262/#sec-symbol.species
+ defineWellKnownSymbol('species');
+
+ // `Array[@@species]` getter
+ // https://tc39.es/ecma262/#sec-get-array-@@species
+ setSpecies('Array');
+
+ // `Array.prototype.fill` method
+ // https://tc39.es/ecma262/#sec-array.prototype.fill
+ _export({ target: 'Array', proto: true }, {
+ fill: arrayFill
+ });
+
+ // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
+ addToUnscopables('fill');
+
+ var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('slice');
+
+ var SPECIES$1 = wellKnownSymbol('species');
+ var nativeSlice = [].slice;
+ var max = Math.max;
+
+ // `Array.prototype.slice` method
+ // https://tc39.es/ecma262/#sec-array.prototype.slice
+ // fallback for not array-like ES3 strings and DOM objects
+ _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT }, {
+ slice: function slice(start, end) {
+ var O = toIndexedObject(this);
+ var length = toLength(O.length);
+ var k = toAbsoluteIndex(start, length);
+ var fin = toAbsoluteIndex(end === undefined ? length : end, length);
+ // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
+ var Constructor, result, n;
+ if (isArray$3(O)) {
+ Constructor = O.constructor;
+ // cross-realm fallback
+ if (isConstructor(Constructor) && (Constructor === Array || isArray$3(Constructor.prototype))) {
+ Constructor = undefined;
+ } else if (isObject$1(Constructor)) {
+ Constructor = Constructor[SPECIES$1];
+ if (Constructor === null) Constructor = undefined;
+ }
+ if (Constructor === Array || Constructor === undefined) {
+ return nativeSlice.call(O, k, fin);
+ }
+ }
+ result = new (Constructor === undefined ? Array : Constructor)(max(fin - k, 0));
+ for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
+ result.length = n;
+ return result;
+ }
+ });
+
+ var $includes = arrayIncludes.includes;
+
+
+ // `Array.prototype.includes` method
+ // https://tc39.es/ecma262/#sec-array.prototype.includes
+ _export({ target: 'Array', proto: true }, {
+ includes: function includes(el /* , fromIndex = 0 */) {
+ return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
+ }
+ });
+
+ // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
+ addToUnscopables('includes');
+
+ var notARegexp = function (it) {
+ if (isRegexp(it)) {
+ throw TypeError("The method doesn't accept regular expressions");
+ } return it;
+ };
+
+ var MATCH = wellKnownSymbol('match');
+
+ var correctIsRegexpLogic = function (METHOD_NAME) {
+ var regexp = /./;
+ try {
+ '/./'[METHOD_NAME](regexp);
+ } catch (error1) {
+ try {
+ regexp[MATCH] = false;
+ return '/./'[METHOD_NAME](regexp);
+ } catch (error2) { /* empty */ }
+ } return false;
+ };
+
+ // `String.prototype.includes` method
+ // https://tc39.es/ecma262/#sec-string.prototype.includes
+ _export({ target: 'String', proto: true, forced: !correctIsRegexpLogic('includes') }, {
+ includes: function includes(searchString /* , position = 0 */) {
+ return !!~toString_1(requireObjectCoercible(this))
+ .indexOf(toString_1(notARegexp(searchString)), arguments.length > 1 ? arguments[1] : undefined);
+ }
+ });
+
+ // `URL.prototype.toJSON` method
+ // https://url.spec.whatwg.org/#dom-url-tojson
+ _export({ target: 'URL', proto: true, enumerable: true }, {
+ toJSON: function toJSON() {
+ return URL.prototype.toString.call(this);
+ }
+ });
+
+ var PROPER_FUNCTION_NAME = functionName.PROPER;
+
+
+
+ var non = '\u200B\u0085\u180E';
+
+ // check that a method works with the correct list
+ // of whitespaces and has a correct name
+ var stringTrimForced = function (METHOD_NAME) {
+ return fails(function () {
+ return !!whitespaces[METHOD_NAME]()
+ || non[METHOD_NAME]() !== non
+ || (PROPER_FUNCTION_NAME && whitespaces[METHOD_NAME].name !== METHOD_NAME);
+ });
+ };
+
+ var $trim = stringTrim.trim;
+
+
+ // `String.prototype.trim` method
+ // https://tc39.es/ecma262/#sec-string.prototype.trim
+ _export({ target: 'String', proto: true, forced: stringTrimForced('trim') }, {
+ trim: function trim() {
+ return $trim(this);
+ }
+ });
+
+ var lookup$1 = [];
+ var revLookup$1 = [];
+ var Arr$1 = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
+ var inited$1 = false;
+
+ function init$1() {
+ inited$1 = true;
+ var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
+
+ for (var i = 0, len = code.length; i < len; ++i) {
+ lookup$1[i] = code[i];
+ revLookup$1[code.charCodeAt(i)] = i;
+ }
+
+ revLookup$1['-'.charCodeAt(0)] = 62;
+ revLookup$1['_'.charCodeAt(0)] = 63;
+ }
+
+ function toByteArray$1(b64) {
+ if (!inited$1) {
+ init$1();
+ }
+
+ var i, j, l, tmp, placeHolders, arr;
+ var len = b64.length;
+
+ if (len % 4 > 0) {
+ throw new Error('Invalid string. Length must be a multiple of 4');
+ } // the number of equal signs (place holders)
+ // if there are two placeholders, than the two characters before it
+ // represent one byte
+ // if there is only one, then the three characters before it represent 2 bytes
+ // this is just a cheap hack to not do indexOf twice
+
+
+ placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; // base64 is 4/3 + up to two characters of the original data
+
+ arr = new Arr$1(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars
+
+ l = placeHolders > 0 ? len - 4 : len;
+ var L = 0;
+
+ for (i = 0, j = 0; i < l; i += 4, j += 3) {
+ tmp = revLookup$1[b64.charCodeAt(i)] << 18 | revLookup$1[b64.charCodeAt(i + 1)] << 12 | revLookup$1[b64.charCodeAt(i + 2)] << 6 | revLookup$1[b64.charCodeAt(i + 3)];
+ arr[L++] = tmp >> 16 & 0xFF;
+ arr[L++] = tmp >> 8 & 0xFF;
+ arr[L++] = tmp & 0xFF;
+ }
+
+ if (placeHolders === 2) {
+ tmp = revLookup$1[b64.charCodeAt(i)] << 2 | revLookup$1[b64.charCodeAt(i + 1)] >> 4;
+ arr[L++] = tmp & 0xFF;
+ } else if (placeHolders === 1) {
+ tmp = revLookup$1[b64.charCodeAt(i)] << 10 | revLookup$1[b64.charCodeAt(i + 1)] << 4 | revLookup$1[b64.charCodeAt(i + 2)] >> 2;
+ arr[L++] = tmp >> 8 & 0xFF;
+ arr[L++] = tmp & 0xFF;
+ }
+
+ return arr;
+ }
+
+ function tripletToBase64$1(num) {
+ return lookup$1[num >> 18 & 0x3F] + lookup$1[num >> 12 & 0x3F] + lookup$1[num >> 6 & 0x3F] + lookup$1[num & 0x3F];
+ }
+
+ function encodeChunk$1(uint8, start, end) {
+ var tmp;
+ var output = [];
+
+ for (var i = start; i < end; i += 3) {
+ tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2];
+ output.push(tripletToBase64$1(tmp));
+ }
+
+ return output.join('');
+ }
+
+ function fromByteArray$1(uint8) {
+ if (!inited$1) {
+ init$1();
+ }
+
+ var tmp;
+ var len = uint8.length;
+ var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
+
+ var output = '';
+ var parts = [];
+ var maxChunkLength = 16383; // must be multiple of 3
+ // go through the array every three bytes, we'll deal with trailing stuff later
+
+ for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
+ parts.push(encodeChunk$1(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
+ } // pad the end with zeros, but make sure to not forget the extra bytes
+
+
+ if (extraBytes === 1) {
+ tmp = uint8[len - 1];
+ output += lookup$1[tmp >> 2];
+ output += lookup$1[tmp << 4 & 0x3F];
+ output += '==';
+ } else if (extraBytes === 2) {
+ tmp = (uint8[len - 2] << 8) + uint8[len - 1];
+ output += lookup$1[tmp >> 10];
+ output += lookup$1[tmp >> 4 & 0x3F];
+ output += lookup$1[tmp << 2 & 0x3F];
+ output += '=';
+ }
+
+ parts.push(output);
+ return parts.join('');
+ }
+
+ function read$1(buffer, offset, isLE, mLen, nBytes) {
+ var e, m;
+ var eLen = nBytes * 8 - mLen - 1;
+ var eMax = (1 << eLen) - 1;
+ var eBias = eMax >> 1;
+ var nBits = -7;
+ var i = isLE ? nBytes - 1 : 0;
+ var d = isLE ? -1 : 1;
+ var s = buffer[offset + i];
+ i += d;
+ e = s & (1 << -nBits) - 1;
+ s >>= -nBits;
+ nBits += eLen;
+
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+
+ m = e & (1 << -nBits) - 1;
+ e >>= -nBits;
+ nBits += mLen;
+
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+
+ if (e === 0) {
+ e = 1 - eBias;
+ } else if (e === eMax) {
+ return m ? NaN : (s ? -1 : 1) * Infinity;
+ } else {
+ m = m + Math.pow(2, mLen);
+ e = e - eBias;
+ }
+
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
+ }
+ function write$1(buffer, value, offset, isLE, mLen, nBytes) {
+ var e, m, c;
+ var eLen = nBytes * 8 - mLen - 1;
+ var eMax = (1 << eLen) - 1;
+ var eBias = eMax >> 1;
+ var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
+ var i = isLE ? 0 : nBytes - 1;
+ var d = isLE ? 1 : -1;
+ var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
+ value = Math.abs(value);
+
+ if (isNaN(value) || value === Infinity) {
+ m = isNaN(value) ? 1 : 0;
+ e = eMax;
+ } else {
+ e = Math.floor(Math.log(value) / Math.LN2);
+
+ if (value * (c = Math.pow(2, -e)) < 1) {
+ e--;
+ c *= 2;
+ }
+
+ if (e + eBias >= 1) {
+ value += rt / c;
+ } else {
+ value += rt * Math.pow(2, 1 - eBias);
+ }
+
+ if (value * c >= 2) {
+ e++;
+ c /= 2;
+ }
+
+ if (e + eBias >= eMax) {
+ m = 0;
+ e = eMax;
+ } else if (e + eBias >= 1) {
+ m = (value * c - 1) * Math.pow(2, mLen);
+ e = e + eBias;
+ } else {
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
+ e = 0;
+ }
+ }
+
+ for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
+
+ e = e << mLen | m;
+ eLen += mLen;
+
+ for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
+
+ buffer[offset + i - d] |= s * 128;
+ }
+
+ var toString$2 = {}.toString;
+ var isArray$2 = Array.isArray || function (arr) {
+ return toString$2.call(arr) == '[object Array]';
+ };
+
+ var INSPECT_MAX_BYTES$1 = 50;
+ /**
+ * If `Buffer.TYPED_ARRAY_SUPPORT`:
+ * === true Use Uint8Array implementation (fastest)
+ * === false Use Object implementation (most compatible, even IE6)
+ *
+ * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
+ * Opera 11.6+, iOS 4.2+.
+ *
+ * Due to various browser bugs, sometimes the Object implementation will be used even
+ * when the browser supports typed arrays.
+ *
+ * Note:
+ *
+ * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
+ * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
+ *
+ * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
+ *
+ * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
+ * incorrect length in some situations.
+
+ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
+ * get the Object implementation, which is slower but behaves correctly.
+ */
+
+ Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true;
+
+ function kMaxLength$1() {
+ return Buffer$1.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff;
+ }
+
+ function createBuffer$1(that, length) {
+ if (kMaxLength$1() < length) {
+ throw new RangeError('Invalid typed array length');
+ }
+
+ if (Buffer$1.TYPED_ARRAY_SUPPORT) {
+ // Return an augmented `Uint8Array` instance, for best performance
+ that = new Uint8Array(length);
+ that.__proto__ = Buffer$1.prototype;
+ } else {
+ // Fallback: Return an object instance of the Buffer class
+ if (that === null) {
+ that = new Buffer$1(length);
+ }
+
+ that.length = length;
+ }
+
+ return that;
+ }
+ /**
+ * The Buffer constructor returns instances of `Uint8Array` that have their
+ * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
+ * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
+ * and the `Uint8Array` methods. Square bracket notation works as expected -- it
+ * returns a single octet.
+ *
+ * The `Uint8Array` prototype remains unmodified.
+ */
+
+
+ function Buffer$1(arg, encodingOrOffset, length) {
+ if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) {
+ return new Buffer$1(arg, encodingOrOffset, length);
+ } // Common case.
+
+
+ if (typeof arg === 'number') {
+ if (typeof encodingOrOffset === 'string') {
+ throw new Error('If encoding is specified then the first argument must be a string');
+ }
+
+ return allocUnsafe$1(this, arg);
+ }
+
+ return from$1(this, arg, encodingOrOffset, length);
+ }
+ Buffer$1.poolSize = 8192; // not used by this implementation
+ // TODO: Legacy, not needed anymore. Remove in next major version.
+
+ Buffer$1._augment = function (arr) {
+ arr.__proto__ = Buffer$1.prototype;
+ return arr;
+ };
+
+ function from$1(that, value, encodingOrOffset, length) {
+ if (typeof value === 'number') {
+ throw new TypeError('"value" argument must not be a number');
+ }
+
+ if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
+ return fromArrayBuffer$1(that, value, encodingOrOffset, length);
+ }
+
+ if (typeof value === 'string') {
+ return fromString$1(that, value, encodingOrOffset);
+ }
+
+ return fromObject$1(that, value);
+ }
+ /**
+ * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
+ * if value is a number.
+ * Buffer.from(str[, encoding])
+ * Buffer.from(array)
+ * Buffer.from(buffer)
+ * Buffer.from(arrayBuffer[, byteOffset[, length]])
+ **/
+
+
+ Buffer$1.from = function (value, encodingOrOffset, length) {
+ return from$1(null, value, encodingOrOffset, length);
+ };
+
+ if (Buffer$1.TYPED_ARRAY_SUPPORT) {
+ Buffer$1.prototype.__proto__ = Uint8Array.prototype;
+ Buffer$1.__proto__ = Uint8Array;
+ }
+
+ function assertSize$1(size) {
+ if (typeof size !== 'number') {
+ throw new TypeError('"size" argument must be a number');
+ } else if (size < 0) {
+ throw new RangeError('"size" argument must not be negative');
+ }
+ }
+
+ function alloc$1(that, size, fill, encoding) {
+ assertSize$1(size);
+
+ if (size <= 0) {
+ return createBuffer$1(that, size);
+ }
+
+ if (fill !== undefined) {
+ // Only pay attention to encoding if it's a string. This
+ // prevents accidentally sending in a number that would
+ // be interpretted as a start offset.
+ return typeof encoding === 'string' ? createBuffer$1(that, size).fill(fill, encoding) : createBuffer$1(that, size).fill(fill);
+ }
+
+ return createBuffer$1(that, size);
+ }
+ /**
+ * Creates a new filled Buffer instance.
+ * alloc(size[, fill[, encoding]])
+ **/
+
+
+ Buffer$1.alloc = function (size, fill, encoding) {
+ return alloc$1(null, size, fill, encoding);
+ };
+
+ function allocUnsafe$1(that, size) {
+ assertSize$1(size);
+ that = createBuffer$1(that, size < 0 ? 0 : checked$1(size) | 0);
+
+ if (!Buffer$1.TYPED_ARRAY_SUPPORT) {
+ for (var i = 0; i < size; ++i) {
+ that[i] = 0;
+ }
+ }
+
+ return that;
+ }
+ /**
+ * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
+ * */
+
+
+ Buffer$1.allocUnsafe = function (size) {
+ return allocUnsafe$1(null, size);
+ };
+ /**
+ * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
+ */
+
+
+ Buffer$1.allocUnsafeSlow = function (size) {
+ return allocUnsafe$1(null, size);
+ };
+
+ function fromString$1(that, string, encoding) {
+ if (typeof encoding !== 'string' || encoding === '') {
+ encoding = 'utf8';
+ }
+
+ if (!Buffer$1.isEncoding(encoding)) {
+ throw new TypeError('"encoding" must be a valid string encoding');
+ }
+
+ var length = byteLength$1(string, encoding) | 0;
+ that = createBuffer$1(that, length);
+ var actual = that.write(string, encoding);
+
+ if (actual !== length) {
+ // Writing a hex string, for example, that contains invalid characters will
+ // cause everything after the first invalid character to be ignored. (e.g.
+ // 'abxxcd' will be treated as 'ab')
+ that = that.slice(0, actual);
+ }
+
+ return that;
+ }
+
+ function fromArrayLike$1(that, array) {
+ var length = array.length < 0 ? 0 : checked$1(array.length) | 0;
+ that = createBuffer$1(that, length);
+
+ for (var i = 0; i < length; i += 1) {
+ that[i] = array[i] & 255;
+ }
+
+ return that;
+ }
+
+ function fromArrayBuffer$1(that, array, byteOffset, length) {
+ array.byteLength; // this throws if `array` is not a valid ArrayBuffer
+
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
+ throw new RangeError('\'offset\' is out of bounds');
+ }
+
+ if (array.byteLength < byteOffset + (length || 0)) {
+ throw new RangeError('\'length\' is out of bounds');
+ }
+
+ if (byteOffset === undefined && length === undefined) {
+ array = new Uint8Array(array);
+ } else if (length === undefined) {
+ array = new Uint8Array(array, byteOffset);
+ } else {
+ array = new Uint8Array(array, byteOffset, length);
+ }
+
+ if (Buffer$1.TYPED_ARRAY_SUPPORT) {
+ // Return an augmented `Uint8Array` instance, for best performance
+ that = array;
+ that.__proto__ = Buffer$1.prototype;
+ } else {
+ // Fallback: Return an object instance of the Buffer class
+ that = fromArrayLike$1(that, array);
+ }
+
+ return that;
+ }
+
+ function fromObject$1(that, obj) {
+ if (internalIsBuffer$1(obj)) {
+ var len = checked$1(obj.length) | 0;
+ that = createBuffer$1(that, len);
+
+ if (that.length === 0) {
+ return that;
+ }
+
+ obj.copy(that, 0, 0, len);
+ return that;
+ }
+
+ if (obj) {
+ if (typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer || 'length' in obj) {
+ if (typeof obj.length !== 'number' || isnan$1(obj.length)) {
+ return createBuffer$1(that, 0);
+ }
+
+ return fromArrayLike$1(that, obj);
+ }
+
+ if (obj.type === 'Buffer' && isArray$2(obj.data)) {
+ return fromArrayLike$1(that, obj.data);
+ }
+ }
+
+ throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.');
+ }
+
+ function checked$1(length) {
+ // Note: cannot use `length < kMaxLength()` here because that fails when
+ // length is NaN (which is otherwise coerced to zero.)
+ if (length >= kMaxLength$1()) {
+ throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength$1().toString(16) + ' bytes');
+ }
+
+ return length | 0;
+ }
+ Buffer$1.isBuffer = isBuffer$2;
+
+ function internalIsBuffer$1(b) {
+ return !!(b != null && b._isBuffer);
+ }
+
+ Buffer$1.compare = function compare(a, b) {
+ if (!internalIsBuffer$1(a) || !internalIsBuffer$1(b)) {
+ throw new TypeError('Arguments must be Buffers');
+ }
+
+ if (a === b) return 0;
+ var x = a.length;
+ var y = b.length;
+
+ for (var i = 0, len = Math.min(x, y); i < len; ++i) {
+ if (a[i] !== b[i]) {
+ x = a[i];
+ y = b[i];
+ break;
+ }
+ }
+
+ if (x < y) return -1;
+ if (y < x) return 1;
+ return 0;
+ };
+
+ Buffer$1.isEncoding = function isEncoding(encoding) {
+ switch (String(encoding).toLowerCase()) {
+ case 'hex':
+ case 'utf8':
+ case 'utf-8':
+ case 'ascii':
+ case 'latin1':
+ case 'binary':
+ case 'base64':
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return true;
+
+ default:
+ return false;
+ }
+ };
+
+ Buffer$1.concat = function concat(list, length) {
+ if (!isArray$2(list)) {
+ throw new TypeError('"list" argument must be an Array of Buffers');
+ }
+
+ if (list.length === 0) {
+ return Buffer$1.alloc(0);
+ }
+
+ var i;
+
+ if (length === undefined) {
+ length = 0;
+
+ for (i = 0; i < list.length; ++i) {
+ length += list[i].length;
+ }
+ }
+
+ var buffer = Buffer$1.allocUnsafe(length);
+ var pos = 0;
+
+ for (i = 0; i < list.length; ++i) {
+ var buf = list[i];
+
+ if (!internalIsBuffer$1(buf)) {
+ throw new TypeError('"list" argument must be an Array of Buffers');
+ }
+
+ buf.copy(buffer, pos);
+ pos += buf.length;
+ }
+
+ return buffer;
+ };
+
+ function byteLength$1(string, encoding) {
+ if (internalIsBuffer$1(string)) {
+ return string.length;
+ }
+
+ if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
+ return string.byteLength;
+ }
+
+ if (typeof string !== 'string') {
+ string = '' + string;
+ }
+
+ var len = string.length;
+ if (len === 0) return 0; // Use a for loop to avoid recursion
+
+ var loweredCase = false;
+
+ for (;;) {
+ switch (encoding) {
+ case 'ascii':
+ case 'latin1':
+ case 'binary':
+ return len;
+
+ case 'utf8':
+ case 'utf-8':
+ case undefined:
+ return utf8ToBytes$1(string).length;
+
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return len * 2;
+
+ case 'hex':
+ return len >>> 1;
+
+ case 'base64':
+ return base64ToBytes$1(string).length;
+
+ default:
+ if (loweredCase) return utf8ToBytes$1(string).length; // assume utf8
+
+ encoding = ('' + encoding).toLowerCase();
+ loweredCase = true;
+ }
+ }
+ }
+
+ Buffer$1.byteLength = byteLength$1;
+
+ function slowToString$1(encoding, start, end) {
+ var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
+ // property of a typed array.
+ // This behaves neither like String nor Uint8Array in that we set start/end
+ // to their upper/lower bounds if the value passed is out of range.
+ // undefined is handled specially as per ECMA-262 6th Edition,
+ // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
+
+ if (start === undefined || start < 0) {
+ start = 0;
+ } // Return early if start > this.length. Done here to prevent potential uint32
+ // coercion fail below.
+
+
+ if (start > this.length) {
+ return '';
+ }
+
+ if (end === undefined || end > this.length) {
+ end = this.length;
+ }
+
+ if (end <= 0) {
+ return '';
+ } // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
+
+
+ end >>>= 0;
+ start >>>= 0;
+
+ if (end <= start) {
+ return '';
+ }
+
+ if (!encoding) encoding = 'utf8';
+
+ while (true) {
+ switch (encoding) {
+ case 'hex':
+ return hexSlice$1(this, start, end);
+
+ case 'utf8':
+ case 'utf-8':
+ return utf8Slice$1(this, start, end);
+
+ case 'ascii':
+ return asciiSlice$1(this, start, end);
+
+ case 'latin1':
+ case 'binary':
+ return latin1Slice$1(this, start, end);
+
+ case 'base64':
+ return base64Slice$1(this, start, end);
+
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return utf16leSlice$1(this, start, end);
+
+ default:
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
+ encoding = (encoding + '').toLowerCase();
+ loweredCase = true;
+ }
+ }
+ } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
+ // Buffer instances.
+
+
+ Buffer$1.prototype._isBuffer = true;
+
+ function swap$1(b, n, m) {
+ var i = b[n];
+ b[n] = b[m];
+ b[m] = i;
+ }
+
+ Buffer$1.prototype.swap16 = function swap16() {
+ var len = this.length;
+
+ if (len % 2 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 16-bits');
+ }
+
+ for (var i = 0; i < len; i += 2) {
+ swap$1(this, i, i + 1);
+ }
+
+ return this;
+ };
+
+ Buffer$1.prototype.swap32 = function swap32() {
+ var len = this.length;
+
+ if (len % 4 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 32-bits');
+ }
+
+ for (var i = 0; i < len; i += 4) {
+ swap$1(this, i, i + 3);
+ swap$1(this, i + 1, i + 2);
+ }
+
+ return this;
+ };
+
+ Buffer$1.prototype.swap64 = function swap64() {
+ var len = this.length;
+
+ if (len % 8 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 64-bits');
+ }
+
+ for (var i = 0; i < len; i += 8) {
+ swap$1(this, i, i + 7);
+ swap$1(this, i + 1, i + 6);
+ swap$1(this, i + 2, i + 5);
+ swap$1(this, i + 3, i + 4);
+ }
+
+ return this;
+ };
+
+ Buffer$1.prototype.toString = function toString() {
+ var length = this.length | 0;
+ if (length === 0) return '';
+ if (arguments.length === 0) return utf8Slice$1(this, 0, length);
+ return slowToString$1.apply(this, arguments);
+ };
+
+ Buffer$1.prototype.equals = function equals(b) {
+ if (!internalIsBuffer$1(b)) throw new TypeError('Argument must be a Buffer');
+ if (this === b) return true;
+ return Buffer$1.compare(this, b) === 0;
+ };
+
+ Buffer$1.prototype.inspect = function inspect() {
+ var str = '';
+ var max = INSPECT_MAX_BYTES$1;
+
+ if (this.length > 0) {
+ str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
+ if (this.length > max) str += ' ... ';
+ }
+
+ return '';
+ };
+
+ Buffer$1.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
+ if (!internalIsBuffer$1(target)) {
+ throw new TypeError('Argument must be a Buffer');
+ }
+
+ if (start === undefined) {
+ start = 0;
+ }
+
+ if (end === undefined) {
+ end = target ? target.length : 0;
+ }
+
+ if (thisStart === undefined) {
+ thisStart = 0;
+ }
+
+ if (thisEnd === undefined) {
+ thisEnd = this.length;
+ }
+
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
+ throw new RangeError('out of range index');
+ }
+
+ if (thisStart >= thisEnd && start >= end) {
+ return 0;
+ }
+
+ if (thisStart >= thisEnd) {
+ return -1;
+ }
+
+ if (start >= end) {
+ return 1;
+ }
+
+ start >>>= 0;
+ end >>>= 0;
+ thisStart >>>= 0;
+ thisEnd >>>= 0;
+ if (this === target) return 0;
+ var x = thisEnd - thisStart;
+ var y = end - start;
+ var len = Math.min(x, y);
+ var thisCopy = this.slice(thisStart, thisEnd);
+ var targetCopy = target.slice(start, end);
+
+ for (var i = 0; i < len; ++i) {
+ if (thisCopy[i] !== targetCopy[i]) {
+ x = thisCopy[i];
+ y = targetCopy[i];
+ break;
+ }
+ }
+
+ if (x < y) return -1;
+ if (y < x) return 1;
+ return 0;
+ }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
+ // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
+ //
+ // Arguments:
+ // - buffer - a Buffer to search
+ // - val - a string, Buffer, or number
+ // - byteOffset - an index into `buffer`; will be clamped to an int32
+ // - encoding - an optional encoding, relevant is val is a string
+ // - dir - true for indexOf, false for lastIndexOf
+
+
+ function bidirectionalIndexOf$1(buffer, val, byteOffset, encoding, dir) {
+ // Empty buffer means no match
+ if (buffer.length === 0) return -1; // Normalize byteOffset
+
+ if (typeof byteOffset === 'string') {
+ encoding = byteOffset;
+ byteOffset = 0;
+ } else if (byteOffset > 0x7fffffff) {
+ byteOffset = 0x7fffffff;
+ } else if (byteOffset < -0x80000000) {
+ byteOffset = -0x80000000;
+ }
+
+ byteOffset = +byteOffset; // Coerce to Number.
+
+ if (isNaN(byteOffset)) {
+ // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
+ byteOffset = dir ? 0 : buffer.length - 1;
+ } // Normalize byteOffset: negative offsets start from the end of the buffer
+
+
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
+
+ if (byteOffset >= buffer.length) {
+ if (dir) return -1;else byteOffset = buffer.length - 1;
+ } else if (byteOffset < 0) {
+ if (dir) byteOffset = 0;else return -1;
+ } // Normalize val
+
+
+ if (typeof val === 'string') {
+ val = Buffer$1.from(val, encoding);
+ } // Finally, search either indexOf (if dir is true) or lastIndexOf
+
+
+ if (internalIsBuffer$1(val)) {
+ // Special case: looking for empty string/buffer always fails
+ if (val.length === 0) {
+ return -1;
+ }
+
+ return arrayIndexOf$1(buffer, val, byteOffset, encoding, dir);
+ } else if (typeof val === 'number') {
+ val = val & 0xFF; // Search for a byte value [0-255]
+
+ if (Buffer$1.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') {
+ if (dir) {
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
+ } else {
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
+ }
+ }
+
+ return arrayIndexOf$1(buffer, [val], byteOffset, encoding, dir);
+ }
+
+ throw new TypeError('val must be string, number or Buffer');
+ }
+
+ function arrayIndexOf$1(arr, val, byteOffset, encoding, dir) {
+ var indexSize = 1;
+ var arrLength = arr.length;
+ var valLength = val.length;
+
+ if (encoding !== undefined) {
+ encoding = String(encoding).toLowerCase();
+
+ if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') {
+ if (arr.length < 2 || val.length < 2) {
+ return -1;
+ }
+
+ indexSize = 2;
+ arrLength /= 2;
+ valLength /= 2;
+ byteOffset /= 2;
+ }
+ }
+
+ function read(buf, i) {
+ if (indexSize === 1) {
+ return buf[i];
+ } else {
+ return buf.readUInt16BE(i * indexSize);
+ }
+ }
+
+ var i;
+
+ if (dir) {
+ var foundIndex = -1;
+
+ for (i = byteOffset; i < arrLength; i++) {
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
+ if (foundIndex === -1) foundIndex = i;
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
+ } else {
+ if (foundIndex !== -1) i -= i - foundIndex;
+ foundIndex = -1;
+ }
+ }
+ } else {
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
+
+ for (i = byteOffset; i >= 0; i--) {
+ var found = true;
+
+ for (var j = 0; j < valLength; j++) {
+ if (read(arr, i + j) !== read(val, j)) {
+ found = false;
+ break;
+ }
+ }
+
+ if (found) return i;
+ }
+ }
+
+ return -1;
+ }
+
+ Buffer$1.prototype.includes = function includes(val, byteOffset, encoding) {
+ return this.indexOf(val, byteOffset, encoding) !== -1;
+ };
+
+ Buffer$1.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
+ return bidirectionalIndexOf$1(this, val, byteOffset, encoding, true);
+ };
+
+ Buffer$1.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
+ return bidirectionalIndexOf$1(this, val, byteOffset, encoding, false);
+ };
+
+ function hexWrite$1(buf, string, offset, length) {
+ offset = Number(offset) || 0;
+ var remaining = buf.length - offset;
+
+ if (!length) {
+ length = remaining;
+ } else {
+ length = Number(length);
+
+ if (length > remaining) {
+ length = remaining;
+ }
+ } // must be an even number of digits
+
+
+ var strLen = string.length;
+ if (strLen % 2 !== 0) throw new TypeError('Invalid hex string');
+
+ if (length > strLen / 2) {
+ length = strLen / 2;
+ }
+
+ for (var i = 0; i < length; ++i) {
+ var parsed = parseInt(string.substr(i * 2, 2), 16);
+ if (isNaN(parsed)) return i;
+ buf[offset + i] = parsed;
+ }
+
+ return i;
+ }
+
+ function utf8Write$1(buf, string, offset, length) {
+ return blitBuffer$1(utf8ToBytes$1(string, buf.length - offset), buf, offset, length);
+ }
+
+ function asciiWrite$1(buf, string, offset, length) {
+ return blitBuffer$1(asciiToBytes$1(string), buf, offset, length);
+ }
+
+ function latin1Write$1(buf, string, offset, length) {
+ return asciiWrite$1(buf, string, offset, length);
+ }
+
+ function base64Write$1(buf, string, offset, length) {
+ return blitBuffer$1(base64ToBytes$1(string), buf, offset, length);
+ }
+
+ function ucs2Write$1(buf, string, offset, length) {
+ return blitBuffer$1(utf16leToBytes$1(string, buf.length - offset), buf, offset, length);
+ }
+
+ Buffer$1.prototype.write = function write(string, offset, length, encoding) {
+ // Buffer#write(string)
+ if (offset === undefined) {
+ encoding = 'utf8';
+ length = this.length;
+ offset = 0; // Buffer#write(string, encoding)
+ } else if (length === undefined && typeof offset === 'string') {
+ encoding = offset;
+ length = this.length;
+ offset = 0; // Buffer#write(string, offset[, length][, encoding])
+ } else if (isFinite(offset)) {
+ offset = offset | 0;
+
+ if (isFinite(length)) {
+ length = length | 0;
+ if (encoding === undefined) encoding = 'utf8';
+ } else {
+ encoding = length;
+ length = undefined;
+ } // legacy write(string, encoding, offset, length) - remove in v0.13
+
+ } else {
+ throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported');
+ }
+
+ var remaining = this.length - offset;
+ if (length === undefined || length > remaining) length = remaining;
+
+ if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
+ throw new RangeError('Attempt to write outside buffer bounds');
+ }
+
+ if (!encoding) encoding = 'utf8';
+ var loweredCase = false;
+
+ for (;;) {
+ switch (encoding) {
+ case 'hex':
+ return hexWrite$1(this, string, offset, length);
+
+ case 'utf8':
+ case 'utf-8':
+ return utf8Write$1(this, string, offset, length);
+
+ case 'ascii':
+ return asciiWrite$1(this, string, offset, length);
+
+ case 'latin1':
+ case 'binary':
+ return latin1Write$1(this, string, offset, length);
+
+ case 'base64':
+ // Warning: maxLength not taken into account in base64Write
+ return base64Write$1(this, string, offset, length);
+
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return ucs2Write$1(this, string, offset, length);
+
+ default:
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
+ encoding = ('' + encoding).toLowerCase();
+ loweredCase = true;
+ }
+ }
+ };
+
+ Buffer$1.prototype.toJSON = function toJSON() {
+ return {
+ type: 'Buffer',
+ data: Array.prototype.slice.call(this._arr || this, 0)
+ };
+ };
+
+ function base64Slice$1(buf, start, end) {
+ if (start === 0 && end === buf.length) {
+ return fromByteArray$1(buf);
+ } else {
+ return fromByteArray$1(buf.slice(start, end));
+ }
+ }
+
+ function utf8Slice$1(buf, start, end) {
+ end = Math.min(buf.length, end);
+ var res = [];
+ var i = start;
+
+ while (i < end) {
+ var firstByte = buf[i];
+ var codePoint = null;
+ var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1;
+
+ if (i + bytesPerSequence <= end) {
+ var secondByte, thirdByte, fourthByte, tempCodePoint;
+
+ switch (bytesPerSequence) {
+ case 1:
+ if (firstByte < 0x80) {
+ codePoint = firstByte;
+ }
+
+ break;
+
+ case 2:
+ secondByte = buf[i + 1];
+
+ if ((secondByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F;
+
+ if (tempCodePoint > 0x7F) {
+ codePoint = tempCodePoint;
+ }
+ }
+
+ break;
+
+ case 3:
+ secondByte = buf[i + 1];
+ thirdByte = buf[i + 2];
+
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F;
+
+ if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
+ codePoint = tempCodePoint;
+ }
+ }
+
+ break;
+
+ case 4:
+ secondByte = buf[i + 1];
+ thirdByte = buf[i + 2];
+ fourthByte = buf[i + 3];
+
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F;
+
+ if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
+ codePoint = tempCodePoint;
+ }
+ }
+
+ }
+ }
+
+ if (codePoint === null) {
+ // we did not generate a valid codePoint so insert a
+ // replacement char (U+FFFD) and advance only 1 byte
+ codePoint = 0xFFFD;
+ bytesPerSequence = 1;
+ } else if (codePoint > 0xFFFF) {
+ // encode to utf16 (surrogate pair dance)
+ codePoint -= 0x10000;
+ res.push(codePoint >>> 10 & 0x3FF | 0xD800);
+ codePoint = 0xDC00 | codePoint & 0x3FF;
+ }
+
+ res.push(codePoint);
+ i += bytesPerSequence;
+ }
+
+ return decodeCodePointsArray$1(res);
+ } // Based on http://stackoverflow.com/a/22747272/680742, the browser with
+ // the lowest limit is Chrome, with 0x10000 args.
+ // We go 1 magnitude less, for safety
+
+
+ var MAX_ARGUMENTS_LENGTH$1 = 0x1000;
+
+ function decodeCodePointsArray$1(codePoints) {
+ var len = codePoints.length;
+
+ if (len <= MAX_ARGUMENTS_LENGTH$1) {
+ return String.fromCharCode.apply(String, codePoints); // avoid extra slice()
+ } // Decode in chunks to avoid "call stack size exceeded".
+
+
+ var res = '';
+ var i = 0;
+
+ while (i < len) {
+ res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH$1));
+ }
+
+ return res;
+ }
+
+ function asciiSlice$1(buf, start, end) {
+ var ret = '';
+ end = Math.min(buf.length, end);
+
+ for (var i = start; i < end; ++i) {
+ ret += String.fromCharCode(buf[i] & 0x7F);
+ }
+
+ return ret;
+ }
+
+ function latin1Slice$1(buf, start, end) {
+ var ret = '';
+ end = Math.min(buf.length, end);
+
+ for (var i = start; i < end; ++i) {
+ ret += String.fromCharCode(buf[i]);
+ }
+
+ return ret;
+ }
+
+ function hexSlice$1(buf, start, end) {
+ var len = buf.length;
+ if (!start || start < 0) start = 0;
+ if (!end || end < 0 || end > len) end = len;
+ var out = '';
+
+ for (var i = start; i < end; ++i) {
+ out += toHex$1(buf[i]);
+ }
+
+ return out;
+ }
+
+ function utf16leSlice$1(buf, start, end) {
+ var bytes = buf.slice(start, end);
+ var res = '';
+
+ for (var i = 0; i < bytes.length; i += 2) {
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
+ }
+
+ return res;
+ }
+
+ Buffer$1.prototype.slice = function slice(start, end) {
+ var len = this.length;
+ start = ~~start;
+ end = end === undefined ? len : ~~end;
+
+ if (start < 0) {
+ start += len;
+ if (start < 0) start = 0;
+ } else if (start > len) {
+ start = len;
+ }
+
+ if (end < 0) {
+ end += len;
+ if (end < 0) end = 0;
+ } else if (end > len) {
+ end = len;
+ }
+
+ if (end < start) end = start;
+ var newBuf;
+
+ if (Buffer$1.TYPED_ARRAY_SUPPORT) {
+ newBuf = this.subarray(start, end);
+ newBuf.__proto__ = Buffer$1.prototype;
+ } else {
+ var sliceLen = end - start;
+ newBuf = new Buffer$1(sliceLen, undefined);
+
+ for (var i = 0; i < sliceLen; ++i) {
+ newBuf[i] = this[i + start];
+ }
+ }
+
+ return newBuf;
+ };
+ /*
+ * Need to make sure that buffer isn't trying to write out of bounds.
+ */
+
+
+ function checkOffset$1(offset, ext, length) {
+ if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint');
+ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length');
+ }
+
+ Buffer$1.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
+ offset = offset | 0;
+ byteLength = byteLength | 0;
+ if (!noAssert) checkOffset$1(offset, byteLength, this.length);
+ var val = this[offset];
+ var mul = 1;
+ var i = 0;
+
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul;
+ }
+
+ return val;
+ };
+
+ Buffer$1.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
+ offset = offset | 0;
+ byteLength = byteLength | 0;
+
+ if (!noAssert) {
+ checkOffset$1(offset, byteLength, this.length);
+ }
+
+ var val = this[offset + --byteLength];
+ var mul = 1;
+
+ while (byteLength > 0 && (mul *= 0x100)) {
+ val += this[offset + --byteLength] * mul;
+ }
+
+ return val;
+ };
+
+ Buffer$1.prototype.readUInt8 = function readUInt8(offset, noAssert) {
+ if (!noAssert) checkOffset$1(offset, 1, this.length);
+ return this[offset];
+ };
+
+ Buffer$1.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
+ if (!noAssert) checkOffset$1(offset, 2, this.length);
+ return this[offset] | this[offset + 1] << 8;
+ };
+
+ Buffer$1.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
+ if (!noAssert) checkOffset$1(offset, 2, this.length);
+ return this[offset] << 8 | this[offset + 1];
+ };
+
+ Buffer$1.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
+ if (!noAssert) checkOffset$1(offset, 4, this.length);
+ return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000;
+ };
+
+ Buffer$1.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
+ if (!noAssert) checkOffset$1(offset, 4, this.length);
+ return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
+ };
+
+ Buffer$1.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
+ offset = offset | 0;
+ byteLength = byteLength | 0;
+ if (!noAssert) checkOffset$1(offset, byteLength, this.length);
+ var val = this[offset];
+ var mul = 1;
+ var i = 0;
+
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul;
+ }
+
+ mul *= 0x80;
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength);
+ return val;
+ };
+
+ Buffer$1.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
+ offset = offset | 0;
+ byteLength = byteLength | 0;
+ if (!noAssert) checkOffset$1(offset, byteLength, this.length);
+ var i = byteLength;
+ var mul = 1;
+ var val = this[offset + --i];
+
+ while (i > 0 && (mul *= 0x100)) {
+ val += this[offset + --i] * mul;
+ }
+
+ mul *= 0x80;
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength);
+ return val;
+ };
+
+ Buffer$1.prototype.readInt8 = function readInt8(offset, noAssert) {
+ if (!noAssert) checkOffset$1(offset, 1, this.length);
+ if (!(this[offset] & 0x80)) return this[offset];
+ return (0xff - this[offset] + 1) * -1;
+ };
+
+ Buffer$1.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
+ if (!noAssert) checkOffset$1(offset, 2, this.length);
+ var val = this[offset] | this[offset + 1] << 8;
+ return val & 0x8000 ? val | 0xFFFF0000 : val;
+ };
+
+ Buffer$1.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
+ if (!noAssert) checkOffset$1(offset, 2, this.length);
+ var val = this[offset + 1] | this[offset] << 8;
+ return val & 0x8000 ? val | 0xFFFF0000 : val;
+ };
+
+ Buffer$1.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
+ if (!noAssert) checkOffset$1(offset, 4, this.length);
+ return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
+ };
+
+ Buffer$1.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
+ if (!noAssert) checkOffset$1(offset, 4, this.length);
+ return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
+ };
+
+ Buffer$1.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
+ if (!noAssert) checkOffset$1(offset, 4, this.length);
+ return read$1(this, offset, true, 23, 4);
+ };
+
+ Buffer$1.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
+ if (!noAssert) checkOffset$1(offset, 4, this.length);
+ return read$1(this, offset, false, 23, 4);
+ };
+
+ Buffer$1.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
+ if (!noAssert) checkOffset$1(offset, 8, this.length);
+ return read$1(this, offset, true, 52, 8);
+ };
+
+ Buffer$1.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
+ if (!noAssert) checkOffset$1(offset, 8, this.length);
+ return read$1(this, offset, false, 52, 8);
+ };
+
+ function checkInt$1(buf, value, offset, ext, max, min) {
+ if (!internalIsBuffer$1(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
+ if (offset + ext > buf.length) throw new RangeError('Index out of range');
+ }
+
+ Buffer$1.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ byteLength = byteLength | 0;
+
+ if (!noAssert) {
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1;
+ checkInt$1(this, value, offset, byteLength, maxBytes, 0);
+ }
+
+ var mul = 1;
+ var i = 0;
+ this[offset] = value & 0xFF;
+
+ while (++i < byteLength && (mul *= 0x100)) {
+ this[offset + i] = value / mul & 0xFF;
+ }
+
+ return offset + byteLength;
+ };
+
+ Buffer$1.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ byteLength = byteLength | 0;
+
+ if (!noAssert) {
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1;
+ checkInt$1(this, value, offset, byteLength, maxBytes, 0);
+ }
+
+ var i = byteLength - 1;
+ var mul = 1;
+ this[offset + i] = value & 0xFF;
+
+ while (--i >= 0 && (mul *= 0x100)) {
+ this[offset + i] = value / mul & 0xFF;
+ }
+
+ return offset + byteLength;
+ };
+
+ Buffer$1.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt$1(this, value, offset, 1, 0xff, 0);
+ if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
+ this[offset] = value & 0xff;
+ return offset + 1;
+ };
+
+ function objectWriteUInt16$1(buf, value, offset, littleEndian) {
+ if (value < 0) value = 0xffff + value + 1;
+
+ for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
+ buf[offset + i] = (value & 0xff << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8;
+ }
+ }
+
+ Buffer$1.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt$1(this, value, offset, 2, 0xffff, 0);
+
+ if (Buffer$1.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value & 0xff;
+ this[offset + 1] = value >>> 8;
+ } else {
+ objectWriteUInt16$1(this, value, offset, true);
+ }
+
+ return offset + 2;
+ };
+
+ Buffer$1.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt$1(this, value, offset, 2, 0xffff, 0);
+
+ if (Buffer$1.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value >>> 8;
+ this[offset + 1] = value & 0xff;
+ } else {
+ objectWriteUInt16$1(this, value, offset, false);
+ }
+
+ return offset + 2;
+ };
+
+ function objectWriteUInt32$1(buf, value, offset, littleEndian) {
+ if (value < 0) value = 0xffffffff + value + 1;
+
+ for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
+ buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 0xff;
+ }
+ }
+
+ Buffer$1.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt$1(this, value, offset, 4, 0xffffffff, 0);
+
+ if (Buffer$1.TYPED_ARRAY_SUPPORT) {
+ this[offset + 3] = value >>> 24;
+ this[offset + 2] = value >>> 16;
+ this[offset + 1] = value >>> 8;
+ this[offset] = value & 0xff;
+ } else {
+ objectWriteUInt32$1(this, value, offset, true);
+ }
+
+ return offset + 4;
+ };
+
+ Buffer$1.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt$1(this, value, offset, 4, 0xffffffff, 0);
+
+ if (Buffer$1.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value >>> 24;
+ this[offset + 1] = value >>> 16;
+ this[offset + 2] = value >>> 8;
+ this[offset + 3] = value & 0xff;
+ } else {
+ objectWriteUInt32$1(this, value, offset, false);
+ }
+
+ return offset + 4;
+ };
+
+ Buffer$1.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
+ value = +value;
+ offset = offset | 0;
+
+ if (!noAssert) {
+ var limit = Math.pow(2, 8 * byteLength - 1);
+ checkInt$1(this, value, offset, byteLength, limit - 1, -limit);
+ }
+
+ var i = 0;
+ var mul = 1;
+ var sub = 0;
+ this[offset] = value & 0xFF;
+
+ while (++i < byteLength && (mul *= 0x100)) {
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
+ sub = 1;
+ }
+
+ this[offset + i] = (value / mul >> 0) - sub & 0xFF;
+ }
+
+ return offset + byteLength;
+ };
+
+ Buffer$1.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
+ value = +value;
+ offset = offset | 0;
+
+ if (!noAssert) {
+ var limit = Math.pow(2, 8 * byteLength - 1);
+ checkInt$1(this, value, offset, byteLength, limit - 1, -limit);
+ }
+
+ var i = byteLength - 1;
+ var mul = 1;
+ var sub = 0;
+ this[offset + i] = value & 0xFF;
+
+ while (--i >= 0 && (mul *= 0x100)) {
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
+ sub = 1;
+ }
+
+ this[offset + i] = (value / mul >> 0) - sub & 0xFF;
+ }
+
+ return offset + byteLength;
+ };
+
+ Buffer$1.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt$1(this, value, offset, 1, 0x7f, -0x80);
+ if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
+ if (value < 0) value = 0xff + value + 1;
+ this[offset] = value & 0xff;
+ return offset + 1;
+ };
+
+ Buffer$1.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt$1(this, value, offset, 2, 0x7fff, -0x8000);
+
+ if (Buffer$1.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value & 0xff;
+ this[offset + 1] = value >>> 8;
+ } else {
+ objectWriteUInt16$1(this, value, offset, true);
+ }
+
+ return offset + 2;
+ };
+
+ Buffer$1.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt$1(this, value, offset, 2, 0x7fff, -0x8000);
+
+ if (Buffer$1.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value >>> 8;
+ this[offset + 1] = value & 0xff;
+ } else {
+ objectWriteUInt16$1(this, value, offset, false);
+ }
+
+ return offset + 2;
+ };
+
+ Buffer$1.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt$1(this, value, offset, 4, 0x7fffffff, -0x80000000);
+
+ if (Buffer$1.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value & 0xff;
+ this[offset + 1] = value >>> 8;
+ this[offset + 2] = value >>> 16;
+ this[offset + 3] = value >>> 24;
+ } else {
+ objectWriteUInt32$1(this, value, offset, true);
+ }
+
+ return offset + 4;
+ };
+
+ Buffer$1.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt$1(this, value, offset, 4, 0x7fffffff, -0x80000000);
+ if (value < 0) value = 0xffffffff + value + 1;
+
+ if (Buffer$1.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value >>> 24;
+ this[offset + 1] = value >>> 16;
+ this[offset + 2] = value >>> 8;
+ this[offset + 3] = value & 0xff;
+ } else {
+ objectWriteUInt32$1(this, value, offset, false);
+ }
+
+ return offset + 4;
+ };
+
+ function checkIEEE754$1(buf, value, offset, ext, max, min) {
+ if (offset + ext > buf.length) throw new RangeError('Index out of range');
+ if (offset < 0) throw new RangeError('Index out of range');
+ }
+
+ function writeFloat$1(buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ checkIEEE754$1(buf, value, offset, 4);
+ }
+
+ write$1(buf, value, offset, littleEndian, 23, 4);
+ return offset + 4;
+ }
+
+ Buffer$1.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
+ return writeFloat$1(this, value, offset, true, noAssert);
+ };
+
+ Buffer$1.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
+ return writeFloat$1(this, value, offset, false, noAssert);
+ };
+
+ function writeDouble$1(buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ checkIEEE754$1(buf, value, offset, 8);
+ }
+
+ write$1(buf, value, offset, littleEndian, 52, 8);
+ return offset + 8;
+ }
+
+ Buffer$1.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
+ return writeDouble$1(this, value, offset, true, noAssert);
+ };
+
+ Buffer$1.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
+ return writeDouble$1(this, value, offset, false, noAssert);
+ }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
+
+
+ Buffer$1.prototype.copy = function copy(target, targetStart, start, end) {
+ if (!start) start = 0;
+ if (!end && end !== 0) end = this.length;
+ if (targetStart >= target.length) targetStart = target.length;
+ if (!targetStart) targetStart = 0;
+ if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done
+
+ if (end === start) return 0;
+ if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions
+
+ if (targetStart < 0) {
+ throw new RangeError('targetStart out of bounds');
+ }
+
+ if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds');
+ if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob?
+
+ if (end > this.length) end = this.length;
+
+ if (target.length - targetStart < end - start) {
+ end = target.length - targetStart + start;
+ }
+
+ var len = end - start;
+ var i;
+
+ if (this === target && start < targetStart && targetStart < end) {
+ // descending copy from end
+ for (i = len - 1; i >= 0; --i) {
+ target[i + targetStart] = this[i + start];
+ }
+ } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) {
+ // ascending copy from start
+ for (i = 0; i < len; ++i) {
+ target[i + targetStart] = this[i + start];
+ }
+ } else {
+ Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart);
+ }
+
+ return len;
+ }; // Usage:
+ // buffer.fill(number[, offset[, end]])
+ // buffer.fill(buffer[, offset[, end]])
+ // buffer.fill(string[, offset[, end]][, encoding])
+
+
+ Buffer$1.prototype.fill = function fill(val, start, end, encoding) {
+ // Handle string cases:
+ if (typeof val === 'string') {
+ if (typeof start === 'string') {
+ encoding = start;
+ start = 0;
+ end = this.length;
+ } else if (typeof end === 'string') {
+ encoding = end;
+ end = this.length;
+ }
+
+ if (val.length === 1) {
+ var code = val.charCodeAt(0);
+
+ if (code < 256) {
+ val = code;
+ }
+ }
+
+ if (encoding !== undefined && typeof encoding !== 'string') {
+ throw new TypeError('encoding must be a string');
+ }
+
+ if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) {
+ throw new TypeError('Unknown encoding: ' + encoding);
+ }
+ } else if (typeof val === 'number') {
+ val = val & 255;
+ } // Invalid ranges are not set to a default, so can range check early.
+
+
+ if (start < 0 || this.length < start || this.length < end) {
+ throw new RangeError('Out of range index');
+ }
+
+ if (end <= start) {
+ return this;
+ }
+
+ start = start >>> 0;
+ end = end === undefined ? this.length : end >>> 0;
+ if (!val) val = 0;
+ var i;
+
+ if (typeof val === 'number') {
+ for (i = start; i < end; ++i) {
+ this[i] = val;
+ }
+ } else {
+ var bytes = internalIsBuffer$1(val) ? val : utf8ToBytes$1(new Buffer$1(val, encoding).toString());
+ var len = bytes.length;
+
+ for (i = 0; i < end - start; ++i) {
+ this[i + start] = bytes[i % len];
+ }
+ }
+
+ return this;
+ }; // HELPER FUNCTIONS
+ // ================
+
+
+ var INVALID_BASE64_RE$1 = /[^+\/0-9A-Za-z-_]/g;
+
+ function base64clean$1(str) {
+ // Node strips out invalid characters like \n and \t from the string, base64-js does not
+ str = stringtrim$1(str).replace(INVALID_BASE64_RE$1, ''); // Node converts strings with length < 2 to ''
+
+ if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
+
+ while (str.length % 4 !== 0) {
+ str = str + '=';
+ }
+
+ return str;
+ }
+
+ function stringtrim$1(str) {
+ if (str.trim) return str.trim();
+ return str.replace(/^\s+|\s+$/g, '');
+ }
+
+ function toHex$1(n) {
+ if (n < 16) return '0' + n.toString(16);
+ return n.toString(16);
+ }
+
+ function utf8ToBytes$1(string, units) {
+ units = units || Infinity;
+ var codePoint;
+ var length = string.length;
+ var leadSurrogate = null;
+ var bytes = [];
+
+ for (var i = 0; i < length; ++i) {
+ codePoint = string.charCodeAt(i); // is surrogate component
+
+ if (codePoint > 0xD7FF && codePoint < 0xE000) {
+ // last char was a lead
+ if (!leadSurrogate) {
+ // no lead yet
+ if (codePoint > 0xDBFF) {
+ // unexpected trail
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
+ continue;
+ } else if (i + 1 === length) {
+ // unpaired lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
+ continue;
+ } // valid lead
+
+
+ leadSurrogate = codePoint;
+ continue;
+ } // 2 leads in a row
+
+
+ if (codePoint < 0xDC00) {
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
+ leadSurrogate = codePoint;
+ continue;
+ } // valid surrogate pair
+
+
+ codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
+ } else if (leadSurrogate) {
+ // valid bmp char, but last char was a lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
+ }
+
+ leadSurrogate = null; // encode utf8
+
+ if (codePoint < 0x80) {
+ if ((units -= 1) < 0) break;
+ bytes.push(codePoint);
+ } else if (codePoint < 0x800) {
+ if ((units -= 2) < 0) break;
+ bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80);
+ } else if (codePoint < 0x10000) {
+ if ((units -= 3) < 0) break;
+ bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
+ } else if (codePoint < 0x110000) {
+ if ((units -= 4) < 0) break;
+ bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
+ } else {
+ throw new Error('Invalid code point');
+ }
+ }
+
+ return bytes;
+ }
+
+ function asciiToBytes$1(str) {
+ var byteArray = [];
+
+ for (var i = 0; i < str.length; ++i) {
+ // Node's code seems to be doing this and not & 0x7F..
+ byteArray.push(str.charCodeAt(i) & 0xFF);
+ }
+
+ return byteArray;
+ }
+
+ function utf16leToBytes$1(str, units) {
+ var c, hi, lo;
+ var byteArray = [];
+
+ for (var i = 0; i < str.length; ++i) {
+ if ((units -= 2) < 0) break;
+ c = str.charCodeAt(i);
+ hi = c >> 8;
+ lo = c % 256;
+ byteArray.push(lo);
+ byteArray.push(hi);
+ }
+
+ return byteArray;
+ }
+
+ function base64ToBytes$1(str) {
+ return toByteArray$1(base64clean$1(str));
+ }
+
+ function blitBuffer$1(src, dst, offset, length) {
+ for (var i = 0; i < length; ++i) {
+ if (i + offset >= dst.length || i >= src.length) break;
+ dst[i + offset] = src[i];
+ }
+
+ return i;
+ }
+
+ function isnan$1(val) {
+ return val !== val; // eslint-disable-line no-self-compare
+ } // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
+ // The _isBuffer check is for Safari 5-7 support, because it's missing
+ // Object.prototype.constructor. Remove this eventually
+
+
+ function isBuffer$2(obj) {
+ return obj != null && (!!obj._isBuffer || isFastBuffer$1(obj) || isSlowBuffer$1(obj));
+ }
+
+ function isFastBuffer$1(obj) {
+ return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj);
+ } // For Node v0.10 support. Remove this eventually.
+
+
+ function isSlowBuffer$1(obj) {
+ return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer$1(obj.slice(0, 0));
+ }
+
+ // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
+
+ function defaultSetTimout() {
+ throw new Error('setTimeout has not been defined');
+ }
+
+ function defaultClearTimeout() {
+ throw new Error('clearTimeout has not been defined');
+ }
+
+ var cachedSetTimeout = defaultSetTimout;
+ var cachedClearTimeout = defaultClearTimeout;
+
+ if (typeof global$1.setTimeout === 'function') {
+ cachedSetTimeout = setTimeout;
+ }
+
+ if (typeof global$1.clearTimeout === 'function') {
+ cachedClearTimeout = clearTimeout;
+ }
+
+ function runTimeout(fun) {
+ if (cachedSetTimeout === setTimeout) {
+ //normal enviroments in sane situations
+ return setTimeout(fun, 0);
+ } // if setTimeout wasn't available but was latter defined
+
+
+ if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
+ cachedSetTimeout = setTimeout;
+ return setTimeout(fun, 0);
+ }
+
+ try {
+ // when when somebody has screwed with setTimeout but no I.E. maddness
+ return cachedSetTimeout(fun, 0);
+ } catch (e) {
+ try {
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
+ return cachedSetTimeout.call(null, fun, 0);
+ } catch (e) {
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
+ return cachedSetTimeout.call(this, fun, 0);
+ }
+ }
+ }
+
+ function runClearTimeout(marker) {
+ if (cachedClearTimeout === clearTimeout) {
+ //normal enviroments in sane situations
+ return clearTimeout(marker);
+ } // if clearTimeout wasn't available but was latter defined
+
+
+ if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
+ cachedClearTimeout = clearTimeout;
+ return clearTimeout(marker);
+ }
+
+ try {
+ // when when somebody has screwed with setTimeout but no I.E. maddness
+ return cachedClearTimeout(marker);
+ } catch (e) {
+ try {
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
+ return cachedClearTimeout.call(null, marker);
+ } catch (e) {
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
+ // Some versions of I.E. have different rules for clearTimeout vs setTimeout
+ return cachedClearTimeout.call(this, marker);
+ }
+ }
+ }
+
+ var queue$1 = [];
+ var draining = false;
+ var currentQueue;
+ var queueIndex = -1;
+
+ function cleanUpNextTick() {
+ if (!draining || !currentQueue) {
+ return;
+ }
+
+ draining = false;
+
+ if (currentQueue.length) {
+ queue$1 = currentQueue.concat(queue$1);
+ } else {
+ queueIndex = -1;
+ }
+
+ if (queue$1.length) {
+ drainQueue();
+ }
+ }
+
+ function drainQueue() {
+ if (draining) {
+ return;
+ }
+
+ var timeout = runTimeout(cleanUpNextTick);
+ draining = true;
+ var len = queue$1.length;
+
+ while (len) {
+ currentQueue = queue$1;
+ queue$1 = [];
+
+ while (++queueIndex < len) {
+ if (currentQueue) {
+ currentQueue[queueIndex].run();
+ }
+ }
+
+ queueIndex = -1;
+ len = queue$1.length;
+ }
+
+ currentQueue = null;
+ draining = false;
+ runClearTimeout(timeout);
+ }
+
+ function nextTick(fun) {
+ var args = new Array(arguments.length - 1);
+
+ if (arguments.length > 1) {
+ for (var i = 1; i < arguments.length; i++) {
+ args[i - 1] = arguments[i];
+ }
+ }
+
+ queue$1.push(new Item(fun, args));
+
+ if (queue$1.length === 1 && !draining) {
+ runTimeout(drainQueue);
+ }
+ } // v8 likes predictible objects
+
+
+ function Item(fun, array) {
+ this.fun = fun;
+ this.array = array;
+ }
+
+ Item.prototype.run = function () {
+ this.fun.apply(null, this.array);
+ };
+
+ var title = 'browser';
+ var platform = 'browser';
+ var browser$3 = true;
+ var env = {};
+ var argv = [];
+ var version$1 = ''; // empty string to avoid regexp issues
+
+ var versions = {};
+ var release = {};
+ var config = {};
+
+ function noop() {}
+
+ var on = noop;
+ var addListener = noop;
+ var once = noop;
+ var off = noop;
+ var removeListener = noop;
+ var removeAllListeners = noop;
+ var emit = noop;
+
+ function binding(name) {
+ throw new Error('process.binding is not supported');
+ }
+
+ function cwd() {
+ return '/';
+ }
+
+ function chdir(dir) {
+ throw new Error('process.chdir is not supported');
+ }
+
+ function umask() {
+ return 0;
+ } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
+
+
+ var performance = global$1.performance || {};
+
+ var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () {
+ return new Date().getTime();
+ }; // generate timestamp or delta
+ // see http://nodejs.org/api/process.html#process_process_hrtime
+
+
+ function hrtime(previousTimestamp) {
+ var clocktime = performanceNow.call(performance) * 1e-3;
+ var seconds = Math.floor(clocktime);
+ var nanoseconds = Math.floor(clocktime % 1 * 1e9);
+
+ if (previousTimestamp) {
+ seconds = seconds - previousTimestamp[0];
+ nanoseconds = nanoseconds - previousTimestamp[1];
+
+ if (nanoseconds < 0) {
+ seconds--;
+ nanoseconds += 1e9;
+ }
+ }
+
+ return [seconds, nanoseconds];
+ }
+
+ var startTime = new Date();
+
+ function uptime() {
+ var currentTime = new Date();
+ var dif = currentTime - startTime;
+ return dif / 1000;
+ }
+
+ var browser$1$1 = {
+ nextTick: nextTick,
+ title: title,
+ browser: browser$3,
+ env: env,
+ argv: argv,
+ version: version$1,
+ versions: versions,
+ on: on,
+ addListener: addListener,
+ once: once,
+ off: off,
+ removeListener: removeListener,
+ removeAllListeners: removeAllListeners,
+ emit: emit,
+ binding: binding,
+ cwd: cwd,
+ chdir: chdir,
+ umask: umask,
+ hrtime: hrtime,
+ platform: platform,
+ release: release,
+ config: config,
+ uptime: uptime
+ };
+ var process$3 = browser$1$1;
+
+ var inherits$2;
+
+ if (typeof Object.create === 'function') {
+ inherits$2 = function inherits(ctor, superCtor) {
+ // implementation from standard node.js 'util' module
+ ctor.super_ = superCtor;
+ ctor.prototype = Object.create(superCtor.prototype, {
+ constructor: {
+ value: ctor,
+ enumerable: false,
+ writable: true,
+ configurable: true
+ }
+ });
+ };
+ } else {
+ inherits$2 = function inherits(ctor, superCtor) {
+ ctor.super_ = superCtor;
+
+ var TempCtor = function TempCtor() {};
+
+ TempCtor.prototype = superCtor.prototype;
+ ctor.prototype = new TempCtor();
+ ctor.prototype.constructor = ctor;
+ };
+ }
+
+ var inherits$3 = inherits$2;
+
+ var formatRegExp = /%[sdj%]/g;
+ function format$1(f) {
+ if (!isString$1(f)) {
+ var objects = [];
+
+ for (var i = 0; i < arguments.length; i++) {
+ objects.push(inspect(arguments[i]));
+ }
+
+ return objects.join(' ');
+ }
+
+ var i = 1;
+ var args = arguments;
+ var len = args.length;
+ var str = String(f).replace(formatRegExp, function (x) {
+ if (x === '%%') return '%';
+ if (i >= len) return x;
+
+ switch (x) {
+ case '%s':
+ return String(args[i++]);
+
+ case '%d':
+ return Number(args[i++]);
+
+ case '%j':
+ try {
+ return JSON.stringify(args[i++]);
+ } catch (_) {
+ return '[Circular]';
+ }
+
+ default:
+ return x;
+ }
+ });
+
+ for (var x = args[i]; i < len; x = args[++i]) {
+ if (isNull(x) || !isObject(x)) {
+ str += ' ' + x;
+ } else {
+ str += ' ' + inspect(x);
+ }
+ }
+
+ return str;
+ }
+ // Returns a modified function which warns once by default.
+ // If --no-deprecation is set, then it is a no-op.
+
+ function deprecate$1(fn, msg) {
+ // Allow for deprecating things in the process of starting up.
+ if (isUndefined(global$1.process)) {
+ return function () {
+ return deprecate$1(fn, msg).apply(this, arguments);
+ };
+ }
+
+ if (process$3.noDeprecation === true) {
+ return fn;
+ }
+
+ var warned = false;
+
+ function deprecated() {
+ if (!warned) {
+ if (process$3.throwDeprecation) {
+ throw new Error(msg);
+ } else if (process$3.traceDeprecation) {
+ console.trace(msg);
+ } else {
+ console.error(msg);
+ }
+
+ warned = true;
+ }
+
+ return fn.apply(this, arguments);
+ }
+
+ return deprecated;
+ }
+ var debugs = {};
+ var debugEnviron;
+ function debuglog(set) {
+ if (isUndefined(debugEnviron)) debugEnviron = process$3.env.NODE_DEBUG || '';
+ set = set.toUpperCase();
+
+ if (!debugs[set]) {
+ if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
+ var pid = 0;
+
+ debugs[set] = function () {
+ var msg = format$1.apply(null, arguments);
+ console.error('%s %d: %s', set, pid, msg);
+ };
+ } else {
+ debugs[set] = function () {};
+ }
+ }
+
+ return debugs[set];
+ }
+ /**
+ * Echos the value of a value. Trys to print the value out
+ * in the best way possible given the different types.
+ *
+ * @param {Object} obj The object to print out.
+ * @param {Object} opts Optional options object that alters the output.
+ */
+
+ /* legacy: obj, showHidden, depth, colors*/
+
+ function inspect(obj, opts) {
+ // default options
+ var ctx = {
+ seen: [],
+ stylize: stylizeNoColor
+ }; // legacy...
+
+ if (arguments.length >= 3) ctx.depth = arguments[2];
+ if (arguments.length >= 4) ctx.colors = arguments[3];
+
+ if (isBoolean(opts)) {
+ // legacy...
+ ctx.showHidden = opts;
+ } else if (opts) {
+ // got an "options" object
+ _extend(ctx, opts);
+ } // set default options
+
+
+ if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
+ if (isUndefined(ctx.depth)) ctx.depth = 2;
+ if (isUndefined(ctx.colors)) ctx.colors = false;
+ if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
+ if (ctx.colors) ctx.stylize = stylizeWithColor;
+ return formatValue(ctx, obj, ctx.depth);
+ } // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
+
+ inspect.colors = {
+ 'bold': [1, 22],
+ 'italic': [3, 23],
+ 'underline': [4, 24],
+ 'inverse': [7, 27],
+ 'white': [37, 39],
+ 'grey': [90, 39],
+ 'black': [30, 39],
+ 'blue': [34, 39],
+ 'cyan': [36, 39],
+ 'green': [32, 39],
+ 'magenta': [35, 39],
+ 'red': [31, 39],
+ 'yellow': [33, 39]
+ }; // Don't use 'blue' not visible on cmd.exe
+
+ inspect.styles = {
+ 'special': 'cyan',
+ 'number': 'yellow',
+ 'boolean': 'yellow',
+ 'undefined': 'grey',
+ 'null': 'bold',
+ 'string': 'green',
+ 'date': 'magenta',
+ // "name": intentionally not styling
+ 'regexp': 'red'
+ };
+
+ function stylizeWithColor(str, styleType) {
+ var style = inspect.styles[styleType];
+
+ if (style) {
+ return "\x1B[" + inspect.colors[style][0] + 'm' + str + "\x1B[" + inspect.colors[style][1] + 'm';
+ } else {
+ return str;
+ }
+ }
+
+ function stylizeNoColor(str, styleType) {
+ return str;
+ }
+
+ function arrayToHash(array) {
+ var hash = {};
+ array.forEach(function (val, idx) {
+ hash[val] = true;
+ });
+ return hash;
+ }
+
+ function formatValue(ctx, value, recurseTimes) {
+ // Provide a hook for user-specified inspect functions.
+ // Check that value is an object with an inspect function on it
+ if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special
+ value.inspect !== inspect && // Also filter out any prototype objects using the circular check.
+ !(value.constructor && value.constructor.prototype === value)) {
+ var ret = value.inspect(recurseTimes, ctx);
+
+ if (!isString$1(ret)) {
+ ret = formatValue(ctx, ret, recurseTimes);
+ }
+
+ return ret;
+ } // Primitive types cannot have properties
+
+
+ var primitive = formatPrimitive(ctx, value);
+
+ if (primitive) {
+ return primitive;
+ } // Look up the keys of the object.
+
+
+ var keys = Object.keys(value);
+ var visibleKeys = arrayToHash(keys);
+
+ if (ctx.showHidden) {
+ keys = Object.getOwnPropertyNames(value);
+ } // IE doesn't make error fields non-enumerable
+ // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
+
+
+ if (isError$1(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
+ return formatError(value);
+ } // Some type of object without properties can be shortcutted.
+
+
+ if (keys.length === 0) {
+ if (isFunction(value)) {
+ var name = value.name ? ': ' + value.name : '';
+ return ctx.stylize('[Function' + name + ']', 'special');
+ }
+
+ if (isRegExp(value)) {
+ return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
+ }
+
+ if (isDate(value)) {
+ return ctx.stylize(Date.prototype.toString.call(value), 'date');
+ }
+
+ if (isError$1(value)) {
+ return formatError(value);
+ }
+ }
+
+ var base = '',
+ array = false,
+ braces = ['{', '}']; // Make Array say that they are Array
+
+ if (isArray$1(value)) {
+ array = true;
+ braces = ['[', ']'];
+ } // Make functions say that they are functions
+
+
+ if (isFunction(value)) {
+ var n = value.name ? ': ' + value.name : '';
+ base = ' [Function' + n + ']';
+ } // Make RegExps say that they are RegExps
+
+
+ if (isRegExp(value)) {
+ base = ' ' + RegExp.prototype.toString.call(value);
+ } // Make dates with properties first say the date
+
+
+ if (isDate(value)) {
+ base = ' ' + Date.prototype.toUTCString.call(value);
+ } // Make error with message first say the error
+
+
+ if (isError$1(value)) {
+ base = ' ' + formatError(value);
+ }
+
+ if (keys.length === 0 && (!array || value.length == 0)) {
+ return braces[0] + base + braces[1];
+ }
+
+ if (recurseTimes < 0) {
+ if (isRegExp(value)) {
+ return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
+ } else {
+ return ctx.stylize('[Object]', 'special');
+ }
+ }
+
+ ctx.seen.push(value);
+ var output;
+
+ if (array) {
+ output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
+ } else {
+ output = keys.map(function (key) {
+ return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
+ });
+ }
+
+ ctx.seen.pop();
+ return reduceToSingleString(output, base, braces);
+ }
+
+ function formatPrimitive(ctx, value) {
+ if (isUndefined(value)) return ctx.stylize('undefined', 'undefined');
+
+ if (isString$1(value)) {
+ var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\'';
+ return ctx.stylize(simple, 'string');
+ }
+
+ if (isNumber(value)) return ctx.stylize('' + value, 'number');
+ if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here.
+
+ if (isNull(value)) return ctx.stylize('null', 'null');
+ }
+
+ function formatError(value) {
+ return '[' + Error.prototype.toString.call(value) + ']';
+ }
+
+ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
+ var output = [];
+
+ for (var i = 0, l = value.length; i < l; ++i) {
+ if (hasOwnProperty(value, String(i))) {
+ output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
+ } else {
+ output.push('');
+ }
+ }
+
+ keys.forEach(function (key) {
+ if (!key.match(/^\d+$/)) {
+ output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
+ }
+ });
+ return output;
+ }
+
+ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
+ var name, str, desc;
+ desc = Object.getOwnPropertyDescriptor(value, key) || {
+ value: value[key]
+ };
+
+ if (desc.get) {
+ if (desc.set) {
+ str = ctx.stylize('[Getter/Setter]', 'special');
+ } else {
+ str = ctx.stylize('[Getter]', 'special');
+ }
+ } else {
+ if (desc.set) {
+ str = ctx.stylize('[Setter]', 'special');
+ }
+ }
+
+ if (!hasOwnProperty(visibleKeys, key)) {
+ name = '[' + key + ']';
+ }
+
+ if (!str) {
+ if (ctx.seen.indexOf(desc.value) < 0) {
+ if (isNull(recurseTimes)) {
+ str = formatValue(ctx, desc.value, null);
+ } else {
+ str = formatValue(ctx, desc.value, recurseTimes - 1);
+ }
+
+ if (str.indexOf('\n') > -1) {
+ if (array) {
+ str = str.split('\n').map(function (line) {
+ return ' ' + line;
+ }).join('\n').substr(2);
+ } else {
+ str = '\n' + str.split('\n').map(function (line) {
+ return ' ' + line;
+ }).join('\n');
+ }
+ }
+ } else {
+ str = ctx.stylize('[Circular]', 'special');
+ }
+ }
+
+ if (isUndefined(name)) {
+ if (array && key.match(/^\d+$/)) {
+ return str;
+ }
+
+ name = JSON.stringify('' + key);
+
+ if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
+ name = name.substr(1, name.length - 2);
+ name = ctx.stylize(name, 'name');
+ } else {
+ name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
+ name = ctx.stylize(name, 'string');
+ }
+ }
+
+ return name + ': ' + str;
+ }
+
+ function reduceToSingleString(output, base, braces) {
+ var length = output.reduce(function (prev, cur) {
+ if (cur.indexOf('\n') >= 0) ;
+ return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
+ }, 0);
+
+ if (length > 60) {
+ return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1];
+ }
+
+ return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
+ } // NOTE: These type checking functions intentionally don't use `instanceof`
+ // because it is fragile and can be easily faked with `Object.create()`.
+
+
+ function isArray$1(ar) {
+ return Array.isArray(ar);
+ }
+ function isBoolean(arg) {
+ return typeof arg === 'boolean';
+ }
+ function isNull(arg) {
+ return arg === null;
+ }
+ function isNullOrUndefined(arg) {
+ return arg == null;
+ }
+ function isNumber(arg) {
+ return typeof arg === 'number';
+ }
+ function isString$1(arg) {
+ return typeof arg === 'string';
+ }
+ function isSymbol(arg) {
+ return _typeof(arg) === 'symbol';
+ }
+ function isUndefined(arg) {
+ return arg === void 0;
+ }
+ function isRegExp(re) {
+ return isObject(re) && objectToString(re) === '[object RegExp]';
+ }
+ function isObject(arg) {
+ return _typeof(arg) === 'object' && arg !== null;
+ }
+ function isDate(d) {
+ return isObject(d) && objectToString(d) === '[object Date]';
+ }
+ function isError$1(e) {
+ return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error);
+ }
+ function isFunction(arg) {
+ return typeof arg === 'function';
+ }
+ function isPrimitive(arg) {
+ return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || _typeof(arg) === 'symbol' || // ES6 symbol
+ typeof arg === 'undefined';
+ }
+ function isBuffer$1(maybeBuf) {
+ return isBuffer$2(maybeBuf);
+ }
+
+ function objectToString(o) {
+ return Object.prototype.toString.call(o);
+ }
+
+ function pad(n) {
+ return n < 10 ? '0' + n.toString(10) : n.toString(10);
+ }
+
+ var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34
+
+ function timestamp() {
+ var d = new Date();
+ var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':');
+ return [d.getDate(), months[d.getMonth()], time].join(' ');
+ } // log is just a thin wrapper to console.log that prepends a timestamp
+
+
+ function log$1() {
+ console.log('%s - %s', timestamp(), format$1.apply(null, arguments));
+ }
+ function _extend(origin, add) {
+ // Don't do anything if add isn't an object
+ if (!add || !isObject(add)) return origin;
+ var keys = Object.keys(add);
+ var i = keys.length;
+
+ while (i--) {
+ origin[keys[i]] = add[keys[i]];
+ }
+
+ return origin;
+ }
+
+ function hasOwnProperty(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
+ }
+
+ var util = {
+ inherits: inherits$3,
+ _extend: _extend,
+ log: log$1,
+ isBuffer: isBuffer$1,
+ isPrimitive: isPrimitive,
+ isFunction: isFunction,
+ isError: isError$1,
+ isDate: isDate,
+ isObject: isObject,
+ isRegExp: isRegExp,
+ isUndefined: isUndefined,
+ isSymbol: isSymbol,
+ isString: isString$1,
+ isNumber: isNumber,
+ isNullOrUndefined: isNullOrUndefined,
+ isNull: isNull,
+ isBoolean: isBoolean,
+ isArray: isArray$1,
+ inspect: inspect,
+ deprecate: deprecate$1,
+ format: format$1,
+ debuglog: debuglog
+ };
+
+ var lookup = [];
+ var revLookup = [];
+ var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
+ var inited = false;
+
+ function init() {
+ inited = true;
+ var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
+
+ for (var i = 0, len = code.length; i < len; ++i) {
+ lookup[i] = code[i];
+ revLookup[code.charCodeAt(i)] = i;
+ }
+
+ revLookup['-'.charCodeAt(0)] = 62;
+ revLookup['_'.charCodeAt(0)] = 63;
+ }
+
+ function toByteArray(b64) {
+ if (!inited) {
+ init();
+ }
+
+ var i, j, l, tmp, placeHolders, arr;
+ var len = b64.length;
+
+ if (len % 4 > 0) {
+ throw new Error('Invalid string. Length must be a multiple of 4');
+ } // the number of equal signs (place holders)
+ // if there are two placeholders, than the two characters before it
+ // represent one byte
+ // if there is only one, then the three characters before it represent 2 bytes
+ // this is just a cheap hack to not do indexOf twice
+
+
+ placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; // base64 is 4/3 + up to two characters of the original data
+
+ arr = new Arr(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars
+
+ l = placeHolders > 0 ? len - 4 : len;
+ var L = 0;
+
+ for (i = 0, j = 0; i < l; i += 4, j += 3) {
+ tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
+ arr[L++] = tmp >> 16 & 0xFF;
+ arr[L++] = tmp >> 8 & 0xFF;
+ arr[L++] = tmp & 0xFF;
+ }
+
+ if (placeHolders === 2) {
+ tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
+ arr[L++] = tmp & 0xFF;
+ } else if (placeHolders === 1) {
+ tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
+ arr[L++] = tmp >> 8 & 0xFF;
+ arr[L++] = tmp & 0xFF;
+ }
+
+ return arr;
+ }
+
+ function tripletToBase64(num) {
+ return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
+ }
+
+ function encodeChunk(uint8, start, end) {
+ var tmp;
+ var output = [];
+
+ for (var i = start; i < end; i += 3) {
+ tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2];
+ output.push(tripletToBase64(tmp));
+ }
+
+ return output.join('');
+ }
+
+ function fromByteArray(uint8) {
+ if (!inited) {
+ init();
+ }
+
+ var tmp;
+ var len = uint8.length;
+ var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
+
+ var output = '';
+ var parts = [];
+ var maxChunkLength = 16383; // must be multiple of 3
+ // go through the array every three bytes, we'll deal with trailing stuff later
+
+ for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
+ parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
+ } // pad the end with zeros, but make sure to not forget the extra bytes
+
+
+ if (extraBytes === 1) {
+ tmp = uint8[len - 1];
+ output += lookup[tmp >> 2];
+ output += lookup[tmp << 4 & 0x3F];
+ output += '==';
+ } else if (extraBytes === 2) {
+ tmp = (uint8[len - 2] << 8) + uint8[len - 1];
+ output += lookup[tmp >> 10];
+ output += lookup[tmp >> 4 & 0x3F];
+ output += lookup[tmp << 2 & 0x3F];
+ output += '=';
+ }
+
+ parts.push(output);
+ return parts.join('');
+ }
+
+ function read(buffer, offset, isLE, mLen, nBytes) {
+ var e, m;
+ var eLen = nBytes * 8 - mLen - 1;
+ var eMax = (1 << eLen) - 1;
+ var eBias = eMax >> 1;
+ var nBits = -7;
+ var i = isLE ? nBytes - 1 : 0;
+ var d = isLE ? -1 : 1;
+ var s = buffer[offset + i];
+ i += d;
+ e = s & (1 << -nBits) - 1;
+ s >>= -nBits;
+ nBits += eLen;
+
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+
+ m = e & (1 << -nBits) - 1;
+ e >>= -nBits;
+ nBits += mLen;
+
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+
+ if (e === 0) {
+ e = 1 - eBias;
+ } else if (e === eMax) {
+ return m ? NaN : (s ? -1 : 1) * Infinity;
+ } else {
+ m = m + Math.pow(2, mLen);
+ e = e - eBias;
+ }
+
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
+ }
+
+ function write(buffer, value, offset, isLE, mLen, nBytes) {
+ var e, m, c;
+ var eLen = nBytes * 8 - mLen - 1;
+ var eMax = (1 << eLen) - 1;
+ var eBias = eMax >> 1;
+ var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
+ var i = isLE ? 0 : nBytes - 1;
+ var d = isLE ? 1 : -1;
+ var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
+ value = Math.abs(value);
+
+ if (isNaN(value) || value === Infinity) {
+ m = isNaN(value) ? 1 : 0;
+ e = eMax;
+ } else {
+ e = Math.floor(Math.log(value) / Math.LN2);
+
+ if (value * (c = Math.pow(2, -e)) < 1) {
+ e--;
+ c *= 2;
+ }
+
+ if (e + eBias >= 1) {
+ value += rt / c;
+ } else {
+ value += rt * Math.pow(2, 1 - eBias);
+ }
+
+ if (value * c >= 2) {
+ e++;
+ c /= 2;
+ }
+
+ if (e + eBias >= eMax) {
+ m = 0;
+ e = eMax;
+ } else if (e + eBias >= 1) {
+ m = (value * c - 1) * Math.pow(2, mLen);
+ e = e + eBias;
+ } else {
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
+ e = 0;
+ }
+ }
+
+ for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
+
+ e = e << mLen | m;
+ eLen += mLen;
+
+ for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
+
+ buffer[offset + i - d] |= s * 128;
+ }
+
+ var toString$1 = {}.toString;
+
+ var isArray = Array.isArray || function (arr) {
+ return toString$1.call(arr) == '[object Array]';
+ };
+ /*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author Feross Aboukhadijeh
+ * @license MIT
+ */
+
+
+ var INSPECT_MAX_BYTES = 50;
+ /**
+ * If `Buffer.TYPED_ARRAY_SUPPORT`:
+ * === true Use Uint8Array implementation (fastest)
+ * === false Use Object implementation (most compatible, even IE6)
+ *
+ * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
+ * Opera 11.6+, iOS 4.2+.
+ *
+ * Due to various browser bugs, sometimes the Object implementation will be used even
+ * when the browser supports typed arrays.
+ *
+ * Note:
+ *
+ * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
+ * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
+ *
+ * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
+ *
+ * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
+ * incorrect length in some situations.
+
+ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
+ * get the Object implementation, which is slower but behaves correctly.
+ */
+
+ Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true;
+
+ function kMaxLength() {
+ return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff;
+ }
+
+ function createBuffer(that, length) {
+ if (kMaxLength() < length) {
+ throw new RangeError('Invalid typed array length');
+ }
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ // Return an augmented `Uint8Array` instance, for best performance
+ that = new Uint8Array(length);
+ that.__proto__ = Buffer.prototype;
+ } else {
+ // Fallback: Return an object instance of the Buffer class
+ if (that === null) {
+ that = new Buffer(length);
+ }
+
+ that.length = length;
+ }
+
+ return that;
+ }
+ /**
+ * The Buffer constructor returns instances of `Uint8Array` that have their
+ * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
+ * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
+ * and the `Uint8Array` methods. Square bracket notation works as expected -- it
+ * returns a single octet.
+ *
+ * The `Uint8Array` prototype remains unmodified.
+ */
+
+
+ function Buffer(arg, encodingOrOffset, length) {
+ if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
+ return new Buffer(arg, encodingOrOffset, length);
+ } // Common case.
+
+
+ if (typeof arg === 'number') {
+ if (typeof encodingOrOffset === 'string') {
+ throw new Error('If encoding is specified then the first argument must be a string');
+ }
+
+ return allocUnsafe(this, arg);
+ }
+
+ return from(this, arg, encodingOrOffset, length);
+ }
+
+ Buffer.poolSize = 8192; // not used by this implementation
+ // TODO: Legacy, not needed anymore. Remove in next major version.
+
+ Buffer._augment = function (arr) {
+ arr.__proto__ = Buffer.prototype;
+ return arr;
+ };
+
+ function from(that, value, encodingOrOffset, length) {
+ if (typeof value === 'number') {
+ throw new TypeError('"value" argument must not be a number');
+ }
+
+ if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
+ return fromArrayBuffer(that, value, encodingOrOffset, length);
+ }
+
+ if (typeof value === 'string') {
+ return fromString(that, value, encodingOrOffset);
+ }
+
+ return fromObject(that, value);
+ }
+ /**
+ * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
+ * if value is a number.
+ * Buffer.from(str[, encoding])
+ * Buffer.from(array)
+ * Buffer.from(buffer)
+ * Buffer.from(arrayBuffer[, byteOffset[, length]])
+ **/
+
+
+ Buffer.from = function (value, encodingOrOffset, length) {
+ return from(null, value, encodingOrOffset, length);
+ };
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ Buffer.prototype.__proto__ = Uint8Array.prototype;
+ Buffer.__proto__ = Uint8Array;
+ }
+
+ function assertSize(size) {
+ if (typeof size !== 'number') {
+ throw new TypeError('"size" argument must be a number');
+ } else if (size < 0) {
+ throw new RangeError('"size" argument must not be negative');
+ }
+ }
+
+ function alloc(that, size, fill, encoding) {
+ assertSize(size);
+
+ if (size <= 0) {
+ return createBuffer(that, size);
+ }
+
+ if (fill !== undefined) {
+ // Only pay attention to encoding if it's a string. This
+ // prevents accidentally sending in a number that would
+ // be interpretted as a start offset.
+ return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill);
+ }
+
+ return createBuffer(that, size);
+ }
+ /**
+ * Creates a new filled Buffer instance.
+ * alloc(size[, fill[, encoding]])
+ **/
+
+
+ Buffer.alloc = function (size, fill, encoding) {
+ return alloc(null, size, fill, encoding);
+ };
+
+ function allocUnsafe(that, size) {
+ assertSize(size);
+ that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
+
+ if (!Buffer.TYPED_ARRAY_SUPPORT) {
+ for (var i = 0; i < size; ++i) {
+ that[i] = 0;
+ }
+ }
+
+ return that;
+ }
+ /**
+ * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
+ * */
+
+
+ Buffer.allocUnsafe = function (size) {
+ return allocUnsafe(null, size);
+ };
+ /**
+ * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
+ */
+
+
+ Buffer.allocUnsafeSlow = function (size) {
+ return allocUnsafe(null, size);
+ };
+
+ function fromString(that, string, encoding) {
+ if (typeof encoding !== 'string' || encoding === '') {
+ encoding = 'utf8';
+ }
+
+ if (!Buffer.isEncoding(encoding)) {
+ throw new TypeError('"encoding" must be a valid string encoding');
+ }
+
+ var length = byteLength(string, encoding) | 0;
+ that = createBuffer(that, length);
+ var actual = that.write(string, encoding);
+
+ if (actual !== length) {
+ // Writing a hex string, for example, that contains invalid characters will
+ // cause everything after the first invalid character to be ignored. (e.g.
+ // 'abxxcd' will be treated as 'ab')
+ that = that.slice(0, actual);
+ }
+
+ return that;
+ }
+
+ function fromArrayLike(that, array) {
+ var length = array.length < 0 ? 0 : checked(array.length) | 0;
+ that = createBuffer(that, length);
+
+ for (var i = 0; i < length; i += 1) {
+ that[i] = array[i] & 255;
+ }
+
+ return that;
+ }
+
+ function fromArrayBuffer(that, array, byteOffset, length) {
+ array.byteLength; // this throws if `array` is not a valid ArrayBuffer
+
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
+ throw new RangeError('\'offset\' is out of bounds');
+ }
+
+ if (array.byteLength < byteOffset + (length || 0)) {
+ throw new RangeError('\'length\' is out of bounds');
+ }
+
+ if (byteOffset === undefined && length === undefined) {
+ array = new Uint8Array(array);
+ } else if (length === undefined) {
+ array = new Uint8Array(array, byteOffset);
+ } else {
+ array = new Uint8Array(array, byteOffset, length);
+ }
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ // Return an augmented `Uint8Array` instance, for best performance
+ that = array;
+ that.__proto__ = Buffer.prototype;
+ } else {
+ // Fallback: Return an object instance of the Buffer class
+ that = fromArrayLike(that, array);
+ }
+
+ return that;
+ }
+
+ function fromObject(that, obj) {
+ if (internalIsBuffer(obj)) {
+ var len = checked(obj.length) | 0;
+ that = createBuffer(that, len);
+
+ if (that.length === 0) {
+ return that;
+ }
+
+ obj.copy(that, 0, 0, len);
+ return that;
+ }
+
+ if (obj) {
+ if (typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer || 'length' in obj) {
+ if (typeof obj.length !== 'number' || isnan(obj.length)) {
+ return createBuffer(that, 0);
+ }
+
+ return fromArrayLike(that, obj);
+ }
+
+ if (obj.type === 'Buffer' && isArray(obj.data)) {
+ return fromArrayLike(that, obj.data);
+ }
+ }
+
+ throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.');
+ }
+
+ function checked(length) {
+ // Note: cannot use `length < kMaxLength()` here because that fails when
+ // length is NaN (which is otherwise coerced to zero.)
+ if (length >= kMaxLength()) {
+ throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes');
+ }
+
+ return length | 0;
+ }
+
+ Buffer.isBuffer = isBuffer;
+
+ function internalIsBuffer(b) {
+ return !!(b != null && b._isBuffer);
+ }
+
+ Buffer.compare = function compare(a, b) {
+ if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
+ throw new TypeError('Arguments must be Buffers');
+ }
+
+ if (a === b) return 0;
+ var x = a.length;
+ var y = b.length;
+
+ for (var i = 0, len = Math.min(x, y); i < len; ++i) {
+ if (a[i] !== b[i]) {
+ x = a[i];
+ y = b[i];
+ break;
+ }
+ }
+
+ if (x < y) return -1;
+ if (y < x) return 1;
+ return 0;
+ };
+
+ Buffer.isEncoding = function isEncoding(encoding) {
+ switch (String(encoding).toLowerCase()) {
+ case 'hex':
+ case 'utf8':
+ case 'utf-8':
+ case 'ascii':
+ case 'latin1':
+ case 'binary':
+ case 'base64':
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return true;
+
+ default:
+ return false;
+ }
+ };
+
+ Buffer.concat = function concat(list, length) {
+ if (!isArray(list)) {
+ throw new TypeError('"list" argument must be an Array of Buffers');
+ }
+
+ if (list.length === 0) {
+ return Buffer.alloc(0);
+ }
+
+ var i;
+
+ if (length === undefined) {
+ length = 0;
+
+ for (i = 0; i < list.length; ++i) {
+ length += list[i].length;
+ }
+ }
+
+ var buffer = Buffer.allocUnsafe(length);
+ var pos = 0;
+
+ for (i = 0; i < list.length; ++i) {
+ var buf = list[i];
+
+ if (!internalIsBuffer(buf)) {
+ throw new TypeError('"list" argument must be an Array of Buffers');
+ }
+
+ buf.copy(buffer, pos);
+ pos += buf.length;
+ }
+
+ return buffer;
+ };
+
+ function byteLength(string, encoding) {
+ if (internalIsBuffer(string)) {
+ return string.length;
+ }
+
+ if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
+ return string.byteLength;
+ }
+
+ if (typeof string !== 'string') {
+ string = '' + string;
+ }
+
+ var len = string.length;
+ if (len === 0) return 0; // Use a for loop to avoid recursion
+
+ var loweredCase = false;
+
+ for (;;) {
+ switch (encoding) {
+ case 'ascii':
+ case 'latin1':
+ case 'binary':
+ return len;
+
+ case 'utf8':
+ case 'utf-8':
+ case undefined:
+ return utf8ToBytes(string).length;
+
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return len * 2;
+
+ case 'hex':
+ return len >>> 1;
+
+ case 'base64':
+ return base64ToBytes(string).length;
+
+ default:
+ if (loweredCase) return utf8ToBytes(string).length; // assume utf8
+
+ encoding = ('' + encoding).toLowerCase();
+ loweredCase = true;
+ }
+ }
+ }
+
+ Buffer.byteLength = byteLength;
+
+ function slowToString(encoding, start, end) {
+ var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
+ // property of a typed array.
+ // This behaves neither like String nor Uint8Array in that we set start/end
+ // to their upper/lower bounds if the value passed is out of range.
+ // undefined is handled specially as per ECMA-262 6th Edition,
+ // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
+
+ if (start === undefined || start < 0) {
+ start = 0;
+ } // Return early if start > this.length. Done here to prevent potential uint32
+ // coercion fail below.
+
+
+ if (start > this.length) {
+ return '';
+ }
+
+ if (end === undefined || end > this.length) {
+ end = this.length;
+ }
+
+ if (end <= 0) {
+ return '';
+ } // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
+
+
+ end >>>= 0;
+ start >>>= 0;
+
+ if (end <= start) {
+ return '';
+ }
+
+ if (!encoding) encoding = 'utf8';
+
+ while (true) {
+ switch (encoding) {
+ case 'hex':
+ return hexSlice(this, start, end);
+
+ case 'utf8':
+ case 'utf-8':
+ return utf8Slice(this, start, end);
+
+ case 'ascii':
+ return asciiSlice(this, start, end);
+
+ case 'latin1':
+ case 'binary':
+ return latin1Slice(this, start, end);
+
+ case 'base64':
+ return base64Slice(this, start, end);
+
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return utf16leSlice(this, start, end);
+
+ default:
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
+ encoding = (encoding + '').toLowerCase();
+ loweredCase = true;
+ }
+ }
+ } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
+ // Buffer instances.
+
+
+ Buffer.prototype._isBuffer = true;
+
+ function swap(b, n, m) {
+ var i = b[n];
+ b[n] = b[m];
+ b[m] = i;
+ }
+
+ Buffer.prototype.swap16 = function swap16() {
+ var len = this.length;
+
+ if (len % 2 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 16-bits');
+ }
+
+ for (var i = 0; i < len; i += 2) {
+ swap(this, i, i + 1);
+ }
+
+ return this;
+ };
+
+ Buffer.prototype.swap32 = function swap32() {
+ var len = this.length;
+
+ if (len % 4 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 32-bits');
+ }
+
+ for (var i = 0; i < len; i += 4) {
+ swap(this, i, i + 3);
+ swap(this, i + 1, i + 2);
+ }
+
+ return this;
+ };
+
+ Buffer.prototype.swap64 = function swap64() {
+ var len = this.length;
+
+ if (len % 8 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 64-bits');
+ }
+
+ for (var i = 0; i < len; i += 8) {
+ swap(this, i, i + 7);
+ swap(this, i + 1, i + 6);
+ swap(this, i + 2, i + 5);
+ swap(this, i + 3, i + 4);
+ }
+
+ return this;
+ };
+
+ Buffer.prototype.toString = function toString() {
+ var length = this.length | 0;
+ if (length === 0) return '';
+ if (arguments.length === 0) return utf8Slice(this, 0, length);
+ return slowToString.apply(this, arguments);
+ };
+
+ Buffer.prototype.equals = function equals(b) {
+ if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer');
+ if (this === b) return true;
+ return Buffer.compare(this, b) === 0;
+ };
+
+ Buffer.prototype.inspect = function inspect() {
+ var str = '';
+ var max = INSPECT_MAX_BYTES;
+
+ if (this.length > 0) {
+ str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
+ if (this.length > max) str += ' ... ';
+ }
+
+ return '';
+ };
+
+ Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
+ if (!internalIsBuffer(target)) {
+ throw new TypeError('Argument must be a Buffer');
+ }
+
+ if (start === undefined) {
+ start = 0;
+ }
+
+ if (end === undefined) {
+ end = target ? target.length : 0;
+ }
+
+ if (thisStart === undefined) {
+ thisStart = 0;
+ }
+
+ if (thisEnd === undefined) {
+ thisEnd = this.length;
+ }
+
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
+ throw new RangeError('out of range index');
+ }
+
+ if (thisStart >= thisEnd && start >= end) {
+ return 0;
+ }
+
+ if (thisStart >= thisEnd) {
+ return -1;
+ }
+
+ if (start >= end) {
+ return 1;
+ }
+
+ start >>>= 0;
+ end >>>= 0;
+ thisStart >>>= 0;
+ thisEnd >>>= 0;
+ if (this === target) return 0;
+ var x = thisEnd - thisStart;
+ var y = end - start;
+ var len = Math.min(x, y);
+ var thisCopy = this.slice(thisStart, thisEnd);
+ var targetCopy = target.slice(start, end);
+
+ for (var i = 0; i < len; ++i) {
+ if (thisCopy[i] !== targetCopy[i]) {
+ x = thisCopy[i];
+ y = targetCopy[i];
+ break;
+ }
+ }
+
+ if (x < y) return -1;
+ if (y < x) return 1;
+ return 0;
+ }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
+ // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
+ //
+ // Arguments:
+ // - buffer - a Buffer to search
+ // - val - a string, Buffer, or number
+ // - byteOffset - an index into `buffer`; will be clamped to an int32
+ // - encoding - an optional encoding, relevant is val is a string
+ // - dir - true for indexOf, false for lastIndexOf
+
+
+ function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
+ // Empty buffer means no match
+ if (buffer.length === 0) return -1; // Normalize byteOffset
+
+ if (typeof byteOffset === 'string') {
+ encoding = byteOffset;
+ byteOffset = 0;
+ } else if (byteOffset > 0x7fffffff) {
+ byteOffset = 0x7fffffff;
+ } else if (byteOffset < -0x80000000) {
+ byteOffset = -0x80000000;
+ }
+
+ byteOffset = +byteOffset; // Coerce to Number.
+
+ if (isNaN(byteOffset)) {
+ // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
+ byteOffset = dir ? 0 : buffer.length - 1;
+ } // Normalize byteOffset: negative offsets start from the end of the buffer
+
+
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
+
+ if (byteOffset >= buffer.length) {
+ if (dir) return -1;else byteOffset = buffer.length - 1;
+ } else if (byteOffset < 0) {
+ if (dir) byteOffset = 0;else return -1;
+ } // Normalize val
+
+
+ if (typeof val === 'string') {
+ val = Buffer.from(val, encoding);
+ } // Finally, search either indexOf (if dir is true) or lastIndexOf
+
+
+ if (internalIsBuffer(val)) {
+ // Special case: looking for empty string/buffer always fails
+ if (val.length === 0) {
+ return -1;
+ }
+
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
+ } else if (typeof val === 'number') {
+ val = val & 0xFF; // Search for a byte value [0-255]
+
+ if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') {
+ if (dir) {
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
+ } else {
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
+ }
+ }
+
+ return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
+ }
+
+ throw new TypeError('val must be string, number or Buffer');
+ }
+
+ function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
+ var indexSize = 1;
+ var arrLength = arr.length;
+ var valLength = val.length;
+
+ if (encoding !== undefined) {
+ encoding = String(encoding).toLowerCase();
+
+ if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') {
+ if (arr.length < 2 || val.length < 2) {
+ return -1;
+ }
+
+ indexSize = 2;
+ arrLength /= 2;
+ valLength /= 2;
+ byteOffset /= 2;
+ }
+ }
+
+ function read(buf, i) {
+ if (indexSize === 1) {
+ return buf[i];
+ } else {
+ return buf.readUInt16BE(i * indexSize);
+ }
+ }
+
+ var i;
+
+ if (dir) {
+ var foundIndex = -1;
+
+ for (i = byteOffset; i < arrLength; i++) {
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
+ if (foundIndex === -1) foundIndex = i;
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
+ } else {
+ if (foundIndex !== -1) i -= i - foundIndex;
+ foundIndex = -1;
+ }
+ }
+ } else {
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
+
+ for (i = byteOffset; i >= 0; i--) {
+ var found = true;
+
+ for (var j = 0; j < valLength; j++) {
+ if (read(arr, i + j) !== read(val, j)) {
+ found = false;
+ break;
+ }
+ }
+
+ if (found) return i;
+ }
+ }
+
+ return -1;
+ }
+
+ Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
+ return this.indexOf(val, byteOffset, encoding) !== -1;
+ };
+
+ Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
+ };
+
+ Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
+ };
+
+ function hexWrite(buf, string, offset, length) {
+ offset = Number(offset) || 0;
+ var remaining = buf.length - offset;
+
+ if (!length) {
+ length = remaining;
+ } else {
+ length = Number(length);
+
+ if (length > remaining) {
+ length = remaining;
+ }
+ } // must be an even number of digits
+
+
+ var strLen = string.length;
+ if (strLen % 2 !== 0) throw new TypeError('Invalid hex string');
+
+ if (length > strLen / 2) {
+ length = strLen / 2;
+ }
+
+ for (var i = 0; i < length; ++i) {
+ var parsed = parseInt(string.substr(i * 2, 2), 16);
+ if (isNaN(parsed)) return i;
+ buf[offset + i] = parsed;
+ }
+
+ return i;
+ }
+
+ function utf8Write(buf, string, offset, length) {
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
+ }
+
+ function asciiWrite(buf, string, offset, length) {
+ return blitBuffer(asciiToBytes(string), buf, offset, length);
+ }
+
+ function latin1Write(buf, string, offset, length) {
+ return asciiWrite(buf, string, offset, length);
+ }
+
+ function base64Write(buf, string, offset, length) {
+ return blitBuffer(base64ToBytes(string), buf, offset, length);
+ }
+
+ function ucs2Write(buf, string, offset, length) {
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
+ }
+
+ Buffer.prototype.write = function write(string, offset, length, encoding) {
+ // Buffer#write(string)
+ if (offset === undefined) {
+ encoding = 'utf8';
+ length = this.length;
+ offset = 0; // Buffer#write(string, encoding)
+ } else if (length === undefined && typeof offset === 'string') {
+ encoding = offset;
+ length = this.length;
+ offset = 0; // Buffer#write(string, offset[, length][, encoding])
+ } else if (isFinite(offset)) {
+ offset = offset | 0;
+
+ if (isFinite(length)) {
+ length = length | 0;
+ if (encoding === undefined) encoding = 'utf8';
+ } else {
+ encoding = length;
+ length = undefined;
+ } // legacy write(string, encoding, offset, length) - remove in v0.13
+
+ } else {
+ throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported');
+ }
+
+ var remaining = this.length - offset;
+ if (length === undefined || length > remaining) length = remaining;
+
+ if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
+ throw new RangeError('Attempt to write outside buffer bounds');
+ }
+
+ if (!encoding) encoding = 'utf8';
+ var loweredCase = false;
+
+ for (;;) {
+ switch (encoding) {
+ case 'hex':
+ return hexWrite(this, string, offset, length);
+
+ case 'utf8':
+ case 'utf-8':
+ return utf8Write(this, string, offset, length);
+
+ case 'ascii':
+ return asciiWrite(this, string, offset, length);
+
+ case 'latin1':
+ case 'binary':
+ return latin1Write(this, string, offset, length);
+
+ case 'base64':
+ // Warning: maxLength not taken into account in base64Write
+ return base64Write(this, string, offset, length);
+
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return ucs2Write(this, string, offset, length);
+
+ default:
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
+ encoding = ('' + encoding).toLowerCase();
+ loweredCase = true;
+ }
+ }
+ };
+
+ Buffer.prototype.toJSON = function toJSON() {
+ return {
+ type: 'Buffer',
+ data: Array.prototype.slice.call(this._arr || this, 0)
+ };
+ };
+
+ function base64Slice(buf, start, end) {
+ if (start === 0 && end === buf.length) {
+ return fromByteArray(buf);
+ } else {
+ return fromByteArray(buf.slice(start, end));
+ }
+ }
+
+ function utf8Slice(buf, start, end) {
+ end = Math.min(buf.length, end);
+ var res = [];
+ var i = start;
+
+ while (i < end) {
+ var firstByte = buf[i];
+ var codePoint = null;
+ var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1;
+
+ if (i + bytesPerSequence <= end) {
+ var secondByte, thirdByte, fourthByte, tempCodePoint;
+
+ switch (bytesPerSequence) {
+ case 1:
+ if (firstByte < 0x80) {
+ codePoint = firstByte;
+ }
+
+ break;
+
+ case 2:
+ secondByte = buf[i + 1];
+
+ if ((secondByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F;
+
+ if (tempCodePoint > 0x7F) {
+ codePoint = tempCodePoint;
+ }
+ }
+
+ break;
+
+ case 3:
+ secondByte = buf[i + 1];
+ thirdByte = buf[i + 2];
+
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F;
+
+ if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
+ codePoint = tempCodePoint;
+ }
+ }
+
+ break;
+
+ case 4:
+ secondByte = buf[i + 1];
+ thirdByte = buf[i + 2];
+ fourthByte = buf[i + 3];
+
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F;
+
+ if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
+ codePoint = tempCodePoint;
+ }
+ }
+
+ }
+ }
+
+ if (codePoint === null) {
+ // we did not generate a valid codePoint so insert a
+ // replacement char (U+FFFD) and advance only 1 byte
+ codePoint = 0xFFFD;
+ bytesPerSequence = 1;
+ } else if (codePoint > 0xFFFF) {
+ // encode to utf16 (surrogate pair dance)
+ codePoint -= 0x10000;
+ res.push(codePoint >>> 10 & 0x3FF | 0xD800);
+ codePoint = 0xDC00 | codePoint & 0x3FF;
+ }
+
+ res.push(codePoint);
+ i += bytesPerSequence;
+ }
+
+ return decodeCodePointsArray(res);
+ } // Based on http://stackoverflow.com/a/22747272/680742, the browser with
+ // the lowest limit is Chrome, with 0x10000 args.
+ // We go 1 magnitude less, for safety
+
+
+ var MAX_ARGUMENTS_LENGTH = 0x1000;
+
+ function decodeCodePointsArray(codePoints) {
+ var len = codePoints.length;
+
+ if (len <= MAX_ARGUMENTS_LENGTH) {
+ return String.fromCharCode.apply(String, codePoints); // avoid extra slice()
+ } // Decode in chunks to avoid "call stack size exceeded".
+
+
+ var res = '';
+ var i = 0;
+
+ while (i < len) {
+ res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
+ }
+
+ return res;
+ }
+
+ function asciiSlice(buf, start, end) {
+ var ret = '';
+ end = Math.min(buf.length, end);
+
+ for (var i = start; i < end; ++i) {
+ ret += String.fromCharCode(buf[i] & 0x7F);
+ }
+
+ return ret;
+ }
+
+ function latin1Slice(buf, start, end) {
+ var ret = '';
+ end = Math.min(buf.length, end);
+
+ for (var i = start; i < end; ++i) {
+ ret += String.fromCharCode(buf[i]);
+ }
+
+ return ret;
+ }
+
+ function hexSlice(buf, start, end) {
+ var len = buf.length;
+ if (!start || start < 0) start = 0;
+ if (!end || end < 0 || end > len) end = len;
+ var out = '';
+
+ for (var i = start; i < end; ++i) {
+ out += toHex(buf[i]);
+ }
+
+ return out;
+ }
+
+ function utf16leSlice(buf, start, end) {
+ var bytes = buf.slice(start, end);
+ var res = '';
+
+ for (var i = 0; i < bytes.length; i += 2) {
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
+ }
+
+ return res;
+ }
+
+ Buffer.prototype.slice = function slice(start, end) {
+ var len = this.length;
+ start = ~~start;
+ end = end === undefined ? len : ~~end;
+
+ if (start < 0) {
+ start += len;
+ if (start < 0) start = 0;
+ } else if (start > len) {
+ start = len;
+ }
+
+ if (end < 0) {
+ end += len;
+ if (end < 0) end = 0;
+ } else if (end > len) {
+ end = len;
+ }
+
+ if (end < start) end = start;
+ var newBuf;
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ newBuf = this.subarray(start, end);
+ newBuf.__proto__ = Buffer.prototype;
+ } else {
+ var sliceLen = end - start;
+ newBuf = new Buffer(sliceLen, undefined);
+
+ for (var i = 0; i < sliceLen; ++i) {
+ newBuf[i] = this[i + start];
+ }
+ }
+
+ return newBuf;
+ };
+ /*
+ * Need to make sure that buffer isn't trying to write out of bounds.
+ */
+
+
+ function checkOffset(offset, ext, length) {
+ if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint');
+ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length');
+ }
+
+ Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
+ offset = offset | 0;
+ byteLength = byteLength | 0;
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
+ var val = this[offset];
+ var mul = 1;
+ var i = 0;
+
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul;
+ }
+
+ return val;
+ };
+
+ Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
+ offset = offset | 0;
+ byteLength = byteLength | 0;
+
+ if (!noAssert) {
+ checkOffset(offset, byteLength, this.length);
+ }
+
+ var val = this[offset + --byteLength];
+ var mul = 1;
+
+ while (byteLength > 0 && (mul *= 0x100)) {
+ val += this[offset + --byteLength] * mul;
+ }
+
+ return val;
+ };
+
+ Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 1, this.length);
+ return this[offset];
+ };
+
+ Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length);
+ return this[offset] | this[offset + 1] << 8;
+ };
+
+ Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length);
+ return this[offset] << 8 | this[offset + 1];
+ };
+
+ Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length);
+ return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000;
+ };
+
+ Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length);
+ return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
+ };
+
+ Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
+ offset = offset | 0;
+ byteLength = byteLength | 0;
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
+ var val = this[offset];
+ var mul = 1;
+ var i = 0;
+
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul;
+ }
+
+ mul *= 0x80;
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength);
+ return val;
+ };
+
+ Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
+ offset = offset | 0;
+ byteLength = byteLength | 0;
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
+ var i = byteLength;
+ var mul = 1;
+ var val = this[offset + --i];
+
+ while (i > 0 && (mul *= 0x100)) {
+ val += this[offset + --i] * mul;
+ }
+
+ mul *= 0x80;
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength);
+ return val;
+ };
+
+ Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 1, this.length);
+ if (!(this[offset] & 0x80)) return this[offset];
+ return (0xff - this[offset] + 1) * -1;
+ };
+
+ Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length);
+ var val = this[offset] | this[offset + 1] << 8;
+ return val & 0x8000 ? val | 0xFFFF0000 : val;
+ };
+
+ Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length);
+ var val = this[offset + 1] | this[offset] << 8;
+ return val & 0x8000 ? val | 0xFFFF0000 : val;
+ };
+
+ Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length);
+ return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
+ };
+
+ Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length);
+ return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
+ };
+
+ Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length);
+ return read(this, offset, true, 23, 4);
+ };
+
+ Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length);
+ return read(this, offset, false, 23, 4);
+ };
+
+ Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 8, this.length);
+ return read(this, offset, true, 52, 8);
+ };
+
+ Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 8, this.length);
+ return read(this, offset, false, 52, 8);
+ };
+
+ function checkInt(buf, value, offset, ext, max, min) {
+ if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
+ if (offset + ext > buf.length) throw new RangeError('Index out of range');
+ }
+
+ Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ byteLength = byteLength | 0;
+
+ if (!noAssert) {
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1;
+ checkInt(this, value, offset, byteLength, maxBytes, 0);
+ }
+
+ var mul = 1;
+ var i = 0;
+ this[offset] = value & 0xFF;
+
+ while (++i < byteLength && (mul *= 0x100)) {
+ this[offset + i] = value / mul & 0xFF;
+ }
+
+ return offset + byteLength;
+ };
+
+ Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ byteLength = byteLength | 0;
+
+ if (!noAssert) {
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1;
+ checkInt(this, value, offset, byteLength, maxBytes, 0);
+ }
+
+ var i = byteLength - 1;
+ var mul = 1;
+ this[offset + i] = value & 0xFF;
+
+ while (--i >= 0 && (mul *= 0x100)) {
+ this[offset + i] = value / mul & 0xFF;
+ }
+
+ return offset + byteLength;
+ };
+
+ Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
+ this[offset] = value & 0xff;
+ return offset + 1;
+ };
+
+ function objectWriteUInt16(buf, value, offset, littleEndian) {
+ if (value < 0) value = 0xffff + value + 1;
+
+ for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
+ buf[offset + i] = (value & 0xff << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8;
+ }
+ }
+
+ Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value & 0xff;
+ this[offset + 1] = value >>> 8;
+ } else {
+ objectWriteUInt16(this, value, offset, true);
+ }
+
+ return offset + 2;
+ };
+
+ Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value >>> 8;
+ this[offset + 1] = value & 0xff;
+ } else {
+ objectWriteUInt16(this, value, offset, false);
+ }
+
+ return offset + 2;
+ };
+
+ function objectWriteUInt32(buf, value, offset, littleEndian) {
+ if (value < 0) value = 0xffffffff + value + 1;
+
+ for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
+ buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 0xff;
+ }
+ }
+
+ Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset + 3] = value >>> 24;
+ this[offset + 2] = value >>> 16;
+ this[offset + 1] = value >>> 8;
+ this[offset] = value & 0xff;
+ } else {
+ objectWriteUInt32(this, value, offset, true);
+ }
+
+ return offset + 4;
+ };
+
+ Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value >>> 24;
+ this[offset + 1] = value >>> 16;
+ this[offset + 2] = value >>> 8;
+ this[offset + 3] = value & 0xff;
+ } else {
+ objectWriteUInt32(this, value, offset, false);
+ }
+
+ return offset + 4;
+ };
+
+ Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
+ value = +value;
+ offset = offset | 0;
+
+ if (!noAssert) {
+ var limit = Math.pow(2, 8 * byteLength - 1);
+ checkInt(this, value, offset, byteLength, limit - 1, -limit);
+ }
+
+ var i = 0;
+ var mul = 1;
+ var sub = 0;
+ this[offset] = value & 0xFF;
+
+ while (++i < byteLength && (mul *= 0x100)) {
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
+ sub = 1;
+ }
+
+ this[offset + i] = (value / mul >> 0) - sub & 0xFF;
+ }
+
+ return offset + byteLength;
+ };
+
+ Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
+ value = +value;
+ offset = offset | 0;
+
+ if (!noAssert) {
+ var limit = Math.pow(2, 8 * byteLength - 1);
+ checkInt(this, value, offset, byteLength, limit - 1, -limit);
+ }
+
+ var i = byteLength - 1;
+ var mul = 1;
+ var sub = 0;
+ this[offset + i] = value & 0xFF;
+
+ while (--i >= 0 && (mul *= 0x100)) {
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
+ sub = 1;
+ }
+
+ this[offset + i] = (value / mul >> 0) - sub & 0xFF;
+ }
+
+ return offset + byteLength;
+ };
+
+ Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
+ if (value < 0) value = 0xff + value + 1;
+ this[offset] = value & 0xff;
+ return offset + 1;
+ };
+
+ Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value & 0xff;
+ this[offset + 1] = value >>> 8;
+ } else {
+ objectWriteUInt16(this, value, offset, true);
+ }
+
+ return offset + 2;
+ };
+
+ Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value >>> 8;
+ this[offset + 1] = value & 0xff;
+ } else {
+ objectWriteUInt16(this, value, offset, false);
+ }
+
+ return offset + 2;
+ };
+
+ Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value & 0xff;
+ this[offset + 1] = value >>> 8;
+ this[offset + 2] = value >>> 16;
+ this[offset + 3] = value >>> 24;
+ } else {
+ objectWriteUInt32(this, value, offset, true);
+ }
+
+ return offset + 4;
+ };
+
+ Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
+ value = +value;
+ offset = offset | 0;
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
+ if (value < 0) value = 0xffffffff + value + 1;
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = value >>> 24;
+ this[offset + 1] = value >>> 16;
+ this[offset + 2] = value >>> 8;
+ this[offset + 3] = value & 0xff;
+ } else {
+ objectWriteUInt32(this, value, offset, false);
+ }
+
+ return offset + 4;
+ };
+
+ function checkIEEE754(buf, value, offset, ext, max, min) {
+ if (offset + ext > buf.length) throw new RangeError('Index out of range');
+ if (offset < 0) throw new RangeError('Index out of range');
+ }
+
+ function writeFloat(buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ checkIEEE754(buf, value, offset, 4);
+ }
+
+ write(buf, value, offset, littleEndian, 23, 4);
+ return offset + 4;
+ }
+
+ Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
+ return writeFloat(this, value, offset, true, noAssert);
+ };
+
+ Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
+ return writeFloat(this, value, offset, false, noAssert);
+ };
+
+ function writeDouble(buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ checkIEEE754(buf, value, offset, 8);
+ }
+
+ write(buf, value, offset, littleEndian, 52, 8);
+ return offset + 8;
+ }
+
+ Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
+ return writeDouble(this, value, offset, true, noAssert);
+ };
+
+ Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
+ return writeDouble(this, value, offset, false, noAssert);
+ }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
+
+
+ Buffer.prototype.copy = function copy(target, targetStart, start, end) {
+ if (!start) start = 0;
+ if (!end && end !== 0) end = this.length;
+ if (targetStart >= target.length) targetStart = target.length;
+ if (!targetStart) targetStart = 0;
+ if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done
+
+ if (end === start) return 0;
+ if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions
+
+ if (targetStart < 0) {
+ throw new RangeError('targetStart out of bounds');
+ }
+
+ if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds');
+ if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob?
+
+ if (end > this.length) end = this.length;
+
+ if (target.length - targetStart < end - start) {
+ end = target.length - targetStart + start;
+ }
+
+ var len = end - start;
+ var i;
+
+ if (this === target && start < targetStart && targetStart < end) {
+ // descending copy from end
+ for (i = len - 1; i >= 0; --i) {
+ target[i + targetStart] = this[i + start];
+ }
+ } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
+ // ascending copy from start
+ for (i = 0; i < len; ++i) {
+ target[i + targetStart] = this[i + start];
+ }
+ } else {
+ Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart);
+ }
+
+ return len;
+ }; // Usage:
+ // buffer.fill(number[, offset[, end]])
+ // buffer.fill(buffer[, offset[, end]])
+ // buffer.fill(string[, offset[, end]][, encoding])
+
+
+ Buffer.prototype.fill = function fill(val, start, end, encoding) {
+ // Handle string cases:
+ if (typeof val === 'string') {
+ if (typeof start === 'string') {
+ encoding = start;
+ start = 0;
+ end = this.length;
+ } else if (typeof end === 'string') {
+ encoding = end;
+ end = this.length;
+ }
+
+ if (val.length === 1) {
+ var code = val.charCodeAt(0);
+
+ if (code < 256) {
+ val = code;
+ }
+ }
+
+ if (encoding !== undefined && typeof encoding !== 'string') {
+ throw new TypeError('encoding must be a string');
+ }
+
+ if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
+ throw new TypeError('Unknown encoding: ' + encoding);
+ }
+ } else if (typeof val === 'number') {
+ val = val & 255;
+ } // Invalid ranges are not set to a default, so can range check early.
+
+
+ if (start < 0 || this.length < start || this.length < end) {
+ throw new RangeError('Out of range index');
+ }
+
+ if (end <= start) {
+ return this;
+ }
+
+ start = start >>> 0;
+ end = end === undefined ? this.length : end >>> 0;
+ if (!val) val = 0;
+ var i;
+
+ if (typeof val === 'number') {
+ for (i = start; i < end; ++i) {
+ this[i] = val;
+ }
+ } else {
+ var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString());
+ var len = bytes.length;
+
+ for (i = 0; i < end - start; ++i) {
+ this[i + start] = bytes[i % len];
+ }
+ }
+
+ return this;
+ }; // HELPER FUNCTIONS
+ // ================
+
+
+ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
+
+ function base64clean(str) {
+ // Node strips out invalid characters like \n and \t from the string, base64-js does not
+ str = stringtrim(str).replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to ''
+
+ if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
+
+ while (str.length % 4 !== 0) {
+ str = str + '=';
+ }
+
+ return str;
+ }
+
+ function stringtrim(str) {
+ if (str.trim) return str.trim();
+ return str.replace(/^\s+|\s+$/g, '');
+ }
+
+ function toHex(n) {
+ if (n < 16) return '0' + n.toString(16);
+ return n.toString(16);
+ }
+
+ function utf8ToBytes(string, units) {
+ units = units || Infinity;
+ var codePoint;
+ var length = string.length;
+ var leadSurrogate = null;
+ var bytes = [];
+
+ for (var i = 0; i < length; ++i) {
+ codePoint = string.charCodeAt(i); // is surrogate component
+
+ if (codePoint > 0xD7FF && codePoint < 0xE000) {
+ // last char was a lead
+ if (!leadSurrogate) {
+ // no lead yet
+ if (codePoint > 0xDBFF) {
+ // unexpected trail
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
+ continue;
+ } else if (i + 1 === length) {
+ // unpaired lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
+ continue;
+ } // valid lead
+
+
+ leadSurrogate = codePoint;
+ continue;
+ } // 2 leads in a row
+
+
+ if (codePoint < 0xDC00) {
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
+ leadSurrogate = codePoint;
+ continue;
+ } // valid surrogate pair
+
+
+ codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
+ } else if (leadSurrogate) {
+ // valid bmp char, but last char was a lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
+ }
+
+ leadSurrogate = null; // encode utf8
+
+ if (codePoint < 0x80) {
+ if ((units -= 1) < 0) break;
+ bytes.push(codePoint);
+ } else if (codePoint < 0x800) {
+ if ((units -= 2) < 0) break;
+ bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80);
+ } else if (codePoint < 0x10000) {
+ if ((units -= 3) < 0) break;
+ bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
+ } else if (codePoint < 0x110000) {
+ if ((units -= 4) < 0) break;
+ bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
+ } else {
+ throw new Error('Invalid code point');
+ }
+ }
+
+ return bytes;
+ }
+
+ function asciiToBytes(str) {
+ var byteArray = [];
+
+ for (var i = 0; i < str.length; ++i) {
+ // Node's code seems to be doing this and not & 0x7F..
+ byteArray.push(str.charCodeAt(i) & 0xFF);
+ }
+
+ return byteArray;
+ }
+
+ function utf16leToBytes(str, units) {
+ var c, hi, lo;
+ var byteArray = [];
+
+ for (var i = 0; i < str.length; ++i) {
+ if ((units -= 2) < 0) break;
+ c = str.charCodeAt(i);
+ hi = c >> 8;
+ lo = c % 256;
+ byteArray.push(lo);
+ byteArray.push(hi);
+ }
+
+ return byteArray;
+ }
+
+ function base64ToBytes(str) {
+ return toByteArray(base64clean(str));
+ }
+
+ function blitBuffer(src, dst, offset, length) {
+ for (var i = 0; i < length; ++i) {
+ if (i + offset >= dst.length || i >= src.length) break;
+ dst[i + offset] = src[i];
+ }
+
+ return i;
+ }
+
+ function isnan(val) {
+ return val !== val; // eslint-disable-line no-self-compare
+ } // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
+ // The _isBuffer check is for Safari 5-7 support, because it's missing
+ // Object.prototype.constructor. Remove this eventually
+
+
+ function isBuffer(obj) {
+ return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj));
+ }
+
+ function isFastBuffer(obj) {
+ return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj);
+ } // For Node v0.10 support. Remove this eventually.
+
+
+ function isSlowBuffer(obj) {
+ return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0));
+ }
+
+ function BufferList() {
+ this.head = null;
+ this.tail = null;
+ this.length = 0;
+ }
+
+ BufferList.prototype.push = function (v) {
+ var entry = {
+ data: v,
+ next: null
+ };
+ if (this.length > 0) this.tail.next = entry;else this.head = entry;
+ this.tail = entry;
+ ++this.length;
+ };
+
+ BufferList.prototype.unshift = function (v) {
+ var entry = {
+ data: v,
+ next: this.head
+ };
+ if (this.length === 0) this.tail = entry;
+ this.head = entry;
+ ++this.length;
+ };
+
+ BufferList.prototype.shift = function () {
+ if (this.length === 0) return;
+ var ret = this.head.data;
+ if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
+ --this.length;
+ return ret;
+ };
+
+ BufferList.prototype.clear = function () {
+ this.head = this.tail = null;
+ this.length = 0;
+ };
+
+ BufferList.prototype.join = function (s) {
+ if (this.length === 0) return '';
+ var p = this.head;
+ var ret = '' + p.data;
+
+ while (p = p.next) {
+ ret += s + p.data;
+ }
+
+ return ret;
+ };
+
+ BufferList.prototype.concat = function (n) {
+ if (this.length === 0) return Buffer.alloc(0);
+ if (this.length === 1) return this.head.data;
+ var ret = Buffer.allocUnsafe(n >>> 0);
+ var p = this.head;
+ var i = 0;
+
+ while (p) {
+ p.data.copy(ret, i);
+ i += p.data.length;
+ p = p.next;
+ }
+
+ return ret;
+ };
+
+ var isBufferEncoding = Buffer.isEncoding || function (encoding) {
+ switch (encoding && encoding.toLowerCase()) {
+ case 'hex':
+ case 'utf8':
+ case 'utf-8':
+ case 'ascii':
+ case 'binary':
+ case 'base64':
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ case 'raw':
+ return true;
+
+ default:
+ return false;
+ }
+ };
+
+ function assertEncoding(encoding) {
+ if (encoding && !isBufferEncoding(encoding)) {
+ throw new Error('Unknown encoding: ' + encoding);
+ }
+ } // StringDecoder provides an interface for efficiently splitting a series of
+ // buffers into a series of JS strings without breaking apart multi-byte
+ // characters. CESU-8 is handled as part of the UTF-8 encoding.
+ //
+ // @TODO Handling all encodings inside a single object makes it very difficult
+ // to reason about this code, so it should be split up in the future.
+ // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
+ // points as used by CESU-8.
+
+
+ function StringDecoder(encoding) {
+ this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
+ assertEncoding(encoding);
+
+ switch (this.encoding) {
+ case 'utf8':
+ // CESU-8 represents each of Surrogate Pair by 3-bytes
+ this.surrogateSize = 3;
+ break;
+
+ case 'ucs2':
+ case 'utf16le':
+ // UTF-16 represents each of Surrogate Pair by 2-bytes
+ this.surrogateSize = 2;
+ this.detectIncompleteChar = utf16DetectIncompleteChar;
+ break;
+
+ case 'base64':
+ // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
+ this.surrogateSize = 3;
+ this.detectIncompleteChar = base64DetectIncompleteChar;
+ break;
+
+ default:
+ this.write = passThroughWrite;
+ return;
+ } // Enough space to store all bytes of a single character. UTF-8 needs 4
+ // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
+
+
+ this.charBuffer = new Buffer(6); // Number of bytes received for the current incomplete multi-byte character.
+
+ this.charReceived = 0; // Number of bytes expected for the current incomplete multi-byte character.
+
+ this.charLength = 0;
+ }
+ // guaranteed to not contain any partial multi-byte characters. Any partial
+ // character found at the end of the buffer is buffered up, and will be
+ // returned when calling write again with the remaining bytes.
+ //
+ // Note: Converting a Buffer containing an orphan surrogate to a String
+ // currently works, but converting a String to a Buffer (via `new Buffer`, or
+ // Buffer#write) will replace incomplete surrogates with the unicode
+ // replacement character. See https://codereview.chromium.org/121173009/ .
+
+ StringDecoder.prototype.write = function (buffer) {
+ var charStr = ''; // if our last write ended with an incomplete multibyte character
+
+ while (this.charLength) {
+ // determine how many remaining bytes this buffer has to offer for this char
+ var available = buffer.length >= this.charLength - this.charReceived ? this.charLength - this.charReceived : buffer.length; // add the new bytes to the char buffer
+
+ buffer.copy(this.charBuffer, this.charReceived, 0, available);
+ this.charReceived += available;
+
+ if (this.charReceived < this.charLength) {
+ // still not enough chars in this buffer? wait for more ...
+ return '';
+ } // remove bytes belonging to the current character from the buffer
+
+
+ buffer = buffer.slice(available, buffer.length); // get the character that was split
+
+ charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
+
+ var charCode = charStr.charCodeAt(charStr.length - 1);
+
+ if (charCode >= 0xD800 && charCode <= 0xDBFF) {
+ this.charLength += this.surrogateSize;
+ charStr = '';
+ continue;
+ }
+
+ this.charReceived = this.charLength = 0; // if there are no more bytes in this buffer, just emit our char
+
+ if (buffer.length === 0) {
+ return charStr;
+ }
+
+ break;
+ } // determine and set charLength / charReceived
+
+
+ this.detectIncompleteChar(buffer);
+ var end = buffer.length;
+
+ if (this.charLength) {
+ // buffer the incomplete character bytes we got
+ buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
+ end -= this.charReceived;
+ }
+
+ charStr += buffer.toString(this.encoding, 0, end);
+ var end = charStr.length - 1;
+ var charCode = charStr.charCodeAt(end); // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
+
+ if (charCode >= 0xD800 && charCode <= 0xDBFF) {
+ var size = this.surrogateSize;
+ this.charLength += size;
+ this.charReceived += size;
+ this.charBuffer.copy(this.charBuffer, size, 0, size);
+ buffer.copy(this.charBuffer, 0, 0, size);
+ return charStr.substring(0, end);
+ } // or just emit the charStr
+
+
+ return charStr;
+ }; // detectIncompleteChar determines if there is an incomplete UTF-8 character at
+ // the end of the given buffer. If so, it sets this.charLength to the byte
+ // length that character, and sets this.charReceived to the number of bytes
+ // that are available for this character.
+
+
+ StringDecoder.prototype.detectIncompleteChar = function (buffer) {
+ // determine how many bytes we have to check at the end of this buffer
+ var i = buffer.length >= 3 ? 3 : buffer.length; // Figure out if one of the last i bytes of our buffer announces an
+ // incomplete char.
+
+ for (; i > 0; i--) {
+ var c = buffer[buffer.length - i]; // See http://en.wikipedia.org/wiki/UTF-8#Description
+ // 110XXXXX
+
+ if (i == 1 && c >> 5 == 0x06) {
+ this.charLength = 2;
+ break;
+ } // 1110XXXX
+
+
+ if (i <= 2 && c >> 4 == 0x0E) {
+ this.charLength = 3;
+ break;
+ } // 11110XXX
+
+
+ if (i <= 3 && c >> 3 == 0x1E) {
+ this.charLength = 4;
+ break;
+ }
+ }
+
+ this.charReceived = i;
+ };
+
+ StringDecoder.prototype.end = function (buffer) {
+ var res = '';
+ if (buffer && buffer.length) res = this.write(buffer);
+
+ if (this.charReceived) {
+ var cr = this.charReceived;
+ var buf = this.charBuffer;
+ var enc = this.encoding;
+ res += buf.slice(0, cr).toString(enc);
+ }
+
+ return res;
+ };
+
+ function passThroughWrite(buffer) {
+ return buffer.toString(this.encoding);
+ }
+
+ function utf16DetectIncompleteChar(buffer) {
+ this.charReceived = buffer.length % 2;
+ this.charLength = this.charReceived ? 2 : 0;
+ }
+
+ function base64DetectIncompleteChar(buffer) {
+ this.charReceived = buffer.length % 3;
+ this.charLength = this.charReceived ? 3 : 0;
+ }
+
+ Readable.ReadableState = ReadableState;
+ var debug$2 = debuglog('stream');
+ inherits$3(Readable, EventEmitter$2);
+
+ function prependListener(emitter, event, fn) {
+ // Sadly this is not cacheable as some libraries bundle their own
+ // event emitter implementation with them.
+ if (typeof emitter.prependListener === 'function') {
+ return emitter.prependListener(event, fn);
+ } else {
+ // This is a hack to make sure that our error handler is attached before any
+ // userland ones. NEVER DO THIS. This is here only because this code needs
+ // to continue to work with older versions of Node.js that do not include
+ // the prependListener() method. The goal is to eventually remove this hack.
+ if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
+ }
+ }
+
+ function listenerCount(emitter, type) {
+ return emitter.listeners(type).length;
+ }
+
+ function ReadableState(options, stream) {
+ options = options || {}; // object stream flag. Used to make read(n) ignore n and to
+ // make all the buffer merging and length checks go away
+
+ this.objectMode = !!options.objectMode;
+ if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
+ // Note: 0 is a valid value, means "don't call _read preemptively ever"
+
+ var hwm = options.highWaterMark;
+ var defaultHwm = this.objectMode ? 16 : 16 * 1024;
+ this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; // cast to ints.
+
+ this.highWaterMark = ~~this.highWaterMark; // A linked list is used to store data chunks instead of an array because the
+ // linked list can remove elements from the beginning faster than
+ // array.shift()
+
+ this.buffer = new BufferList();
+ this.length = 0;
+ this.pipes = null;
+ this.pipesCount = 0;
+ this.flowing = null;
+ this.ended = false;
+ this.endEmitted = false;
+ this.reading = false; // a flag to be able to tell if the onwrite cb is called immediately,
+ // or on a later tick. We set this to true at first, because any
+ // actions that shouldn't happen until "later" should generally also
+ // not happen before the first write call.
+
+ this.sync = true; // whenever we return null, then we set a flag to say
+ // that we're awaiting a 'readable' event emission.
+
+ this.needReadable = false;
+ this.emittedReadable = false;
+ this.readableListening = false;
+ this.resumeScheduled = false; // Crypto is kind of old and crusty. Historically, its default string
+ // encoding is 'binary' so we have to make this configurable.
+ // Everything else in the universe uses 'utf8', though.
+
+ this.defaultEncoding = options.defaultEncoding || 'utf8'; // when piping, we only care about 'readable' events that happen
+ // after read()ing all the bytes and not getting any pushback.
+
+ this.ranOut = false; // the number of writers that are awaiting a drain event in .pipe()s
+
+ this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
+
+ this.readingMore = false;
+ this.decoder = null;
+ this.encoding = null;
+
+ if (options.encoding) {
+ this.decoder = new StringDecoder(options.encoding);
+ this.encoding = options.encoding;
+ }
+ }
+ function Readable(options) {
+ if (!(this instanceof Readable)) return new Readable(options);
+ this._readableState = new ReadableState(options, this); // legacy
+
+ this.readable = true;
+ if (options && typeof options.read === 'function') this._read = options.read;
+ EventEmitter$2.call(this);
+ } // Manually shove something into the read() buffer.
+ // This returns true if the highWaterMark has not been hit yet,
+ // similar to how Writable.write() returns true if you should
+ // write() some more.
+
+ Readable.prototype.push = function (chunk, encoding) {
+ var state = this._readableState;
+
+ if (!state.objectMode && typeof chunk === 'string') {
+ encoding = encoding || state.defaultEncoding;
+
+ if (encoding !== state.encoding) {
+ chunk = Buffer$1.from(chunk, encoding);
+ encoding = '';
+ }
+ }
+
+ return readableAddChunk(this, state, chunk, encoding, false);
+ }; // Unshift should *always* be something directly out of read()
+
+
+ Readable.prototype.unshift = function (chunk) {
+ var state = this._readableState;
+ return readableAddChunk(this, state, chunk, '', true);
+ };
+
+ Readable.prototype.isPaused = function () {
+ return this._readableState.flowing === false;
+ };
+
+ function readableAddChunk(stream, state, chunk, encoding, addToFront) {
+ var er = chunkInvalid(state, chunk);
+
+ if (er) {
+ stream.emit('error', er);
+ } else if (chunk === null) {
+ state.reading = false;
+ onEofChunk(stream, state);
+ } else if (state.objectMode || chunk && chunk.length > 0) {
+ if (state.ended && !addToFront) {
+ var e = new Error('stream.push() after EOF');
+ stream.emit('error', e);
+ } else if (state.endEmitted && addToFront) {
+ var _e = new Error('stream.unshift() after end event');
+
+ stream.emit('error', _e);
+ } else {
+ var skipAdd;
+
+ if (state.decoder && !addToFront && !encoding) {
+ chunk = state.decoder.write(chunk);
+ skipAdd = !state.objectMode && chunk.length === 0;
+ }
+
+ if (!addToFront) state.reading = false; // Don't add to the buffer if we've decoded to an empty string chunk and
+ // we're not in object mode
+
+ if (!skipAdd) {
+ // if we want the data now, just emit it.
+ if (state.flowing && state.length === 0 && !state.sync) {
+ stream.emit('data', chunk);
+ stream.read(0);
+ } else {
+ // update the buffer info.
+ state.length += state.objectMode ? 1 : chunk.length;
+ if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
+ if (state.needReadable) emitReadable(stream);
+ }
+ }
+
+ maybeReadMore(stream, state);
+ }
+ } else if (!addToFront) {
+ state.reading = false;
+ }
+
+ return needMoreData(state);
+ } // if it's past the high water mark, we can push in some more.
+ // Also, if we have no data yet, we can stand some
+ // more bytes. This is to work around cases where hwm=0,
+ // such as the repl. Also, if the push() triggered a
+ // readable event, and the user called read(largeNumber) such that
+ // needReadable was set, then we ought to push more, so that another
+ // 'readable' event will be triggered.
+
+
+ function needMoreData(state) {
+ return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
+ } // backwards compatibility.
+
+
+ Readable.prototype.setEncoding = function (enc) {
+ this._readableState.decoder = new StringDecoder(enc);
+ this._readableState.encoding = enc;
+ return this;
+ }; // Don't raise the hwm > 8MB
+
+
+ var MAX_HWM = 0x800000;
+
+ function computeNewHighWaterMark(n) {
+ if (n >= MAX_HWM) {
+ n = MAX_HWM;
+ } else {
+ // Get the next highest power of 2 to prevent increasing hwm excessively in
+ // tiny amounts
+ n--;
+ n |= n >>> 1;
+ n |= n >>> 2;
+ n |= n >>> 4;
+ n |= n >>> 8;
+ n |= n >>> 16;
+ n++;
+ }
+
+ return n;
+ } // This function is designed to be inlinable, so please take care when making
+ // changes to the function body.
+
+
+ function howMuchToRead(n, state) {
+ if (n <= 0 || state.length === 0 && state.ended) return 0;
+ if (state.objectMode) return 1;
+
+ if (n !== n) {
+ // Only flow one buffer at a time
+ if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
+ } // If we're asking for more than the current hwm, then raise the hwm.
+
+
+ if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
+ if (n <= state.length) return n; // Don't have enough
+
+ if (!state.ended) {
+ state.needReadable = true;
+ return 0;
+ }
+
+ return state.length;
+ } // you can override either this method, or the async _read(n) below.
+
+
+ Readable.prototype.read = function (n) {
+ debug$2('read', n);
+ n = parseInt(n, 10);
+ var state = this._readableState;
+ var nOrig = n;
+ if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
+ // already have a bunch of data in the buffer, then just trigger
+ // the 'readable' event and move on.
+
+ if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
+ debug$2('read: emitReadable', state.length, state.ended);
+ if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
+ return null;
+ }
+
+ n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
+
+ if (n === 0 && state.ended) {
+ if (state.length === 0) endReadable(this);
+ return null;
+ } // All the actual chunk generation logic needs to be
+ // *below* the call to _read. The reason is that in certain
+ // synthetic stream cases, such as passthrough streams, _read
+ // may be a completely synchronous operation which may change
+ // the state of the read buffer, providing enough data when
+ // before there was *not* enough.
+ //
+ // So, the steps are:
+ // 1. Figure out what the state of things will be after we do
+ // a read from the buffer.
+ //
+ // 2. If that resulting state will trigger a _read, then call _read.
+ // Note that this may be asynchronous, or synchronous. Yes, it is
+ // deeply ugly to write APIs this way, but that still doesn't mean
+ // that the Readable class should behave improperly, as streams are
+ // designed to be sync/async agnostic.
+ // Take note if the _read call is sync or async (ie, if the read call
+ // has returned yet), so that we know whether or not it's safe to emit
+ // 'readable' etc.
+ //
+ // 3. Actually pull the requested chunks out of the buffer and return.
+ // if we need a readable event, then we need to do some reading.
+
+
+ var doRead = state.needReadable;
+ debug$2('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
+
+ if (state.length === 0 || state.length - n < state.highWaterMark) {
+ doRead = true;
+ debug$2('length less than watermark', doRead);
+ } // however, if we've ended, then there's no point, and if we're already
+ // reading, then it's unnecessary.
+
+
+ if (state.ended || state.reading) {
+ doRead = false;
+ debug$2('reading or ended', doRead);
+ } else if (doRead) {
+ debug$2('do read');
+ state.reading = true;
+ state.sync = true; // if the length is currently zero, then we *need* a readable event.
+
+ if (state.length === 0) state.needReadable = true; // call internal read method
+
+ this._read(state.highWaterMark);
+
+ state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
+ // and we need to re-evaluate how much data we can return to the user.
+
+ if (!state.reading) n = howMuchToRead(nOrig, state);
+ }
+
+ var ret;
+ if (n > 0) ret = fromList(n, state);else ret = null;
+
+ if (ret === null) {
+ state.needReadable = true;
+ n = 0;
+ } else {
+ state.length -= n;
+ }
+
+ if (state.length === 0) {
+ // If we have nothing in the buffer, then we want to know
+ // as soon as we *do* get something into the buffer.
+ if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
+
+ if (nOrig !== n && state.ended) endReadable(this);
+ }
+
+ if (ret !== null) this.emit('data', ret);
+ return ret;
+ };
+
+ function chunkInvalid(state, chunk) {
+ var er = null;
+
+ if (!isBuffer$2(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
+ er = new TypeError('Invalid non-string/buffer chunk');
+ }
+
+ return er;
+ }
+
+ function onEofChunk(stream, state) {
+ if (state.ended) return;
+
+ if (state.decoder) {
+ var chunk = state.decoder.end();
+
+ if (chunk && chunk.length) {
+ state.buffer.push(chunk);
+ state.length += state.objectMode ? 1 : chunk.length;
+ }
+ }
+
+ state.ended = true; // emit 'readable' now to make sure it gets picked up.
+
+ emitReadable(stream);
+ } // Don't emit readable right away in sync mode, because this can trigger
+ // another read() call => stack overflow. This way, it might trigger
+ // a nextTick recursion warning, but that's not so bad.
+
+
+ function emitReadable(stream) {
+ var state = stream._readableState;
+ state.needReadable = false;
+
+ if (!state.emittedReadable) {
+ debug$2('emitReadable', state.flowing);
+ state.emittedReadable = true;
+ if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream);
+ }
+ }
+
+ function emitReadable_(stream) {
+ debug$2('emit readable');
+ stream.emit('readable');
+ flow(stream);
+ } // at this point, the user has presumably seen the 'readable' event,
+ // and called read() to consume some data. that may have triggered
+ // in turn another _read(n) call, in which case reading = true if
+ // it's in progress.
+ // However, if we're not ended, or reading, and the length < hwm,
+ // then go ahead and try to read some more preemptively.
+
+
+ function maybeReadMore(stream, state) {
+ if (!state.readingMore) {
+ state.readingMore = true;
+ nextTick(maybeReadMore_, stream, state);
+ }
+ }
+
+ function maybeReadMore_(stream, state) {
+ var len = state.length;
+
+ while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
+ debug$2('maybeReadMore read 0');
+ stream.read(0);
+ if (len === state.length) // didn't get any data, stop spinning.
+ break;else len = state.length;
+ }
+
+ state.readingMore = false;
+ } // abstract method. to be overridden in specific implementation classes.
+ // call cb(er, data) where data is <= n in length.
+ // for virtual (non-string, non-buffer) streams, "length" is somewhat
+ // arbitrary, and perhaps not very meaningful.
+
+
+ Readable.prototype._read = function (n) {
+ this.emit('error', new Error('not implemented'));
+ };
+
+ Readable.prototype.pipe = function (dest, pipeOpts) {
+ var src = this;
+ var state = this._readableState;
+
+ switch (state.pipesCount) {
+ case 0:
+ state.pipes = dest;
+ break;
+
+ case 1:
+ state.pipes = [state.pipes, dest];
+ break;
+
+ default:
+ state.pipes.push(dest);
+ break;
+ }
+
+ state.pipesCount += 1;
+ debug$2('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
+ var doEnd = !pipeOpts || pipeOpts.end !== false;
+ var endFn = doEnd ? onend : cleanup;
+ if (state.endEmitted) nextTick(endFn);else src.once('end', endFn);
+ dest.on('unpipe', onunpipe);
+
+ function onunpipe(readable) {
+ debug$2('onunpipe');
+
+ if (readable === src) {
+ cleanup();
+ }
+ }
+
+ function onend() {
+ debug$2('onend');
+ dest.end();
+ } // when the dest drains, it reduces the awaitDrain counter
+ // on the source. This would be more elegant with a .once()
+ // handler in flow(), but adding and removing repeatedly is
+ // too slow.
+
+
+ var ondrain = pipeOnDrain(src);
+ dest.on('drain', ondrain);
+ var cleanedUp = false;
+
+ function cleanup() {
+ debug$2('cleanup'); // cleanup event handlers once the pipe is broken
+
+ dest.removeListener('close', onclose);
+ dest.removeListener('finish', onfinish);
+ dest.removeListener('drain', ondrain);
+ dest.removeListener('error', onerror);
+ dest.removeListener('unpipe', onunpipe);
+ src.removeListener('end', onend);
+ src.removeListener('end', cleanup);
+ src.removeListener('data', ondata);
+ cleanedUp = true; // if the reader is waiting for a drain event from this
+ // specific writer, then it would cause it to never start
+ // flowing again.
+ // So, if this is awaiting a drain, then we just call it now.
+ // If we don't know, then assume that we are waiting for one.
+
+ if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
+ } // If the user pushes more data while we're writing to dest then we'll end up
+ // in ondata again. However, we only want to increase awaitDrain once because
+ // dest will only emit one 'drain' event for the multiple writes.
+ // => Introduce a guard on increasing awaitDrain.
+
+
+ var increasedAwaitDrain = false;
+ src.on('data', ondata);
+
+ function ondata(chunk) {
+ debug$2('ondata');
+ increasedAwaitDrain = false;
+ var ret = dest.write(chunk);
+
+ if (false === ret && !increasedAwaitDrain) {
+ // If the user unpiped during `dest.write()`, it is possible
+ // to get stuck in a permanently paused state if that write
+ // also returned false.
+ // => Check whether `dest` is still a piping destination.
+ if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
+ debug$2('false write response, pause', src._readableState.awaitDrain);
+ src._readableState.awaitDrain++;
+ increasedAwaitDrain = true;
+ }
+
+ src.pause();
+ }
+ } // if the dest has an error, then stop piping into it.
+ // however, don't suppress the throwing behavior for this.
+
+
+ function onerror(er) {
+ debug$2('onerror', er);
+ unpipe();
+ dest.removeListener('error', onerror);
+ if (listenerCount(dest, 'error') === 0) dest.emit('error', er);
+ } // Make sure our error handler is attached before userland ones.
+
+
+ prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
+
+ function onclose() {
+ dest.removeListener('finish', onfinish);
+ unpipe();
+ }
+
+ dest.once('close', onclose);
+
+ function onfinish() {
+ debug$2('onfinish');
+ dest.removeListener('close', onclose);
+ unpipe();
+ }
+
+ dest.once('finish', onfinish);
+
+ function unpipe() {
+ debug$2('unpipe');
+ src.unpipe(dest);
+ } // tell the dest that it's being piped to
+
+
+ dest.emit('pipe', src); // start the flow if it hasn't been started already.
+
+ if (!state.flowing) {
+ debug$2('pipe resume');
+ src.resume();
+ }
+
+ return dest;
+ };
+
+ function pipeOnDrain(src) {
+ return function () {
+ var state = src._readableState;
+ debug$2('pipeOnDrain', state.awaitDrain);
+ if (state.awaitDrain) state.awaitDrain--;
+
+ if (state.awaitDrain === 0 && src.listeners('data').length) {
+ state.flowing = true;
+ flow(src);
+ }
+ };
+ }
+
+ Readable.prototype.unpipe = function (dest) {
+ var state = this._readableState; // if we're not piping anywhere, then do nothing.
+
+ if (state.pipesCount === 0) return this; // just one destination. most common case.
+
+ if (state.pipesCount === 1) {
+ // passed in one, but it's not the right one.
+ if (dest && dest !== state.pipes) return this;
+ if (!dest) dest = state.pipes; // got a match.
+
+ state.pipes = null;
+ state.pipesCount = 0;
+ state.flowing = false;
+ if (dest) dest.emit('unpipe', this);
+ return this;
+ } // slow case. multiple pipe destinations.
+
+
+ if (!dest) {
+ // remove all.
+ var dests = state.pipes;
+ var len = state.pipesCount;
+ state.pipes = null;
+ state.pipesCount = 0;
+ state.flowing = false;
+
+ for (var _i = 0; _i < len; _i++) {
+ dests[_i].emit('unpipe', this);
+ }
+
+ return this;
+ } // try to find the right one.
+
+
+ var i = indexOf(state.pipes, dest);
+ if (i === -1) return this;
+ state.pipes.splice(i, 1);
+ state.pipesCount -= 1;
+ if (state.pipesCount === 1) state.pipes = state.pipes[0];
+ dest.emit('unpipe', this);
+ return this;
+ }; // set up data events if they are asked for
+ // Ensure readable listeners eventually get something
+
+
+ Readable.prototype.on = function (ev, fn) {
+ var res = EventEmitter$2.prototype.on.call(this, ev, fn);
+
+ if (ev === 'data') {
+ // Start flowing on next tick if stream isn't explicitly paused
+ if (this._readableState.flowing !== false) this.resume();
+ } else if (ev === 'readable') {
+ var state = this._readableState;
+
+ if (!state.endEmitted && !state.readableListening) {
+ state.readableListening = state.needReadable = true;
+ state.emittedReadable = false;
+
+ if (!state.reading) {
+ nextTick(nReadingNextTick, this);
+ } else if (state.length) {
+ emitReadable(this);
+ }
+ }
+ }
+
+ return res;
+ };
+
+ Readable.prototype.addListener = Readable.prototype.on;
+
+ function nReadingNextTick(self) {
+ debug$2('readable nexttick read 0');
+ self.read(0);
+ } // pause() and resume() are remnants of the legacy readable stream API
+ // If the user uses them, then switch into old mode.
+
+
+ Readable.prototype.resume = function () {
+ var state = this._readableState;
+
+ if (!state.flowing) {
+ debug$2('resume');
+ state.flowing = true;
+ resume(this, state);
+ }
+
+ return this;
+ };
+
+ function resume(stream, state) {
+ if (!state.resumeScheduled) {
+ state.resumeScheduled = true;
+ nextTick(resume_, stream, state);
+ }
+ }
+
+ function resume_(stream, state) {
+ if (!state.reading) {
+ debug$2('resume read 0');
+ stream.read(0);
+ }
+
+ state.resumeScheduled = false;
+ state.awaitDrain = 0;
+ stream.emit('resume');
+ flow(stream);
+ if (state.flowing && !state.reading) stream.read(0);
+ }
+
+ Readable.prototype.pause = function () {
+ debug$2('call pause flowing=%j', this._readableState.flowing);
+
+ if (false !== this._readableState.flowing) {
+ debug$2('pause');
+ this._readableState.flowing = false;
+ this.emit('pause');
+ }
+
+ return this;
+ };
+
+ function flow(stream) {
+ var state = stream._readableState;
+ debug$2('flow', state.flowing);
+
+ while (state.flowing && stream.read() !== null) {}
+ } // wrap an old-style stream as the async data source.
+ // This is *not* part of the readable stream interface.
+ // It is an ugly unfortunate mess of history.
+
+
+ Readable.prototype.wrap = function (stream) {
+ var state = this._readableState;
+ var paused = false;
+ var self = this;
+ stream.on('end', function () {
+ debug$2('wrapped end');
+
+ if (state.decoder && !state.ended) {
+ var chunk = state.decoder.end();
+ if (chunk && chunk.length) self.push(chunk);
+ }
+
+ self.push(null);
+ });
+ stream.on('data', function (chunk) {
+ debug$2('wrapped data');
+ if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
+
+ if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
+ var ret = self.push(chunk);
+
+ if (!ret) {
+ paused = true;
+ stream.pause();
+ }
+ }); // proxy all the other methods.
+ // important when wrapping filters and duplexes.
+
+ for (var i in stream) {
+ if (this[i] === undefined && typeof stream[i] === 'function') {
+ this[i] = function (method) {
+ return function () {
+ return stream[method].apply(stream, arguments);
+ };
+ }(i);
+ }
+ } // proxy certain important events.
+
+
+ var events = ['error', 'close', 'destroy', 'pause', 'resume'];
+ forEach(events, function (ev) {
+ stream.on(ev, self.emit.bind(self, ev));
+ }); // when we try to consume some more bytes, simply unpause the
+ // underlying stream.
+
+ self._read = function (n) {
+ debug$2('wrapped _read', n);
+
+ if (paused) {
+ paused = false;
+ stream.resume();
+ }
+ };
+
+ return self;
+ }; // exposed for testing purposes only.
+
+
+ Readable._fromList = fromList; // Pluck off n bytes from an array of buffers.
+ // Length is the combined lengths of all the buffers in the list.
+ // This function is designed to be inlinable, so please take care when making
+ // changes to the function body.
+
+ function fromList(n, state) {
+ // nothing buffered
+ if (state.length === 0) return null;
+ var ret;
+ if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
+ // read it all, truncate the list
+ if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
+ state.buffer.clear();
+ } else {
+ // read part of list
+ ret = fromListPartial(n, state.buffer, state.decoder);
+ }
+ return ret;
+ } // Extracts only enough buffered data to satisfy the amount requested.
+ // This function is designed to be inlinable, so please take care when making
+ // changes to the function body.
+
+
+ function fromListPartial(n, list, hasStrings) {
+ var ret;
+
+ if (n < list.head.data.length) {
+ // slice is the same for buffers and strings
+ ret = list.head.data.slice(0, n);
+ list.head.data = list.head.data.slice(n);
+ } else if (n === list.head.data.length) {
+ // first chunk is a perfect match
+ ret = list.shift();
+ } else {
+ // result spans more than one buffer
+ ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
+ }
+
+ return ret;
+ } // Copies a specified amount of characters from the list of buffered data
+ // chunks.
+ // This function is designed to be inlinable, so please take care when making
+ // changes to the function body.
+
+
+ function copyFromBufferString(n, list) {
+ var p = list.head;
+ var c = 1;
+ var ret = p.data;
+ n -= ret.length;
+
+ while (p = p.next) {
+ var str = p.data;
+ var nb = n > str.length ? str.length : n;
+ if (nb === str.length) ret += str;else ret += str.slice(0, n);
+ n -= nb;
+
+ if (n === 0) {
+ if (nb === str.length) {
+ ++c;
+ if (p.next) list.head = p.next;else list.head = list.tail = null;
+ } else {
+ list.head = p;
+ p.data = str.slice(nb);
+ }
+
+ break;
+ }
+
+ ++c;
+ }
+
+ list.length -= c;
+ return ret;
+ } // Copies a specified amount of bytes from the list of buffered data chunks.
+ // This function is designed to be inlinable, so please take care when making
+ // changes to the function body.
+
+
+ function copyFromBuffer(n, list) {
+ var ret = Buffer$1.allocUnsafe(n);
+ var p = list.head;
+ var c = 1;
+ p.data.copy(ret);
+ n -= p.data.length;
+
+ while (p = p.next) {
+ var buf = p.data;
+ var nb = n > buf.length ? buf.length : n;
+ buf.copy(ret, ret.length - n, 0, nb);
+ n -= nb;
+
+ if (n === 0) {
+ if (nb === buf.length) {
+ ++c;
+ if (p.next) list.head = p.next;else list.head = list.tail = null;
+ } else {
+ list.head = p;
+ p.data = buf.slice(nb);
+ }
+
+ break;
+ }
+
+ ++c;
+ }
+
+ list.length -= c;
+ return ret;
+ }
+
+ function endReadable(stream) {
+ var state = stream._readableState; // If we get here before consuming all the bytes, then that is a
+ // bug in node. Should never happen.
+
+ if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
+
+ if (!state.endEmitted) {
+ state.ended = true;
+ nextTick(endReadableNT, state, stream);
+ }
+ }
+
+ function endReadableNT(state, stream) {
+ // Check that we didn't get one last unshift.
+ if (!state.endEmitted && state.length === 0) {
+ state.endEmitted = true;
+ stream.readable = false;
+ stream.emit('end');
+ }
+ }
+
+ function forEach(xs, f) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ f(xs[i], i);
+ }
+ }
+
+ function indexOf(xs, x) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ if (xs[i] === x) return i;
+ }
+
+ return -1;
+ }
+
+ // A bit simpler than readable streams.
+ Writable.WritableState = WritableState;
+ inherits$3(Writable, EventEmitter$2);
+
+ function nop() {}
+
+ function WriteReq(chunk, encoding, cb) {
+ this.chunk = chunk;
+ this.encoding = encoding;
+ this.callback = cb;
+ this.next = null;
+ }
+
+ function WritableState(options, stream) {
+ Object.defineProperty(this, 'buffer', {
+ get: deprecate$1(function () {
+ return this.getBuffer();
+ }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
+ });
+ options = options || {}; // object stream flag to indicate whether or not this stream
+ // contains buffers or objects.
+
+ this.objectMode = !!options.objectMode;
+ if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
+ // Note: 0 is a valid value, means that we always return false if
+ // the entire buffer is not flushed immediately on write()
+
+ var hwm = options.highWaterMark;
+ var defaultHwm = this.objectMode ? 16 : 16 * 1024;
+ this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; // cast to ints.
+
+ this.highWaterMark = ~~this.highWaterMark;
+ this.needDrain = false; // at the start of calling end()
+
+ this.ending = false; // when end() has been called, and returned
+
+ this.ended = false; // when 'finish' is emitted
+
+ this.finished = false; // should we decode strings into buffers before passing to _write?
+ // this is here so that some node-core streams can optimize string
+ // handling at a lower level.
+
+ var noDecode = options.decodeStrings === false;
+ this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
+ // encoding is 'binary' so we have to make this configurable.
+ // Everything else in the universe uses 'utf8', though.
+
+ this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
+ // of how much we're waiting to get pushed to some underlying
+ // socket or file.
+
+ this.length = 0; // a flag to see when we're in the middle of a write.
+
+ this.writing = false; // when true all writes will be buffered until .uncork() call
+
+ this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
+ // or on a later tick. We set this to true at first, because any
+ // actions that shouldn't happen until "later" should generally also
+ // not happen before the first write call.
+
+ this.sync = true; // a flag to know if we're processing previously buffered items, which
+ // may call the _write() callback in the same tick, so that we don't
+ // end up in an overlapped onwrite situation.
+
+ this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
+
+ this.onwrite = function (er) {
+ onwrite(stream, er);
+ }; // the callback that the user supplies to write(chunk,encoding,cb)
+
+
+ this.writecb = null; // the amount that is being written when _write is called.
+
+ this.writelen = 0;
+ this.bufferedRequest = null;
+ this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
+ // this must be 0 before 'finish' can be emitted
+
+ this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
+ // This is relevant for synchronous Transform streams
+
+ this.prefinished = false; // True if the error was already emitted and should not be thrown again
+
+ this.errorEmitted = false; // count buffered requests
+
+ this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
+ // one allocated and free to use, and we maintain at most two
+
+ this.corkedRequestsFree = new CorkedRequest(this);
+ }
+
+ WritableState.prototype.getBuffer = function writableStateGetBuffer() {
+ var current = this.bufferedRequest;
+ var out = [];
+
+ while (current) {
+ out.push(current);
+ current = current.next;
+ }
+
+ return out;
+ };
+ function Writable(options) {
+ // Writable ctor is applied to Duplexes, though they're not
+ // instanceof Writable, they're instanceof Readable.
+ if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options);
+ this._writableState = new WritableState(options, this); // legacy.
+
+ this.writable = true;
+
+ if (options) {
+ if (typeof options.write === 'function') this._write = options.write;
+ if (typeof options.writev === 'function') this._writev = options.writev;
+ }
+
+ EventEmitter$2.call(this);
+ } // Otherwise people can pipe Writable streams, which is just wrong.
+
+ Writable.prototype.pipe = function () {
+ this.emit('error', new Error('Cannot pipe, not readable'));
+ };
+
+ function writeAfterEnd(stream, cb) {
+ var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb
+
+ stream.emit('error', er);
+ nextTick(cb, er);
+ } // If we get something that is not a buffer, string, null, or undefined,
+ // and we're not in objectMode, then that's an error.
+ // Otherwise stream chunks are all considered to be of length=1, and the
+ // watermarks determine how many objects to keep in the buffer, rather than
+ // how many bytes or characters.
+
+
+ function validChunk(stream, state, chunk, cb) {
+ var valid = true;
+ var er = false; // Always throw error if a null is written
+ // if we are not in object mode then throw
+ // if it is not a buffer, string, or undefined.
+
+ if (chunk === null) {
+ er = new TypeError('May not write null values to stream');
+ } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
+ er = new TypeError('Invalid non-string/buffer chunk');
+ }
+
+ if (er) {
+ stream.emit('error', er);
+ nextTick(cb, er);
+ valid = false;
+ }
+
+ return valid;
+ }
+
+ Writable.prototype.write = function (chunk, encoding, cb) {
+ var state = this._writableState;
+ var ret = false;
+
+ if (typeof encoding === 'function') {
+ cb = encoding;
+ encoding = null;
+ }
+
+ if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
+ if (typeof cb !== 'function') cb = nop;
+ if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) {
+ state.pendingcb++;
+ ret = writeOrBuffer(this, state, chunk, encoding, cb);
+ }
+ return ret;
+ };
+
+ Writable.prototype.cork = function () {
+ var state = this._writableState;
+ state.corked++;
+ };
+
+ Writable.prototype.uncork = function () {
+ var state = this._writableState;
+
+ if (state.corked) {
+ state.corked--;
+ if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
+ }
+ };
+
+ Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
+ // node::ParseEncoding() requires lower case.
+ if (typeof encoding === 'string') encoding = encoding.toLowerCase();
+ if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
+ this._writableState.defaultEncoding = encoding;
+ return this;
+ };
+
+ function decodeChunk(state, chunk, encoding) {
+ if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
+ chunk = Buffer.from(chunk, encoding);
+ }
+
+ return chunk;
+ } // if we're already writing something, then just put this
+ // in the queue, and wait our turn. Otherwise, call _write
+ // If we return false, then we need a drain event, so set that flag.
+
+
+ function writeOrBuffer(stream, state, chunk, encoding, cb) {
+ chunk = decodeChunk(state, chunk, encoding);
+ if (Buffer.isBuffer(chunk)) encoding = 'buffer';
+ var len = state.objectMode ? 1 : chunk.length;
+ state.length += len;
+ var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
+
+ if (!ret) state.needDrain = true;
+
+ if (state.writing || state.corked) {
+ var last = state.lastBufferedRequest;
+ state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
+
+ if (last) {
+ last.next = state.lastBufferedRequest;
+ } else {
+ state.bufferedRequest = state.lastBufferedRequest;
+ }
+
+ state.bufferedRequestCount += 1;
+ } else {
+ doWrite(stream, state, false, len, chunk, encoding, cb);
+ }
+
+ return ret;
+ }
+
+ function doWrite(stream, state, writev, len, chunk, encoding, cb) {
+ state.writelen = len;
+ state.writecb = cb;
+ state.writing = true;
+ state.sync = true;
+ if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
+ state.sync = false;
+ }
+
+ function onwriteError(stream, state, sync, er, cb) {
+ --state.pendingcb;
+ if (sync) nextTick(cb, er);else cb(er);
+ stream._writableState.errorEmitted = true;
+ stream.emit('error', er);
+ }
+
+ function onwriteStateUpdate(state) {
+ state.writing = false;
+ state.writecb = null;
+ state.length -= state.writelen;
+ state.writelen = 0;
+ }
+
+ function onwrite(stream, er) {
+ var state = stream._writableState;
+ var sync = state.sync;
+ var cb = state.writecb;
+ onwriteStateUpdate(state);
+ if (er) onwriteError(stream, state, sync, er, cb);else {
+ // Check if we're actually ready to finish, but don't emit yet
+ var finished = needFinish(state);
+
+ if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
+ clearBuffer(stream, state);
+ }
+
+ if (sync) {
+ /**/
+ nextTick(afterWrite, stream, state, finished, cb);
+ /* */
+ } else {
+ afterWrite(stream, state, finished, cb);
+ }
+ }
+ }
+
+ function afterWrite(stream, state, finished, cb) {
+ if (!finished) onwriteDrain(stream, state);
+ state.pendingcb--;
+ cb();
+ finishMaybe(stream, state);
+ } // Must force callback to be called on nextTick, so that we don't
+ // emit 'drain' before the write() consumer gets the 'false' return
+ // value, and has a chance to attach a 'drain' listener.
+
+
+ function onwriteDrain(stream, state) {
+ if (state.length === 0 && state.needDrain) {
+ state.needDrain = false;
+ stream.emit('drain');
+ }
+ } // if there's something in the buffer waiting, then process it
+
+
+ function clearBuffer(stream, state) {
+ state.bufferProcessing = true;
+ var entry = state.bufferedRequest;
+
+ if (stream._writev && entry && entry.next) {
+ // Fast case, write everything using _writev()
+ var l = state.bufferedRequestCount;
+ var buffer = new Array(l);
+ var holder = state.corkedRequestsFree;
+ holder.entry = entry;
+ var count = 0;
+
+ while (entry) {
+ buffer[count] = entry;
+ entry = entry.next;
+ count += 1;
+ }
+
+ doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
+ // as the hot path ends with doWrite
+
+ state.pendingcb++;
+ state.lastBufferedRequest = null;
+
+ if (holder.next) {
+ state.corkedRequestsFree = holder.next;
+ holder.next = null;
+ } else {
+ state.corkedRequestsFree = new CorkedRequest(state);
+ }
+ } else {
+ // Slow case, write chunks one-by-one
+ while (entry) {
+ var chunk = entry.chunk;
+ var encoding = entry.encoding;
+ var cb = entry.callback;
+ var len = state.objectMode ? 1 : chunk.length;
+ doWrite(stream, state, false, len, chunk, encoding, cb);
+ entry = entry.next; // if we didn't call the onwrite immediately, then
+ // it means that we need to wait until it does.
+ // also, that means that the chunk and cb are currently
+ // being processed, so move the buffer counter past them.
+
+ if (state.writing) {
+ break;
+ }
+ }
+
+ if (entry === null) state.lastBufferedRequest = null;
+ }
+
+ state.bufferedRequestCount = 0;
+ state.bufferedRequest = entry;
+ state.bufferProcessing = false;
+ }
+
+ Writable.prototype._write = function (chunk, encoding, cb) {
+ cb(new Error('not implemented'));
+ };
+
+ Writable.prototype._writev = null;
+
+ Writable.prototype.end = function (chunk, encoding, cb) {
+ var state = this._writableState;
+
+ if (typeof chunk === 'function') {
+ cb = chunk;
+ chunk = null;
+ encoding = null;
+ } else if (typeof encoding === 'function') {
+ cb = encoding;
+ encoding = null;
+ }
+
+ if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
+
+ if (state.corked) {
+ state.corked = 1;
+ this.uncork();
+ } // ignore unnecessary end() calls.
+
+
+ if (!state.ending && !state.finished) endWritable(this, state, cb);
+ };
+
+ function needFinish(state) {
+ return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
+ }
+
+ function prefinish(stream, state) {
+ if (!state.prefinished) {
+ state.prefinished = true;
+ stream.emit('prefinish');
+ }
+ }
+
+ function finishMaybe(stream, state) {
+ var need = needFinish(state);
+
+ if (need) {
+ if (state.pendingcb === 0) {
+ prefinish(stream, state);
+ state.finished = true;
+ stream.emit('finish');
+ } else {
+ prefinish(stream, state);
+ }
+ }
+
+ return need;
+ }
+
+ function endWritable(stream, state, cb) {
+ state.ending = true;
+ finishMaybe(stream, state);
+
+ if (cb) {
+ if (state.finished) nextTick(cb);else stream.once('finish', cb);
+ }
+
+ state.ended = true;
+ stream.writable = false;
+ } // It seems a linked list but it is not
+ // there will be only 2 of these for each stream
+
+
+ function CorkedRequest(state) {
+ var _this = this;
+
+ this.next = null;
+ this.entry = null;
+
+ this.finish = function (err) {
+ var entry = _this.entry;
+ _this.entry = null;
+
+ while (entry) {
+ var cb = entry.callback;
+ state.pendingcb--;
+ cb(err);
+ entry = entry.next;
+ }
+
+ if (state.corkedRequestsFree) {
+ state.corkedRequestsFree.next = _this;
+ } else {
+ state.corkedRequestsFree = _this;
+ }
+ };
+ }
+
+ inherits$3(Duplex, Readable);
+ var keys = Object.keys(Writable.prototype);
+
+ for (var v = 0; v < keys.length; v++) {
+ var method = keys[v];
+ if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
+ }
+ function Duplex(options) {
+ if (!(this instanceof Duplex)) return new Duplex(options);
+ Readable.call(this, options);
+ Writable.call(this, options);
+ if (options && options.readable === false) this.readable = false;
+ if (options && options.writable === false) this.writable = false;
+ this.allowHalfOpen = true;
+ if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
+ this.once('end', onend);
+ } // the no-half-open enforcer
+
+ function onend() {
+ // if we allow half-open state, or if the writable side ended,
+ // then we're ok.
+ if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written.
+ // But allow more writes to happen in this tick.
+
+ nextTick(onEndNT, this);
+ }
+
+ function onEndNT(self) {
+ self.end();
+ }
+
+ // a transform stream is a readable/writable stream where you do
+ inherits$3(Transform, Duplex);
+
+ function TransformState(stream) {
+ this.afterTransform = function (er, data) {
+ return afterTransform(stream, er, data);
+ };
+
+ this.needTransform = false;
+ this.transforming = false;
+ this.writecb = null;
+ this.writechunk = null;
+ this.writeencoding = null;
+ }
+
+ function afterTransform(stream, er, data) {
+ var ts = stream._transformState;
+ ts.transforming = false;
+ var cb = ts.writecb;
+ if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
+ ts.writechunk = null;
+ ts.writecb = null;
+ if (data !== null && data !== undefined) stream.push(data);
+ cb(er);
+ var rs = stream._readableState;
+ rs.reading = false;
+
+ if (rs.needReadable || rs.length < rs.highWaterMark) {
+ stream._read(rs.highWaterMark);
+ }
+ }
+ function Transform(options) {
+ if (!(this instanceof Transform)) return new Transform(options);
+ Duplex.call(this, options);
+ this._transformState = new TransformState(this); // when the writable side finishes, then flush out anything remaining.
+
+ var stream = this; // start out asking for a readable event once data is transformed.
+
+ this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
+ // that Readable wants before the first _read call, so unset the
+ // sync guard flag.
+
+ this._readableState.sync = false;
+
+ if (options) {
+ if (typeof options.transform === 'function') this._transform = options.transform;
+ if (typeof options.flush === 'function') this._flush = options.flush;
+ }
+
+ this.once('prefinish', function () {
+ if (typeof this._flush === 'function') this._flush(function (er) {
+ done(stream, er);
+ });else done(stream);
+ });
+ }
+
+ Transform.prototype.push = function (chunk, encoding) {
+ this._transformState.needTransform = false;
+ return Duplex.prototype.push.call(this, chunk, encoding);
+ }; // This is the part where you do stuff!
+ // override this function in implementation classes.
+ // 'chunk' is an input chunk.
+ //
+ // Call `push(newChunk)` to pass along transformed output
+ // to the readable side. You may call 'push' zero or more times.
+ //
+ // Call `cb(err)` when you are done with this chunk. If you pass
+ // an error, then that'll put the hurt on the whole operation. If you
+ // never call cb(), then you'll never get another chunk.
+
+
+ Transform.prototype._transform = function (chunk, encoding, cb) {
+ throw new Error('Not implemented');
+ };
+
+ Transform.prototype._write = function (chunk, encoding, cb) {
+ var ts = this._transformState;
+ ts.writecb = cb;
+ ts.writechunk = chunk;
+ ts.writeencoding = encoding;
+
+ if (!ts.transforming) {
+ var rs = this._readableState;
+ if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
+ }
+ }; // Doesn't matter what the args are here.
+ // _transform does all the work.
+ // That we got here means that the readable side wants more data.
+
+
+ Transform.prototype._read = function (n) {
+ var ts = this._transformState;
+
+ if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
+ ts.transforming = true;
+
+ this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
+ } else {
+ // mark that we need a transform, so that any data that comes in
+ // will get processed, now that we've asked for it.
+ ts.needTransform = true;
+ }
+ };
+
+ function done(stream, er) {
+ if (er) return stream.emit('error', er); // if there's nothing in the write buffer, then that means
+ // that nothing more will ever be provided
+
+ var ws = stream._writableState;
+ var ts = stream._transformState;
+ if (ws.length) throw new Error('Calling transform done when ws.length != 0');
+ if (ts.transforming) throw new Error('Calling transform done when still transforming');
+ return stream.push(null);
+ }
+
+ inherits$3(PassThrough, Transform);
+ function PassThrough(options) {
+ if (!(this instanceof PassThrough)) return new PassThrough(options);
+ Transform.call(this, options);
+ }
+
+ PassThrough.prototype._transform = function (chunk, encoding, cb) {
+ cb(null, chunk);
+ };
+
+ inherits$3(Stream, EventEmitter$2);
+ Stream.Readable = Readable;
+ Stream.Writable = Writable;
+ Stream.Duplex = Duplex;
+ Stream.Transform = Transform;
+ Stream.PassThrough = PassThrough; // Backwards-compat with node 0.4.x
+
+ Stream.Stream = Stream;
+ // part of this class) is overridden in the Readable class.
+
+ function Stream() {
+ EventEmitter$2.call(this);
+ }
+
+ Stream.prototype.pipe = function (dest, options) {
+ var source = this;
+
+ function ondata(chunk) {
+ if (dest.writable) {
+ if (false === dest.write(chunk) && source.pause) {
+ source.pause();
+ }
+ }
+ }
+
+ source.on('data', ondata);
+
+ function ondrain() {
+ if (source.readable && source.resume) {
+ source.resume();
+ }
+ }
+
+ dest.on('drain', ondrain); // If the 'end' option is not supplied, dest.end() will be called when
+ // source gets the 'end' or 'close' events. Only dest.end() once.
+
+ if (!dest._isStdio && (!options || options.end !== false)) {
+ source.on('end', onend);
+ source.on('close', onclose);
+ }
+
+ var didOnEnd = false;
+
+ function onend() {
+ if (didOnEnd) return;
+ didOnEnd = true;
+ dest.end();
+ }
+
+ function onclose() {
+ if (didOnEnd) return;
+ didOnEnd = true;
+ if (typeof dest.destroy === 'function') dest.destroy();
+ } // don't leave dangling pipes when there are errors.
+
+
+ function onerror(er) {
+ cleanup();
+
+ if (EventEmitter$2.listenerCount(this, 'error') === 0) {
+ throw er; // Unhandled stream error in pipe.
+ }
+ }
+
+ source.on('error', onerror);
+ dest.on('error', onerror); // remove all the event listeners that were added.
+
+ function cleanup() {
+ source.removeListener('data', ondata);
+ dest.removeListener('drain', ondrain);
+ source.removeListener('end', onend);
+ source.removeListener('close', onclose);
+ source.removeListener('error', onerror);
+ dest.removeListener('error', onerror);
+ source.removeListener('end', cleanup);
+ source.removeListener('close', cleanup);
+ dest.removeListener('close', cleanup);
+ }
+
+ source.on('end', cleanup);
+ source.on('close', cleanup);
+ dest.on('close', cleanup);
+ dest.emit('pipe', source); // Allow for unix-like usage: A.pipe(B).pipe(C)
+
+ return dest;
+ };
+
+ var WritableStream = Stream.Writable;
+ var inherits$1 = util.inherits;
+ var browserStdout = BrowserStdout;
+ inherits$1(BrowserStdout, WritableStream);
+
+ function BrowserStdout(opts) {
+ if (!(this instanceof BrowserStdout)) return new BrowserStdout(opts);
+ opts = opts || {};
+ WritableStream.call(this, opts);
+ this.label = opts.label !== undefined ? opts.label : 'stdout';
+ }
+
+ BrowserStdout.prototype._write = function (chunks, encoding, cb) {
+ var output = chunks.toString ? chunks.toString() : chunks;
+
+ if (this.label === false) {
+ console.log(output);
+ } else {
+ console.log(this.label + ':', output);
+ }
+
+ nextTick$1(cb);
+ };
+
+ var parseQuery = function parseQuery(qs) {
+ return qs.replace('?', '').split('&').reduce(function (obj, pair) {
+ var i = pair.indexOf('=');
+ var key = pair.slice(0, i);
+ var val = pair.slice(++i); // Due to how the URLSearchParams API treats spaces
+
+ obj[key] = decodeURIComponent(val.replace(/\+/g, '%20'));
+ return obj;
+ }, {});
+ };
+
+ function highlight(js) {
+ return js.replace(//g, '>').replace(/\/\/(.*)/gm, '').replace(/('.*?')/gm, '$1 ').replace(/(\d+\.\d+)/gm, '$1 ').replace(/(\d+)/gm, '$1 ').replace(/\bnew[ \t]+(\w+)/gm, 'new $1 ').replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1 ');
+ }
+ /**
+ * Highlight the contents of tag `name`.
+ *
+ * @private
+ * @param {string} name
+ */
+
+
+ var highlightTags = function highlightTags(name) {
+ var code = document.getElementById('mocha').getElementsByTagName(name);
+
+ for (var i = 0, len = code.length; i < len; ++i) {
+ code[i].innerHTML = highlight(code[i].innerHTML);
+ }
+ };
+
+ // `Symbol.iterator` well-known symbol
+ // https://tc39.es/ecma262/#sec-symbol.iterator
+ defineWellKnownSymbol('iterator');
+
+ var charAt = stringMultibyte.charAt;
+
+
+
+
+ var STRING_ITERATOR = 'String Iterator';
+ var setInternalState$2 = internalState.set;
+ var getInternalState$1 = internalState.getterFor(STRING_ITERATOR);
+
+ // `String.prototype[@@iterator]` method
+ // https://tc39.es/ecma262/#sec-string.prototype-@@iterator
+ defineIterator(String, 'String', function (iterated) {
+ setInternalState$2(this, {
+ type: STRING_ITERATOR,
+ string: toString_1(iterated),
+ index: 0
+ });
+ // `%StringIteratorPrototype%.next` method
+ // https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next
+ }, function next() {
+ var state = getInternalState$1(this);
+ var string = state.string;
+ var index = state.index;
+ var point;
+ if (index >= string.length) return { value: undefined, done: true };
+ point = charAt(string, index);
+ state.index += point.length;
+ return { value: point, done: false };
+ });
+
+ var ITERATOR = wellKnownSymbol('iterator');
+ var TO_STRING_TAG = wellKnownSymbol('toStringTag');
+ var ArrayValues = es_array_iterator.values;
+
+ var handlePrototype = function (CollectionPrototype, COLLECTION_NAME) {
+ if (CollectionPrototype) {
+ // some Chrome versions have non-configurable methods on DOMTokenList
+ if (CollectionPrototype[ITERATOR] !== ArrayValues) try {
+ createNonEnumerableProperty(CollectionPrototype, ITERATOR, ArrayValues);
+ } catch (error) {
+ CollectionPrototype[ITERATOR] = ArrayValues;
+ }
+ if (!CollectionPrototype[TO_STRING_TAG]) {
+ createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG, COLLECTION_NAME);
+ }
+ if (domIterables[COLLECTION_NAME]) for (var METHOD_NAME in es_array_iterator) {
+ // some Chrome versions have non-configurable methods on DOMTokenList
+ if (CollectionPrototype[METHOD_NAME] !== es_array_iterator[METHOD_NAME]) try {
+ createNonEnumerableProperty(CollectionPrototype, METHOD_NAME, es_array_iterator[METHOD_NAME]);
+ } catch (error) {
+ CollectionPrototype[METHOD_NAME] = es_array_iterator[METHOD_NAME];
+ }
+ }
+ }
+ };
+
+ for (var COLLECTION_NAME in domIterables) {
+ handlePrototype(global_1[COLLECTION_NAME] && global_1[COLLECTION_NAME].prototype, COLLECTION_NAME);
+ }
+
+ handlePrototype(domTokenListPrototype, 'DOMTokenList');
+
+ // `Symbol.asyncIterator` well-known symbol
+ // https://tc39.es/ecma262/#sec-symbol.asynciterator
+ defineWellKnownSymbol('asyncIterator');
+
+ // `Symbol.toStringTag` well-known symbol
+ // https://tc39.es/ecma262/#sec-symbol.tostringtag
+ defineWellKnownSymbol('toStringTag');
+
+ // JSON[@@toStringTag] property
+ // https://tc39.es/ecma262/#sec-json-@@tostringtag
+ setToStringTag(global_1.JSON, 'JSON', true);
+
+ // Math[@@toStringTag] property
+ // https://tc39.es/ecma262/#sec-math-@@tostringtag
+ setToStringTag(Math, 'Math', true);
+
+ var nativePromiseConstructor = global_1.Promise;
+
+ var iteratorClose = function (iterator, kind, value) {
+ var innerResult, innerError;
+ anObject(iterator);
+ try {
+ innerResult = getMethod(iterator, 'return');
+ if (!innerResult) {
+ if (kind === 'throw') throw value;
+ return value;
+ }
+ innerResult = innerResult.call(iterator);
+ } catch (error) {
+ innerError = true;
+ innerResult = error;
+ }
+ if (kind === 'throw') throw value;
+ if (innerError) throw innerResult;
+ anObject(innerResult);
+ return value;
+ };
+
+ var Result = function (stopped, result) {
+ this.stopped = stopped;
+ this.result = result;
+ };
+
+ var iterate = function (iterable, unboundFunction, options) {
+ var that = options && options.that;
+ var AS_ENTRIES = !!(options && options.AS_ENTRIES);
+ var IS_ITERATOR = !!(options && options.IS_ITERATOR);
+ var INTERRUPTED = !!(options && options.INTERRUPTED);
+ var fn = functionBindContext(unboundFunction, that, 1 + AS_ENTRIES + INTERRUPTED);
+ var iterator, iterFn, index, length, result, next, step;
+
+ var stop = function (condition) {
+ if (iterator) iteratorClose(iterator, 'normal', condition);
+ return new Result(true, condition);
+ };
+
+ var callFn = function (value) {
+ if (AS_ENTRIES) {
+ anObject(value);
+ return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
+ } return INTERRUPTED ? fn(value, stop) : fn(value);
+ };
+
+ if (IS_ITERATOR) {
+ iterator = iterable;
+ } else {
+ iterFn = getIteratorMethod(iterable);
+ if (!iterFn) throw TypeError(String(iterable) + ' is not iterable');
+ // optimisation for array iterators
+ if (isArrayIteratorMethod(iterFn)) {
+ for (index = 0, length = toLength(iterable.length); length > index; index++) {
+ result = callFn(iterable[index]);
+ if (result && result instanceof Result) return result;
+ } return new Result(false);
+ }
+ iterator = getIterator(iterable, iterFn);
+ }
+
+ next = iterator.next;
+ while (!(step = next.call(iterator)).done) {
+ try {
+ result = callFn(step.value);
+ } catch (error) {
+ iteratorClose(iterator, 'throw', error);
+ }
+ if (typeof result == 'object' && result && result instanceof Result) return result;
+ } return new Result(false);
+ };
+
+ var engineIsIos = /(?:ipad|iphone|ipod).*applewebkit/i.test(engineUserAgent);
+
+ var engineIsNode = classofRaw(global_1.process) == 'process';
+
+ var set = global_1.setImmediate;
+ var clear = global_1.clearImmediate;
+ var process$2 = global_1.process;
+ var MessageChannel = global_1.MessageChannel;
+ var Dispatch = global_1.Dispatch;
+ var counter = 0;
+ var queue = {};
+ var ONREADYSTATECHANGE = 'onreadystatechange';
+ var location$1, defer, channel, port;
+
+ try {
+ // Deno throws a ReferenceError on `location` access without `--location` flag
+ location$1 = global_1.location;
+ } catch (error) { /* empty */ }
+
+ var run = function (id) {
+ // eslint-disable-next-line no-prototype-builtins -- safe
+ if (queue.hasOwnProperty(id)) {
+ var fn = queue[id];
+ delete queue[id];
+ fn();
+ }
+ };
+
+ var runner$1 = function (id) {
+ return function () {
+ run(id);
+ };
+ };
+
+ var listener = function (event) {
+ run(event.data);
+ };
+
+ var post = function (id) {
+ // old engines have not location.origin
+ global_1.postMessage(String(id), location$1.protocol + '//' + location$1.host);
+ };
+
+ // Node.js 0.9+ & IE10+ has setImmediate, otherwise:
+ if (!set || !clear) {
+ set = function setImmediate(fn) {
+ var args = [];
+ var argumentsLength = arguments.length;
+ var i = 1;
+ while (argumentsLength > i) args.push(arguments[i++]);
+ queue[++counter] = function () {
+ // eslint-disable-next-line no-new-func -- spec requirement
+ (isCallable(fn) ? fn : Function(fn)).apply(undefined, args);
+ };
+ defer(counter);
+ return counter;
+ };
+ clear = function clearImmediate(id) {
+ delete queue[id];
+ };
+ // Node.js 0.8-
+ if (engineIsNode) {
+ defer = function (id) {
+ process$2.nextTick(runner$1(id));
+ };
+ // Sphere (JS game engine) Dispatch API
+ } else if (Dispatch && Dispatch.now) {
+ defer = function (id) {
+ Dispatch.now(runner$1(id));
+ };
+ // Browsers with MessageChannel, includes WebWorkers
+ // except iOS - https://github.com/zloirock/core-js/issues/624
+ } else if (MessageChannel && !engineIsIos) {
+ channel = new MessageChannel();
+ port = channel.port2;
+ channel.port1.onmessage = listener;
+ defer = functionBindContext(port.postMessage, port, 1);
+ // Browsers with postMessage, skip WebWorkers
+ // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
+ } else if (
+ global_1.addEventListener &&
+ isCallable(global_1.postMessage) &&
+ !global_1.importScripts &&
+ location$1 && location$1.protocol !== 'file:' &&
+ !fails(post)
+ ) {
+ defer = post;
+ global_1.addEventListener('message', listener, false);
+ // IE8-
+ } else if (ONREADYSTATECHANGE in documentCreateElement('script')) {
+ defer = function (id) {
+ html$1.appendChild(documentCreateElement('script'))[ONREADYSTATECHANGE] = function () {
+ html$1.removeChild(this);
+ run(id);
+ };
+ };
+ // Rest old browsers
+ } else {
+ defer = function (id) {
+ setTimeout(runner$1(id), 0);
+ };
+ }
+ }
+
+ var task$1 = {
+ set: set,
+ clear: clear
+ };
+
+ var engineIsIosPebble = /ipad|iphone|ipod/i.test(engineUserAgent) && global_1.Pebble !== undefined;
+
+ var engineIsWebosWebkit = /web0s(?!.*chrome)/i.test(engineUserAgent);
+
+ var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
+ var macrotask = task$1.set;
+
+
+
+
+
+ var MutationObserver = global_1.MutationObserver || global_1.WebKitMutationObserver;
+ var document$2 = global_1.document;
+ var process$1 = global_1.process;
+ var Promise$1 = global_1.Promise;
+ // Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`
+ var queueMicrotaskDescriptor = getOwnPropertyDescriptor(global_1, 'queueMicrotask');
+ var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value;
+
+ var flush, head, last, notify$2, toggle, node, promise, then;
+
+ // modern engines have queueMicrotask method
+ if (!queueMicrotask) {
+ flush = function () {
+ var parent, fn;
+ if (engineIsNode && (parent = process$1.domain)) parent.exit();
+ while (head) {
+ fn = head.fn;
+ head = head.next;
+ try {
+ fn();
+ } catch (error) {
+ if (head) notify$2();
+ else last = undefined;
+ throw error;
+ }
+ } last = undefined;
+ if (parent) parent.enter();
+ };
+
+ // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339
+ // also except WebOS Webkit https://github.com/zloirock/core-js/issues/898
+ if (!engineIsIos && !engineIsNode && !engineIsWebosWebkit && MutationObserver && document$2) {
+ toggle = true;
+ node = document$2.createTextNode('');
+ new MutationObserver(flush).observe(node, { characterData: true });
+ notify$2 = function () {
+ node.data = toggle = !toggle;
+ };
+ // environments with maybe non-completely correct, but existent Promise
+ } else if (!engineIsIosPebble && Promise$1 && Promise$1.resolve) {
+ // Promise.resolve without an argument throws an error in LG WebOS 2
+ promise = Promise$1.resolve(undefined);
+ // workaround of WebKit ~ iOS Safari 10.1 bug
+ promise.constructor = Promise$1;
+ then = promise.then;
+ notify$2 = function () {
+ then.call(promise, flush);
+ };
+ // Node.js without promises
+ } else if (engineIsNode) {
+ notify$2 = function () {
+ process$1.nextTick(flush);
+ };
+ // for other environments - macrotask based on:
+ // - setImmediate
+ // - MessageChannel
+ // - window.postMessag
+ // - onreadystatechange
+ // - setTimeout
+ } else {
+ notify$2 = function () {
+ // strange IE + webpack dev server bug - use .call(global)
+ macrotask.call(global_1, flush);
+ };
+ }
+ }
+
+ var microtask = queueMicrotask || function (fn) {
+ var task = { fn: fn, next: undefined };
+ if (last) last.next = task;
+ if (!head) {
+ head = task;
+ notify$2();
+ } last = task;
+ };
+
+ var PromiseCapability = function (C) {
+ var resolve, reject;
+ this.promise = new C(function ($$resolve, $$reject) {
+ if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
+ resolve = $$resolve;
+ reject = $$reject;
+ });
+ this.resolve = aCallable(resolve);
+ this.reject = aCallable(reject);
+ };
+
+ // `NewPromiseCapability` abstract operation
+ // https://tc39.es/ecma262/#sec-newpromisecapability
+ var f = function (C) {
+ return new PromiseCapability(C);
+ };
+
+ var newPromiseCapability$1 = {
+ f: f
+ };
+
+ var promiseResolve = function (C, x) {
+ anObject(C);
+ if (isObject$1(x) && x.constructor === C) return x;
+ var promiseCapability = newPromiseCapability$1.f(C);
+ var resolve = promiseCapability.resolve;
+ resolve(x);
+ return promiseCapability.promise;
+ };
+
+ var hostReportErrors = function (a, b) {
+ var console = global_1.console;
+ if (console && console.error) {
+ arguments.length === 1 ? console.error(a) : console.error(a, b);
+ }
+ };
+
+ var perform = function (exec) {
+ try {
+ return { error: false, value: exec() };
+ } catch (error) {
+ return { error: true, value: error };
+ }
+ };
+
+ var engineIsBrowser = typeof window == 'object';
+
+ var task = task$1.set;
+
+
+
+
+
+
+
+
+
+
+
+
+ var SPECIES = wellKnownSymbol('species');
+ var PROMISE = 'Promise';
+ var getInternalState = internalState.get;
+ var setInternalState$1 = internalState.set;
+ var getInternalPromiseState = internalState.getterFor(PROMISE);
+ var NativePromisePrototype = nativePromiseConstructor && nativePromiseConstructor.prototype;
+ var PromiseConstructor = nativePromiseConstructor;
+ var PromiseConstructorPrototype = NativePromisePrototype;
+ var TypeError$1 = global_1.TypeError;
+ var document$1 = global_1.document;
+ var process = global_1.process;
+ var newPromiseCapability = newPromiseCapability$1.f;
+ var newGenericPromiseCapability = newPromiseCapability;
+ var DISPATCH_EVENT = !!(document$1 && document$1.createEvent && global_1.dispatchEvent);
+ var NATIVE_REJECTION_EVENT = isCallable(global_1.PromiseRejectionEvent);
+ var UNHANDLED_REJECTION = 'unhandledrejection';
+ var REJECTION_HANDLED = 'rejectionhandled';
+ var PENDING = 0;
+ var FULFILLED = 1;
+ var REJECTED = 2;
+ var HANDLED = 1;
+ var UNHANDLED = 2;
+ var SUBCLASSING = false;
+ var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen;
+
+ var FORCED$2 = isForced_1(PROMISE, function () {
+ var PROMISE_CONSTRUCTOR_SOURCE = inspectSource(PromiseConstructor);
+ var GLOBAL_CORE_JS_PROMISE = PROMISE_CONSTRUCTOR_SOURCE !== String(PromiseConstructor);
+ // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
+ // https://bugs.chromium.org/p/chromium/issues/detail?id=830565
+ // We can't detect it synchronously, so just check versions
+ if (!GLOBAL_CORE_JS_PROMISE && engineV8Version === 66) return true;
+ // We can't use @@species feature detection in V8 since it causes
+ // deoptimization and performance degradation
+ // https://github.com/zloirock/core-js/issues/679
+ if (engineV8Version >= 51 && /native code/.test(PROMISE_CONSTRUCTOR_SOURCE)) return false;
+ // Detect correctness of subclassing with @@species support
+ var promise = new PromiseConstructor(function (resolve) { resolve(1); });
+ var FakePromise = function (exec) {
+ exec(function () { /* empty */ }, function () { /* empty */ });
+ };
+ var constructor = promise.constructor = {};
+ constructor[SPECIES] = FakePromise;
+ SUBCLASSING = promise.then(function () { /* empty */ }) instanceof FakePromise;
+ if (!SUBCLASSING) return true;
+ // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test
+ return !GLOBAL_CORE_JS_PROMISE && engineIsBrowser && !NATIVE_REJECTION_EVENT;
+ });
+
+ var INCORRECT_ITERATION$1 = FORCED$2 || !checkCorrectnessOfIteration(function (iterable) {
+ PromiseConstructor.all(iterable)['catch'](function () { /* empty */ });
+ });
+
+ // helpers
+ var isThenable = function (it) {
+ var then;
+ return isObject$1(it) && isCallable(then = it.then) ? then : false;
+ };
+
+ var notify$1 = function (state, isReject) {
+ if (state.notified) return;
+ state.notified = true;
+ var chain = state.reactions;
+ microtask(function () {
+ var value = state.value;
+ var ok = state.state == FULFILLED;
+ var index = 0;
+ // variable length - can't use forEach
+ while (chain.length > index) {
+ var reaction = chain[index++];
+ var handler = ok ? reaction.ok : reaction.fail;
+ var resolve = reaction.resolve;
+ var reject = reaction.reject;
+ var domain = reaction.domain;
+ var result, then, exited;
+ try {
+ if (handler) {
+ if (!ok) {
+ if (state.rejection === UNHANDLED) onHandleUnhandled(state);
+ state.rejection = HANDLED;
+ }
+ if (handler === true) result = value;
+ else {
+ if (domain) domain.enter();
+ result = handler(value); // can throw
+ if (domain) {
+ domain.exit();
+ exited = true;
+ }
+ }
+ if (result === reaction.promise) {
+ reject(TypeError$1('Promise-chain cycle'));
+ } else if (then = isThenable(result)) {
+ then.call(result, resolve, reject);
+ } else resolve(result);
+ } else reject(value);
+ } catch (error) {
+ if (domain && !exited) domain.exit();
+ reject(error);
+ }
+ }
+ state.reactions = [];
+ state.notified = false;
+ if (isReject && !state.rejection) onUnhandled(state);
+ });
+ };
+
+ var dispatchEvent = function (name, promise, reason) {
+ var event, handler;
+ if (DISPATCH_EVENT) {
+ event = document$1.createEvent('Event');
+ event.promise = promise;
+ event.reason = reason;
+ event.initEvent(name, false, true);
+ global_1.dispatchEvent(event);
+ } else event = { promise: promise, reason: reason };
+ if (!NATIVE_REJECTION_EVENT && (handler = global_1['on' + name])) handler(event);
+ else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason);
+ };
+
+ var onUnhandled = function (state) {
+ task.call(global_1, function () {
+ var promise = state.facade;
+ var value = state.value;
+ var IS_UNHANDLED = isUnhandled(state);
+ var result;
+ if (IS_UNHANDLED) {
+ result = perform(function () {
+ if (engineIsNode) {
+ process.emit('unhandledRejection', value, promise);
+ } else dispatchEvent(UNHANDLED_REJECTION, promise, value);
+ });
+ // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
+ state.rejection = engineIsNode || isUnhandled(state) ? UNHANDLED : HANDLED;
+ if (result.error) throw result.value;
+ }
+ });
+ };
+
+ var isUnhandled = function (state) {
+ return state.rejection !== HANDLED && !state.parent;
+ };
+
+ var onHandleUnhandled = function (state) {
+ task.call(global_1, function () {
+ var promise = state.facade;
+ if (engineIsNode) {
+ process.emit('rejectionHandled', promise);
+ } else dispatchEvent(REJECTION_HANDLED, promise, state.value);
+ });
+ };
+
+ var bind = function (fn, state, unwrap) {
+ return function (value) {
+ fn(state, value, unwrap);
+ };
+ };
+
+ var internalReject = function (state, value, unwrap) {
+ if (state.done) return;
+ state.done = true;
+ if (unwrap) state = unwrap;
+ state.value = value;
+ state.state = REJECTED;
+ notify$1(state, true);
+ };
+
+ var internalResolve = function (state, value, unwrap) {
+ if (state.done) return;
+ state.done = true;
+ if (unwrap) state = unwrap;
+ try {
+ if (state.facade === value) throw TypeError$1("Promise can't be resolved itself");
+ var then = isThenable(value);
+ if (then) {
+ microtask(function () {
+ var wrapper = { done: false };
+ try {
+ then.call(value,
+ bind(internalResolve, wrapper, state),
+ bind(internalReject, wrapper, state)
+ );
+ } catch (error) {
+ internalReject(wrapper, error, state);
+ }
+ });
+ } else {
+ state.value = value;
+ state.state = FULFILLED;
+ notify$1(state, false);
+ }
+ } catch (error) {
+ internalReject({ done: false }, error, state);
+ }
+ };
+
+ // constructor polyfill
+ if (FORCED$2) {
+ // 25.4.3.1 Promise(executor)
+ PromiseConstructor = function Promise(executor) {
+ anInstance(this, PromiseConstructor, PROMISE);
+ aCallable(executor);
+ Internal.call(this);
+ var state = getInternalState(this);
+ try {
+ executor(bind(internalResolve, state), bind(internalReject, state));
+ } catch (error) {
+ internalReject(state, error);
+ }
+ };
+ PromiseConstructorPrototype = PromiseConstructor.prototype;
+ // eslint-disable-next-line no-unused-vars -- required for `.length`
+ Internal = function Promise(executor) {
+ setInternalState$1(this, {
+ type: PROMISE,
+ done: false,
+ notified: false,
+ parent: false,
+ reactions: [],
+ rejection: false,
+ state: PENDING,
+ value: undefined
+ });
+ };
+ Internal.prototype = redefineAll(PromiseConstructorPrototype, {
+ // `Promise.prototype.then` method
+ // https://tc39.es/ecma262/#sec-promise.prototype.then
+ then: function then(onFulfilled, onRejected) {
+ var state = getInternalPromiseState(this);
+ var reaction = newPromiseCapability(speciesConstructor(this, PromiseConstructor));
+ reaction.ok = isCallable(onFulfilled) ? onFulfilled : true;
+ reaction.fail = isCallable(onRejected) && onRejected;
+ reaction.domain = engineIsNode ? process.domain : undefined;
+ state.parent = true;
+ state.reactions.push(reaction);
+ if (state.state != PENDING) notify$1(state, false);
+ return reaction.promise;
+ },
+ // `Promise.prototype.catch` method
+ // https://tc39.es/ecma262/#sec-promise.prototype.catch
+ 'catch': function (onRejected) {
+ return this.then(undefined, onRejected);
+ }
+ });
+ OwnPromiseCapability = function () {
+ var promise = new Internal();
+ var state = getInternalState(promise);
+ this.promise = promise;
+ this.resolve = bind(internalResolve, state);
+ this.reject = bind(internalReject, state);
+ };
+ newPromiseCapability$1.f = newPromiseCapability = function (C) {
+ return C === PromiseConstructor || C === PromiseWrapper
+ ? new OwnPromiseCapability(C)
+ : newGenericPromiseCapability(C);
+ };
+
+ if (isCallable(nativePromiseConstructor) && NativePromisePrototype !== Object.prototype) {
+ nativeThen = NativePromisePrototype.then;
+
+ if (!SUBCLASSING) {
+ // make `Promise#then` return a polyfilled `Promise` for native promise-based APIs
+ redefine(NativePromisePrototype, 'then', function then(onFulfilled, onRejected) {
+ var that = this;
+ return new PromiseConstructor(function (resolve, reject) {
+ nativeThen.call(that, resolve, reject);
+ }).then(onFulfilled, onRejected);
+ // https://github.com/zloirock/core-js/issues/640
+ }, { unsafe: true });
+
+ // makes sure that native promise-based APIs `Promise#catch` properly works with patched `Promise#then`
+ redefine(NativePromisePrototype, 'catch', PromiseConstructorPrototype['catch'], { unsafe: true });
+ }
+
+ // make `.constructor === Promise` work for native promise-based APIs
+ try {
+ delete NativePromisePrototype.constructor;
+ } catch (error) { /* empty */ }
+
+ // make `instanceof Promise` work for native promise-based APIs
+ if (objectSetPrototypeOf) {
+ objectSetPrototypeOf(NativePromisePrototype, PromiseConstructorPrototype);
+ }
+ }
+ }
+
+ _export({ global: true, wrap: true, forced: FORCED$2 }, {
+ Promise: PromiseConstructor
+ });
+
+ setToStringTag(PromiseConstructor, PROMISE, false);
+ setSpecies(PROMISE);
+
+ PromiseWrapper = getBuiltIn(PROMISE);
+
+ // statics
+ _export({ target: PROMISE, stat: true, forced: FORCED$2 }, {
+ // `Promise.reject` method
+ // https://tc39.es/ecma262/#sec-promise.reject
+ reject: function reject(r) {
+ var capability = newPromiseCapability(this);
+ capability.reject.call(undefined, r);
+ return capability.promise;
+ }
+ });
+
+ _export({ target: PROMISE, stat: true, forced: FORCED$2 }, {
+ // `Promise.resolve` method
+ // https://tc39.es/ecma262/#sec-promise.resolve
+ resolve: function resolve(x) {
+ return promiseResolve(this, x);
+ }
+ });
+
+ _export({ target: PROMISE, stat: true, forced: INCORRECT_ITERATION$1 }, {
+ // `Promise.all` method
+ // https://tc39.es/ecma262/#sec-promise.all
+ all: function all(iterable) {
+ var C = this;
+ var capability = newPromiseCapability(C);
+ var resolve = capability.resolve;
+ var reject = capability.reject;
+ var result = perform(function () {
+ var $promiseResolve = aCallable(C.resolve);
+ var values = [];
+ var counter = 0;
+ var remaining = 1;
+ iterate(iterable, function (promise) {
+ var index = counter++;
+ var alreadyCalled = false;
+ values.push(undefined);
+ remaining++;
+ $promiseResolve.call(C, promise).then(function (value) {
+ if (alreadyCalled) return;
+ alreadyCalled = true;
+ values[index] = value;
+ --remaining || resolve(values);
+ }, reject);
+ });
+ --remaining || resolve(values);
+ });
+ if (result.error) reject(result.value);
+ return capability.promise;
+ },
+ // `Promise.race` method
+ // https://tc39.es/ecma262/#sec-promise.race
+ race: function race(iterable) {
+ var C = this;
+ var capability = newPromiseCapability(C);
+ var reject = capability.reject;
+ var result = perform(function () {
+ var $promiseResolve = aCallable(C.resolve);
+ iterate(iterable, function (promise) {
+ $promiseResolve.call(C, promise).then(capability.resolve, reject);
+ });
+ });
+ if (result.error) reject(result.value);
+ return capability.promise;
+ }
+ });
+
+ createCommonjsModule(function (module) {
+ /**
+ * Copyright (c) 2014-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+ var runtime = function (exports) {
+
+ var Op = Object.prototype;
+ var hasOwn = Op.hasOwnProperty;
+ var undefined$1; // More compressible than void 0.
+
+ var $Symbol = typeof Symbol === "function" ? Symbol : {};
+ var iteratorSymbol = $Symbol.iterator || "@@iterator";
+ var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
+ var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
+
+ function define(obj, key, value) {
+ Object.defineProperty(obj, key, {
+ value: value,
+ enumerable: true,
+ configurable: true,
+ writable: true
+ });
+ return obj[key];
+ }
+
+ try {
+ // IE 8 has a broken Object.defineProperty that only works on DOM objects.
+ define({}, "");
+ } catch (err) {
+ define = function define(obj, key, value) {
+ return obj[key] = value;
+ };
+ }
+
+ function wrap(innerFn, outerFn, self, tryLocsList) {
+ // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
+ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
+ var generator = Object.create(protoGenerator.prototype);
+ var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next,
+ // .throw, and .return methods.
+
+ generator._invoke = makeInvokeMethod(innerFn, self, context);
+ return generator;
+ }
+
+ exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion
+ // record like context.tryEntries[i].completion. This interface could
+ // have been (and was previously) designed to take a closure to be
+ // invoked without arguments, but in all the cases we care about we
+ // already have an existing method we want to call, so there's no need
+ // to create a new function object. We can even get away with assuming
+ // the method takes exactly one argument, since that happens to be true
+ // in every case, so we don't have to touch the arguments object. The
+ // only additional allocation required is the completion record, which
+ // has a stable shape and so hopefully should be cheap to allocate.
+
+ function tryCatch(fn, obj, arg) {
+ try {
+ return {
+ type: "normal",
+ arg: fn.call(obj, arg)
+ };
+ } catch (err) {
+ return {
+ type: "throw",
+ arg: err
+ };
+ }
+ }
+
+ var GenStateSuspendedStart = "suspendedStart";
+ var GenStateSuspendedYield = "suspendedYield";
+ var GenStateExecuting = "executing";
+ var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as
+ // breaking out of the dispatch switch statement.
+
+ var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and
+ // .constructor.prototype properties for functions that return Generator
+ // objects. For full spec compliance, you may wish to configure your
+ // minifier not to mangle the names of these two functions.
+
+ function Generator() {}
+
+ function GeneratorFunction() {}
+
+ function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that
+ // don't natively support it.
+
+
+ var IteratorPrototype = {};
+
+ IteratorPrototype[iteratorSymbol] = function () {
+ return this;
+ };
+
+ var getProto = Object.getPrototypeOf;
+ var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
+
+ if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
+ // This environment has a native %IteratorPrototype%; use it instead
+ // of the polyfill.
+ IteratorPrototype = NativeIteratorPrototype;
+ }
+
+ var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
+ GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
+ GeneratorFunctionPrototype.constructor = GeneratorFunction;
+ GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"); // Helper for defining the .next, .throw, and .return methods of the
+ // Iterator interface in terms of a single ._invoke method.
+
+ function defineIteratorMethods(prototype) {
+ ["next", "throw", "return"].forEach(function (method) {
+ define(prototype, method, function (arg) {
+ return this._invoke(method, arg);
+ });
+ });
+ }
+
+ exports.isGeneratorFunction = function (genFun) {
+ var ctor = typeof genFun === "function" && genFun.constructor;
+ return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can
+ // do is to check its .name property.
+ (ctor.displayName || ctor.name) === "GeneratorFunction" : false;
+ };
+
+ exports.mark = function (genFun) {
+ if (Object.setPrototypeOf) {
+ Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
+ } else {
+ genFun.__proto__ = GeneratorFunctionPrototype;
+ define(genFun, toStringTagSymbol, "GeneratorFunction");
+ }
+
+ genFun.prototype = Object.create(Gp);
+ return genFun;
+ }; // Within the body of any async function, `await x` is transformed to
+ // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
+ // `hasOwn.call(value, "__await")` to determine if the yielded value is
+ // meant to be awaited.
+
+
+ exports.awrap = function (arg) {
+ return {
+ __await: arg
+ };
+ };
+
+ function AsyncIterator(generator, PromiseImpl) {
+ function invoke(method, arg, resolve, reject) {
+ var record = tryCatch(generator[method], generator, arg);
+
+ if (record.type === "throw") {
+ reject(record.arg);
+ } else {
+ var result = record.arg;
+ var value = result.value;
+
+ if (value && _typeof(value) === "object" && hasOwn.call(value, "__await")) {
+ return PromiseImpl.resolve(value.__await).then(function (value) {
+ invoke("next", value, resolve, reject);
+ }, function (err) {
+ invoke("throw", err, resolve, reject);
+ });
+ }
+
+ return PromiseImpl.resolve(value).then(function (unwrapped) {
+ // When a yielded Promise is resolved, its final value becomes
+ // the .value of the Promise<{value,done}> result for the
+ // current iteration.
+ result.value = unwrapped;
+ resolve(result);
+ }, function (error) {
+ // If a rejected Promise was yielded, throw the rejection back
+ // into the async generator function so it can be handled there.
+ return invoke("throw", error, resolve, reject);
+ });
+ }
+ }
+
+ var previousPromise;
+
+ function enqueue(method, arg) {
+ function callInvokeWithMethodAndArg() {
+ return new PromiseImpl(function (resolve, reject) {
+ invoke(method, arg, resolve, reject);
+ });
+ }
+
+ return previousPromise = // If enqueue has been called before, then we want to wait until
+ // all previous Promises have been resolved before calling invoke,
+ // so that results are always delivered in the correct order. If
+ // enqueue has not been called before, then it is important to
+ // call invoke immediately, without waiting on a callback to fire,
+ // so that the async generator function has the opportunity to do
+ // any necessary setup in a predictable way. This predictability
+ // is why the Promise constructor synchronously invokes its
+ // executor callback, and why async functions synchronously
+ // execute code before the first await. Since we implement simple
+ // async functions in terms of async generators, it is especially
+ // important to get this right, even though it requires care.
+ previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later
+ // invocations of the iterator.
+ callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
+ } // Define the unified helper method that is used to implement .next,
+ // .throw, and .return (see defineIteratorMethods).
+
+
+ this._invoke = enqueue;
+ }
+
+ defineIteratorMethods(AsyncIterator.prototype);
+
+ AsyncIterator.prototype[asyncIteratorSymbol] = function () {
+ return this;
+ };
+
+ exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of
+ // AsyncIterator objects; they just return a Promise for the value of
+ // the final result produced by the iterator.
+
+ exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
+ if (PromiseImpl === void 0) PromiseImpl = Promise;
+ var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
+ return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator.
+ : iter.next().then(function (result) {
+ return result.done ? result.value : iter.next();
+ });
+ };
+
+ function makeInvokeMethod(innerFn, self, context) {
+ var state = GenStateSuspendedStart;
+ return function invoke(method, arg) {
+ if (state === GenStateExecuting) {
+ throw new Error("Generator is already running");
+ }
+
+ if (state === GenStateCompleted) {
+ if (method === "throw") {
+ throw arg;
+ } // Be forgiving, per 25.3.3.3.3 of the spec:
+ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
+
+
+ return doneResult();
+ }
+
+ context.method = method;
+ context.arg = arg;
+
+ while (true) {
+ var delegate = context.delegate;
+
+ if (delegate) {
+ var delegateResult = maybeInvokeDelegate(delegate, context);
+
+ if (delegateResult) {
+ if (delegateResult === ContinueSentinel) continue;
+ return delegateResult;
+ }
+ }
+
+ if (context.method === "next") {
+ // Setting context._sent for legacy support of Babel's
+ // function.sent implementation.
+ context.sent = context._sent = context.arg;
+ } else if (context.method === "throw") {
+ if (state === GenStateSuspendedStart) {
+ state = GenStateCompleted;
+ throw context.arg;
+ }
+
+ context.dispatchException(context.arg);
+ } else if (context.method === "return") {
+ context.abrupt("return", context.arg);
+ }
+
+ state = GenStateExecuting;
+ var record = tryCatch(innerFn, self, context);
+
+ if (record.type === "normal") {
+ // If an exception is thrown from innerFn, we leave state ===
+ // GenStateExecuting and loop back for another invocation.
+ state = context.done ? GenStateCompleted : GenStateSuspendedYield;
+
+ if (record.arg === ContinueSentinel) {
+ continue;
+ }
+
+ return {
+ value: record.arg,
+ done: context.done
+ };
+ } else if (record.type === "throw") {
+ state = GenStateCompleted; // Dispatch the exception by looping back around to the
+ // context.dispatchException(context.arg) call above.
+
+ context.method = "throw";
+ context.arg = record.arg;
+ }
+ }
+ };
+ } // Call delegate.iterator[context.method](context.arg) and handle the
+ // result, either by returning a { value, done } result from the
+ // delegate iterator, or by modifying context.method and context.arg,
+ // setting context.delegate to null, and returning the ContinueSentinel.
+
+
+ function maybeInvokeDelegate(delegate, context) {
+ var method = delegate.iterator[context.method];
+
+ if (method === undefined$1) {
+ // A .throw or .return when the delegate iterator has no .throw
+ // method always terminates the yield* loop.
+ context.delegate = null;
+
+ if (context.method === "throw") {
+ // Note: ["return"] must be used for ES3 parsing compatibility.
+ if (delegate.iterator["return"]) {
+ // If the delegate iterator has a return method, give it a
+ // chance to clean up.
+ context.method = "return";
+ context.arg = undefined$1;
+ maybeInvokeDelegate(delegate, context);
+
+ if (context.method === "throw") {
+ // If maybeInvokeDelegate(context) changed context.method from
+ // "return" to "throw", let that override the TypeError below.
+ return ContinueSentinel;
+ }
+ }
+
+ context.method = "throw";
+ context.arg = new TypeError("The iterator does not provide a 'throw' method");
+ }
+
+ return ContinueSentinel;
+ }
+
+ var record = tryCatch(method, delegate.iterator, context.arg);
+
+ if (record.type === "throw") {
+ context.method = "throw";
+ context.arg = record.arg;
+ context.delegate = null;
+ return ContinueSentinel;
+ }
+
+ var info = record.arg;
+
+ if (!info) {
+ context.method = "throw";
+ context.arg = new TypeError("iterator result is not an object");
+ context.delegate = null;
+ return ContinueSentinel;
+ }
+
+ if (info.done) {
+ // Assign the result of the finished delegate to the temporary
+ // variable specified by delegate.resultName (see delegateYield).
+ context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield).
+
+ context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the
+ // exception, let the outer generator proceed normally. If
+ // context.method was "next", forget context.arg since it has been
+ // "consumed" by the delegate iterator. If context.method was
+ // "return", allow the original .return call to continue in the
+ // outer generator.
+
+ if (context.method !== "return") {
+ context.method = "next";
+ context.arg = undefined$1;
+ }
+ } else {
+ // Re-yield the result returned by the delegate method.
+ return info;
+ } // The delegate iterator is finished, so forget it and continue with
+ // the outer generator.
+
+
+ context.delegate = null;
+ return ContinueSentinel;
+ } // Define Generator.prototype.{next,throw,return} in terms of the
+ // unified ._invoke helper method.
+
+
+ defineIteratorMethods(Gp);
+ define(Gp, toStringTagSymbol, "Generator"); // A Generator should always return itself as the iterator object when the
+ // @@iterator function is called on it. Some browsers' implementations of the
+ // iterator prototype chain incorrectly implement this, causing the Generator
+ // object to not be returned from this call. This ensures that doesn't happen.
+ // See https://github.com/facebook/regenerator/issues/274 for more details.
+
+ Gp[iteratorSymbol] = function () {
+ return this;
+ };
+
+ Gp.toString = function () {
+ return "[object Generator]";
+ };
+
+ function pushTryEntry(locs) {
+ var entry = {
+ tryLoc: locs[0]
+ };
+
+ if (1 in locs) {
+ entry.catchLoc = locs[1];
+ }
+
+ if (2 in locs) {
+ entry.finallyLoc = locs[2];
+ entry.afterLoc = locs[3];
+ }
+
+ this.tryEntries.push(entry);
+ }
+
+ function resetTryEntry(entry) {
+ var record = entry.completion || {};
+ record.type = "normal";
+ delete record.arg;
+ entry.completion = record;
+ }
+
+ function Context(tryLocsList) {
+ // The root entry object (effectively a try statement without a catch
+ // or a finally block) gives us a place to store values thrown from
+ // locations where there is no enclosing try statement.
+ this.tryEntries = [{
+ tryLoc: "root"
+ }];
+ tryLocsList.forEach(pushTryEntry, this);
+ this.reset(true);
+ }
+
+ exports.keys = function (object) {
+ var keys = [];
+
+ for (var key in object) {
+ keys.push(key);
+ }
+
+ keys.reverse(); // Rather than returning an object with a next method, we keep
+ // things simple and return the next function itself.
+
+ return function next() {
+ while (keys.length) {
+ var key = keys.pop();
+
+ if (key in object) {
+ next.value = key;
+ next.done = false;
+ return next;
+ }
+ } // To avoid creating an additional object, we just hang the .value
+ // and .done properties off the next function object itself. This
+ // also ensures that the minifier will not anonymize the function.
+
+
+ next.done = true;
+ return next;
+ };
+ };
+
+ function values(iterable) {
+ if (iterable) {
+ var iteratorMethod = iterable[iteratorSymbol];
+
+ if (iteratorMethod) {
+ return iteratorMethod.call(iterable);
+ }
+
+ if (typeof iterable.next === "function") {
+ return iterable;
+ }
+
+ if (!isNaN(iterable.length)) {
+ var i = -1,
+ next = function next() {
+ while (++i < iterable.length) {
+ if (hasOwn.call(iterable, i)) {
+ next.value = iterable[i];
+ next.done = false;
+ return next;
+ }
+ }
+
+ next.value = undefined$1;
+ next.done = true;
+ return next;
+ };
+
+ return next.next = next;
+ }
+ } // Return an iterator with no values.
+
+
+ return {
+ next: doneResult
+ };
+ }
+
+ exports.values = values;
+
+ function doneResult() {
+ return {
+ value: undefined$1,
+ done: true
+ };
+ }
+
+ Context.prototype = {
+ constructor: Context,
+ reset: function reset(skipTempReset) {
+ this.prev = 0;
+ this.next = 0; // Resetting context._sent for legacy support of Babel's
+ // function.sent implementation.
+
+ this.sent = this._sent = undefined$1;
+ this.done = false;
+ this.delegate = null;
+ this.method = "next";
+ this.arg = undefined$1;
+ this.tryEntries.forEach(resetTryEntry);
+
+ if (!skipTempReset) {
+ for (var name in this) {
+ // Not sure about the optimal order of these conditions:
+ if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) {
+ this[name] = undefined$1;
+ }
+ }
+ }
+ },
+ stop: function stop() {
+ this.done = true;
+ var rootEntry = this.tryEntries[0];
+ var rootRecord = rootEntry.completion;
+
+ if (rootRecord.type === "throw") {
+ throw rootRecord.arg;
+ }
+
+ return this.rval;
+ },
+ dispatchException: function dispatchException(exception) {
+ if (this.done) {
+ throw exception;
+ }
+
+ var context = this;
+
+ function handle(loc, caught) {
+ record.type = "throw";
+ record.arg = exception;
+ context.next = loc;
+
+ if (caught) {
+ // If the dispatched exception was caught by a catch block,
+ // then let that catch block handle the exception normally.
+ context.method = "next";
+ context.arg = undefined$1;
+ }
+
+ return !!caught;
+ }
+
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
+ var entry = this.tryEntries[i];
+ var record = entry.completion;
+
+ if (entry.tryLoc === "root") {
+ // Exception thrown outside of any try block that could handle
+ // it, so set the completion value of the entire function to
+ // throw the exception.
+ return handle("end");
+ }
+
+ if (entry.tryLoc <= this.prev) {
+ var hasCatch = hasOwn.call(entry, "catchLoc");
+ var hasFinally = hasOwn.call(entry, "finallyLoc");
+
+ if (hasCatch && hasFinally) {
+ if (this.prev < entry.catchLoc) {
+ return handle(entry.catchLoc, true);
+ } else if (this.prev < entry.finallyLoc) {
+ return handle(entry.finallyLoc);
+ }
+ } else if (hasCatch) {
+ if (this.prev < entry.catchLoc) {
+ return handle(entry.catchLoc, true);
+ }
+ } else if (hasFinally) {
+ if (this.prev < entry.finallyLoc) {
+ return handle(entry.finallyLoc);
+ }
+ } else {
+ throw new Error("try statement without catch or finally");
+ }
+ }
+ }
+ },
+ abrupt: function abrupt(type, arg) {
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
+ var entry = this.tryEntries[i];
+
+ if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
+ var finallyEntry = entry;
+ break;
+ }
+ }
+
+ if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) {
+ // Ignore the finally entry if control is not jumping to a
+ // location outside the try/catch block.
+ finallyEntry = null;
+ }
+
+ var record = finallyEntry ? finallyEntry.completion : {};
+ record.type = type;
+ record.arg = arg;
+
+ if (finallyEntry) {
+ this.method = "next";
+ this.next = finallyEntry.finallyLoc;
+ return ContinueSentinel;
+ }
+
+ return this.complete(record);
+ },
+ complete: function complete(record, afterLoc) {
+ if (record.type === "throw") {
+ throw record.arg;
+ }
+
+ if (record.type === "break" || record.type === "continue") {
+ this.next = record.arg;
+ } else if (record.type === "return") {
+ this.rval = this.arg = record.arg;
+ this.method = "return";
+ this.next = "end";
+ } else if (record.type === "normal" && afterLoc) {
+ this.next = afterLoc;
+ }
+
+ return ContinueSentinel;
+ },
+ finish: function finish(finallyLoc) {
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
+ var entry = this.tryEntries[i];
+
+ if (entry.finallyLoc === finallyLoc) {
+ this.complete(entry.completion, entry.afterLoc);
+ resetTryEntry(entry);
+ return ContinueSentinel;
+ }
+ }
+ },
+ "catch": function _catch(tryLoc) {
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
+ var entry = this.tryEntries[i];
+
+ if (entry.tryLoc === tryLoc) {
+ var record = entry.completion;
+
+ if (record.type === "throw") {
+ var thrown = record.arg;
+ resetTryEntry(entry);
+ }
+
+ return thrown;
+ }
+ } // The context.catch method must only be called with a location
+ // argument that corresponds to a known catch block.
+
+
+ throw new Error("illegal catch attempt");
+ },
+ delegateYield: function delegateYield(iterable, resultName, nextLoc) {
+ this.delegate = {
+ iterator: values(iterable),
+ resultName: resultName,
+ nextLoc: nextLoc
+ };
+
+ if (this.method === "next") {
+ // Deliberately forget the last sent value so that we don't
+ // accidentally pass it on to the delegate.
+ this.arg = undefined$1;
+ }
+
+ return ContinueSentinel;
+ }
+ }; // Regardless of whether this script is executing as a CommonJS module
+ // or not, return the runtime object so that we can declare the variable
+ // regeneratorRuntime in the outer scope, which allows this module to be
+ // injected easily by `bin/regenerator --include-runtime script.js`.
+
+ return exports;
+ }( // If this script is executing as a CommonJS module, use module.exports
+ // as the regeneratorRuntime namespace. Otherwise create a new empty
+ // object. Either way, the resulting object will be used to initialize
+ // the regeneratorRuntime variable at the top of this file.
+ module.exports );
+
+ try {
+ regeneratorRuntime = runtime;
+ } catch (accidentalStrictMode) {
+ // This module should not be running in strict mode, so the above
+ // assignment should always work unless something is misconfigured. Just
+ // in case runtime.js accidentally runs in strict mode, we can escape
+ // strict mode using a global Function call. This could conceivably fail
+ // if a Content Security Policy forbids using Function, but in that case
+ // the proper solution is to fix the accidental strict mode problem. If
+ // you've misconfigured your bundler to force strict mode and applied a
+ // CSP to forbid Function, and you're not willing to fix either of those
+ // problems, please detail your unique predicament in a GitHub issue.
+ Function("r", "regeneratorRuntime = r")(runtime);
+ }
+ });
+
+ var escapeStringRegexp = function escapeStringRegexp(string) {
+ if (typeof string !== 'string') {
+ throw new TypeError('Expected a string');
+ } // Escape characters with special meaning either inside or outside character sets.
+ // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.
+
+
+ return string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
+ };
+
+ // Copyright Joyent, Inc. and other Node 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.
+ // resolves . and .. elements in a path array with directory names there
+ // must be no slashes, empty elements, or device names (c:\) in the array
+ // (so also no leading and trailing slashes - it does not distinguish
+ // relative and absolute paths)
+ function normalizeArray(parts, allowAboveRoot) {
+ // if the path tries to go above the root, `up` ends up > 0
+ var up = 0;
+
+ for (var i = parts.length - 1; i >= 0; i--) {
+ var last = parts[i];
+
+ if (last === '.') {
+ parts.splice(i, 1);
+ } else if (last === '..') {
+ parts.splice(i, 1);
+ up++;
+ } else if (up) {
+ parts.splice(i, 1);
+ up--;
+ }
+ } // if the path is allowed to go above the root, restore leading ..s
+
+
+ if (allowAboveRoot) {
+ for (; up--; up) {
+ parts.unshift('..');
+ }
+ }
+
+ return parts;
+ } // Split a filename into [root, dir, basename, ext], unix version
+ // 'root' is just a slash, or nothing.
+
+
+ var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
+
+ var splitPath = function splitPath(filename) {
+ return splitPathRe.exec(filename).slice(1);
+ }; // path.resolve([from ...], to)
+ // posix version
+
+
+ function resolve() {
+ var resolvedPath = '',
+ resolvedAbsolute = false;
+
+ for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
+ var path = i >= 0 ? arguments[i] : '/'; // Skip empty and invalid entries
+
+ if (typeof path !== 'string') {
+ throw new TypeError('Arguments to path.resolve must be strings');
+ } else if (!path) {
+ continue;
+ }
+
+ resolvedPath = path + '/' + resolvedPath;
+ resolvedAbsolute = path.charAt(0) === '/';
+ } // At this point the path should be resolved to a full absolute path, but
+ // handle relative paths to be safe (might happen when process.cwd() fails)
+ // Normalize the path
+
+
+ resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function (p) {
+ return !!p;
+ }), !resolvedAbsolute).join('/');
+ return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';
+ }
+ // posix version
+
+ function normalize(path) {
+ var isPathAbsolute = isAbsolute(path),
+ trailingSlash = substr(path, -1) === '/'; // Normalize the path
+
+ path = normalizeArray(filter(path.split('/'), function (p) {
+ return !!p;
+ }), !isPathAbsolute).join('/');
+
+ if (!path && !isPathAbsolute) {
+ path = '.';
+ }
+
+ if (path && trailingSlash) {
+ path += '/';
+ }
+
+ return (isPathAbsolute ? '/' : '') + path;
+ }
+
+ function isAbsolute(path) {
+ return path.charAt(0) === '/';
+ } // posix version
+
+ function join() {
+ var paths = Array.prototype.slice.call(arguments, 0);
+ return normalize(filter(paths, function (p, index) {
+ if (typeof p !== 'string') {
+ throw new TypeError('Arguments to path.join must be strings');
+ }
+
+ return p;
+ }).join('/'));
+ } // path.relative(from, to)
+ // posix version
+
+ function relative(from, to) {
+ from = resolve(from).substr(1);
+ to = resolve(to).substr(1);
+
+ function trim(arr) {
+ var start = 0;
+
+ for (; start < arr.length; start++) {
+ if (arr[start] !== '') break;
+ }
+
+ var end = arr.length - 1;
+
+ for (; end >= 0; end--) {
+ if (arr[end] !== '') break;
+ }
+
+ if (start > end) return [];
+ return arr.slice(start, end - start + 1);
+ }
+
+ var fromParts = trim(from.split('/'));
+ var toParts = trim(to.split('/'));
+ var length = Math.min(fromParts.length, toParts.length);
+ var samePartsLength = length;
+
+ for (var i = 0; i < length; i++) {
+ if (fromParts[i] !== toParts[i]) {
+ samePartsLength = i;
+ break;
+ }
+ }
+
+ var outputParts = [];
+
+ for (var i = samePartsLength; i < fromParts.length; i++) {
+ outputParts.push('..');
+ }
+
+ outputParts = outputParts.concat(toParts.slice(samePartsLength));
+ return outputParts.join('/');
+ }
+ var sep = '/';
+ var delimiter = ':';
+ function dirname(path) {
+ var result = splitPath(path),
+ root = result[0],
+ dir = result[1];
+
+ if (!root && !dir) {
+ // No dirname whatsoever
+ return '.';
+ }
+
+ if (dir) {
+ // It has a dirname, strip trailing slash
+ dir = dir.substr(0, dir.length - 1);
+ }
+
+ return root + dir;
+ }
+ function basename(path, ext) {
+ var f = splitPath(path)[2]; // TODO: make this comparison case-insensitive on windows?
+
+ if (ext && f.substr(-1 * ext.length) === ext) {
+ f = f.substr(0, f.length - ext.length);
+ }
+
+ return f;
+ }
+ function extname(path) {
+ return splitPath(path)[3];
+ }
+ var path = {
+ extname: extname,
+ basename: basename,
+ dirname: dirname,
+ sep: sep,
+ delimiter: delimiter,
+ relative: relative,
+ join: join,
+ isAbsolute: isAbsolute,
+ normalize: normalize,
+ resolve: resolve
+ };
+
+ function filter(xs, f) {
+ if (xs.filter) return xs.filter(f);
+ var res = [];
+
+ for (var i = 0; i < xs.length; i++) {
+ if (f(xs[i], i, xs)) res.push(xs[i]);
+ }
+
+ return res;
+ } // String.prototype.substr - negative index don't work in IE8
+
+
+ var substr = 'ab'.substr(-1) === 'b' ? function (str, start, len) {
+ return str.substr(start, len);
+ } : function (str, start, len) {
+ if (start < 0) start = str.length + start;
+ return str.substr(start, len);
+ };
+
+ // call something on iterator step with safe closing on error
+ var callWithSafeIterationClosing = function (iterator, fn, value, ENTRIES) {
+ try {
+ return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
+ } catch (error) {
+ iteratorClose(iterator, 'throw', error);
+ }
+ };
+
+ // `Array.from` method implementation
+ // https://tc39.es/ecma262/#sec-array.from
+ var arrayFrom = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
+ var O = toObject(arrayLike);
+ var IS_CONSTRUCTOR = isConstructor(this);
+ var argumentsLength = arguments.length;
+ var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
+ var mapping = mapfn !== undefined;
+ if (mapping) mapfn = functionBindContext(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2);
+ var iteratorMethod = getIteratorMethod(O);
+ var index = 0;
+ var length, result, step, iterator, next, value;
+ // if the target is not iterable or it's an array with the default iterator - use a simple case
+ if (iteratorMethod && !(this == Array && isArrayIteratorMethod(iteratorMethod))) {
+ iterator = getIterator(O, iteratorMethod);
+ next = iterator.next;
+ result = IS_CONSTRUCTOR ? new this() : [];
+ for (;!(step = next.call(iterator)).done; index++) {
+ value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;
+ createProperty(result, index, value);
+ }
+ } else {
+ length = toLength(O.length);
+ result = IS_CONSTRUCTOR ? new this(length) : Array(length);
+ for (;length > index; index++) {
+ value = mapping ? mapfn(O[index], index) : O[index];
+ createProperty(result, index, value);
+ }
+ }
+ result.length = index;
+ return result;
+ };
+
+ var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) {
+ // eslint-disable-next-line es/no-array-from -- required for testing
+ Array.from(iterable);
+ });
+
+ // `Array.from` method
+ // https://tc39.es/ecma262/#sec-array.from
+ _export({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, {
+ from: arrayFrom
+ });
+
+ var test$1 = [];
+ var nativeSort = test$1.sort;
+
+ // IE8-
+ var FAILS_ON_UNDEFINED = fails(function () {
+ test$1.sort(undefined);
+ });
+ // V8 bug
+ var FAILS_ON_NULL = fails(function () {
+ test$1.sort(null);
+ });
+ // Old WebKit
+ var STRICT_METHOD = arrayMethodIsStrict('sort');
+
+ var STABLE_SORT = !fails(function () {
+ // feature detection can be too slow, so check engines versions
+ if (engineV8Version) return engineV8Version < 70;
+ if (engineFfVersion && engineFfVersion > 3) return;
+ if (engineIsIeOrEdge) return true;
+ if (engineWebkitVersion) return engineWebkitVersion < 603;
+
+ var result = '';
+ var code, chr, value, index;
+
+ // generate an array with more 512 elements (Chakra and old V8 fails only in this case)
+ for (code = 65; code < 76; code++) {
+ chr = String.fromCharCode(code);
+
+ switch (code) {
+ case 66: case 69: case 70: case 72: value = 3; break;
+ case 68: case 71: value = 4; break;
+ default: value = 2;
+ }
+
+ for (index = 0; index < 47; index++) {
+ test$1.push({ k: chr + index, v: value });
+ }
+ }
+
+ test$1.sort(function (a, b) { return b.v - a.v; });
+
+ for (index = 0; index < test$1.length; index++) {
+ chr = test$1[index].k.charAt(0);
+ if (result.charAt(result.length - 1) !== chr) result += chr;
+ }
+
+ return result !== 'DGBEFHACIJK';
+ });
+
+ var FORCED$1 = FAILS_ON_UNDEFINED || !FAILS_ON_NULL || !STRICT_METHOD || !STABLE_SORT;
+
+ var getSortCompare = function (comparefn) {
+ return function (x, y) {
+ if (y === undefined) return -1;
+ if (x === undefined) return 1;
+ if (comparefn !== undefined) return +comparefn(x, y) || 0;
+ return toString_1(x) > toString_1(y) ? 1 : -1;
+ };
+ };
+
+ // `Array.prototype.sort` method
+ // https://tc39.es/ecma262/#sec-array.prototype.sort
+ _export({ target: 'Array', proto: true, forced: FORCED$1 }, {
+ sort: function sort(comparefn) {
+ if (comparefn !== undefined) aCallable(comparefn);
+
+ var array = toObject(this);
+
+ if (STABLE_SORT) return comparefn === undefined ? nativeSort.call(array) : nativeSort.call(array, comparefn);
+
+ var items = [];
+ var arrayLength = toLength(array.length);
+ var itemsLength, index;
+
+ for (index = 0; index < arrayLength; index++) {
+ if (index in array) items.push(array[index]);
+ }
+
+ items = arraySort(items, getSortCompare(comparefn));
+ itemsLength = items.length;
+ index = 0;
+
+ while (index < itemsLength) array[index] = items[index++];
+ while (index < arrayLength) delete array[index++];
+
+ return array;
+ }
+ });
+
+ var diff$1 = createCommonjsModule(function (module, exports) {
+ (function (global, factory) {
+ factory(exports) ;
+ })(commonjsGlobal, function (exports) {
+
+ function Diff() {}
+
+ Diff.prototype = {
+ diff: function diff(oldString, newString) {
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+ var callback = options.callback;
+
+ if (typeof options === 'function') {
+ callback = options;
+ options = {};
+ }
+
+ this.options = options;
+ var self = this;
+
+ function done(value) {
+ if (callback) {
+ setTimeout(function () {
+ callback(undefined, value);
+ }, 0);
+ return true;
+ } else {
+ return value;
+ }
+ } // Allow subclasses to massage the input prior to running
+
+
+ oldString = this.castInput(oldString);
+ newString = this.castInput(newString);
+ oldString = this.removeEmpty(this.tokenize(oldString));
+ newString = this.removeEmpty(this.tokenize(newString));
+ var newLen = newString.length,
+ oldLen = oldString.length;
+ var editLength = 1;
+ var maxEditLength = newLen + oldLen;
+ var bestPath = [{
+ newPos: -1,
+ components: []
+ }]; // Seed editLength = 0, i.e. the content starts with the same values
+
+ var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
+
+ if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
+ // Identity per the equality and tokenizer
+ return done([{
+ value: this.join(newString),
+ count: newString.length
+ }]);
+ } // Main worker method. checks all permutations of a given edit length for acceptance.
+
+
+ function execEditLength() {
+ for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
+ var basePath = void 0;
+
+ var addPath = bestPath[diagonalPath - 1],
+ removePath = bestPath[diagonalPath + 1],
+ _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
+
+ if (addPath) {
+ // No one else is going to attempt to use this value, clear it
+ bestPath[diagonalPath - 1] = undefined;
+ }
+
+ var canAdd = addPath && addPath.newPos + 1 < newLen,
+ canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
+
+ if (!canAdd && !canRemove) {
+ // If this path is a terminal then prune
+ bestPath[diagonalPath] = undefined;
+ continue;
+ } // Select the diagonal that we want to branch from. We select the prior
+ // path whose position in the new string is the farthest from the origin
+ // and does not pass the bounds of the diff graph
+
+
+ if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
+ basePath = clonePath(removePath);
+ self.pushComponent(basePath.components, undefined, true);
+ } else {
+ basePath = addPath; // No need to clone, we've pulled it from the list
+
+ basePath.newPos++;
+ self.pushComponent(basePath.components, true, undefined);
+ }
+
+ _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
+
+ if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
+ return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
+ } else {
+ // Otherwise track this path as a potential candidate and continue.
+ bestPath[diagonalPath] = basePath;
+ }
+ }
+
+ editLength++;
+ } // Performs the length of edit iteration. Is a bit fugly as this has to support the
+ // sync and async mode which is never fun. Loops over execEditLength until a value
+ // is produced.
+
+
+ if (callback) {
+ (function exec() {
+ setTimeout(function () {
+ // This should not happen, but we want to be safe.
+
+ /* istanbul ignore next */
+ if (editLength > maxEditLength) {
+ return callback();
+ }
+
+ if (!execEditLength()) {
+ exec();
+ }
+ }, 0);
+ })();
+ } else {
+ while (editLength <= maxEditLength) {
+ var ret = execEditLength();
+
+ if (ret) {
+ return ret;
+ }
+ }
+ }
+ },
+ pushComponent: function pushComponent(components, added, removed) {
+ var last = components[components.length - 1];
+
+ if (last && last.added === added && last.removed === removed) {
+ // We need to clone here as the component clone operation is just
+ // as shallow array clone
+ components[components.length - 1] = {
+ count: last.count + 1,
+ added: added,
+ removed: removed
+ };
+ } else {
+ components.push({
+ count: 1,
+ added: added,
+ removed: removed
+ });
+ }
+ },
+ extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
+ var newLen = newString.length,
+ oldLen = oldString.length,
+ newPos = basePath.newPos,
+ oldPos = newPos - diagonalPath,
+ commonCount = 0;
+
+ while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
+ newPos++;
+ oldPos++;
+ commonCount++;
+ }
+
+ if (commonCount) {
+ basePath.components.push({
+ count: commonCount
+ });
+ }
+
+ basePath.newPos = newPos;
+ return oldPos;
+ },
+ equals: function equals(left, right) {
+ if (this.options.comparator) {
+ return this.options.comparator(left, right);
+ } else {
+ return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
+ }
+ },
+ removeEmpty: function removeEmpty(array) {
+ var ret = [];
+
+ for (var i = 0; i < array.length; i++) {
+ if (array[i]) {
+ ret.push(array[i]);
+ }
+ }
+
+ return ret;
+ },
+ castInput: function castInput(value) {
+ return value;
+ },
+ tokenize: function tokenize(value) {
+ return value.split('');
+ },
+ join: function join(chars) {
+ return chars.join('');
+ }
+ };
+
+ function buildValues(diff, components, newString, oldString, useLongestToken) {
+ var componentPos = 0,
+ componentLen = components.length,
+ newPos = 0,
+ oldPos = 0;
+
+ for (; componentPos < componentLen; componentPos++) {
+ var component = components[componentPos];
+
+ if (!component.removed) {
+ if (!component.added && useLongestToken) {
+ var value = newString.slice(newPos, newPos + component.count);
+ value = value.map(function (value, i) {
+ var oldValue = oldString[oldPos + i];
+ return oldValue.length > value.length ? oldValue : value;
+ });
+ component.value = diff.join(value);
+ } else {
+ component.value = diff.join(newString.slice(newPos, newPos + component.count));
+ }
+
+ newPos += component.count; // Common case
+
+ if (!component.added) {
+ oldPos += component.count;
+ }
+ } else {
+ component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
+ oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
+ // The diffing algorithm is tied to add then remove output and this is the simplest
+ // route to get the desired output with minimal overhead.
+
+ if (componentPos && components[componentPos - 1].added) {
+ var tmp = components[componentPos - 1];
+ components[componentPos - 1] = components[componentPos];
+ components[componentPos] = tmp;
+ }
+ }
+ } // Special case handle for when one terminal is ignored (i.e. whitespace).
+ // For this case we merge the terminal into the prior string and drop the change.
+ // This is only available for string mode.
+
+
+ var lastComponent = components[componentLen - 1];
+
+ if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
+ components[componentLen - 2].value += lastComponent.value;
+ components.pop();
+ }
+
+ return components;
+ }
+
+ function clonePath(path) {
+ return {
+ newPos: path.newPos,
+ components: path.components.slice(0)
+ };
+ }
+
+ var characterDiff = new Diff();
+
+ function diffChars(oldStr, newStr, options) {
+ return characterDiff.diff(oldStr, newStr, options);
+ }
+
+ function generateOptions(options, defaults) {
+ if (typeof options === 'function') {
+ defaults.callback = options;
+ } else if (options) {
+ for (var name in options) {
+ /* istanbul ignore else */
+ if (options.hasOwnProperty(name)) {
+ defaults[name] = options[name];
+ }
+ }
+ }
+
+ return defaults;
+ } //
+ // Ranges and exceptions:
+ // Latin-1 Supplement, 0080–00FF
+ // - U+00D7 × Multiplication sign
+ // - U+00F7 ÷ Division sign
+ // Latin Extended-A, 0100–017F
+ // Latin Extended-B, 0180–024F
+ // IPA Extensions, 0250–02AF
+ // Spacing Modifier Letters, 02B0–02FF
+ // - U+02C7 ˇ ˇ Caron
+ // - U+02D8 ˘ ˘ Breve
+ // - U+02D9 ˙ ˙ Dot Above
+ // - U+02DA ˚ ˚ Ring Above
+ // - U+02DB ˛ ˛ Ogonek
+ // - U+02DC ˜ ˜ Small Tilde
+ // - U+02DD ˝ ˝ Double Acute Accent
+ // Latin Extended Additional, 1E00–1EFF
+
+
+ var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
+ var reWhitespace = /\S/;
+ var wordDiff = new Diff();
+
+ wordDiff.equals = function (left, right) {
+ if (this.options.ignoreCase) {
+ left = left.toLowerCase();
+ right = right.toLowerCase();
+ }
+
+ return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
+ };
+
+ wordDiff.tokenize = function (value) {
+ // All whitespace symbols except newline group into one token, each newline - in separate token
+ var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
+
+ for (var i = 0; i < tokens.length - 1; i++) {
+ // If we have an empty string in the next field and we have only word chars before and after, merge
+ if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
+ tokens[i] += tokens[i + 2];
+ tokens.splice(i + 1, 2);
+ i--;
+ }
+ }
+
+ return tokens;
+ };
+
+ function diffWords(oldStr, newStr, options) {
+ options = generateOptions(options, {
+ ignoreWhitespace: true
+ });
+ return wordDiff.diff(oldStr, newStr, options);
+ }
+
+ function diffWordsWithSpace(oldStr, newStr, options) {
+ return wordDiff.diff(oldStr, newStr, options);
+ }
+
+ var lineDiff = new Diff();
+
+ lineDiff.tokenize = function (value) {
+ var retLines = [],
+ linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
+
+ if (!linesAndNewlines[linesAndNewlines.length - 1]) {
+ linesAndNewlines.pop();
+ } // Merge the content and line separators into single tokens
+
+
+ for (var i = 0; i < linesAndNewlines.length; i++) {
+ var line = linesAndNewlines[i];
+
+ if (i % 2 && !this.options.newlineIsToken) {
+ retLines[retLines.length - 1] += line;
+ } else {
+ if (this.options.ignoreWhitespace) {
+ line = line.trim();
+ }
+
+ retLines.push(line);
+ }
+ }
+
+ return retLines;
+ };
+
+ function diffLines(oldStr, newStr, callback) {
+ return lineDiff.diff(oldStr, newStr, callback);
+ }
+
+ function diffTrimmedLines(oldStr, newStr, callback) {
+ var options = generateOptions(callback, {
+ ignoreWhitespace: true
+ });
+ return lineDiff.diff(oldStr, newStr, options);
+ }
+
+ var sentenceDiff = new Diff();
+
+ sentenceDiff.tokenize = function (value) {
+ return value.split(/(\S.+?[.!?])(?=\s+|$)/);
+ };
+
+ function diffSentences(oldStr, newStr, callback) {
+ return sentenceDiff.diff(oldStr, newStr, callback);
+ }
+
+ var cssDiff = new Diff();
+
+ cssDiff.tokenize = function (value) {
+ return value.split(/([{}:;,]|\s+)/);
+ };
+
+ function diffCss(oldStr, newStr, callback) {
+ return cssDiff.diff(oldStr, newStr, callback);
+ }
+
+ function _typeof(obj) {
+ "@babel/helpers - typeof";
+
+ if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
+ _typeof = function _typeof(obj) {
+ return typeof obj;
+ };
+ } else {
+ _typeof = function _typeof(obj) {
+ return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
+ };
+ }
+
+ return _typeof(obj);
+ }
+
+ function _toConsumableArray(arr) {
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
+ }
+
+ function _arrayWithoutHoles(arr) {
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
+ }
+
+ function _iterableToArray(iter) {
+ if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
+ }
+
+ function _unsupportedIterableToArray(o, minLen) {
+ if (!o) return;
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
+ var n = Object.prototype.toString.call(o).slice(8, -1);
+ if (n === "Object" && o.constructor) n = o.constructor.name;
+ if (n === "Map" || n === "Set") return Array.from(o);
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
+ }
+
+ function _arrayLikeToArray(arr, len) {
+ if (len == null || len > arr.length) len = arr.length;
+
+ for (var i = 0, arr2 = new Array(len); i < len; i++) {
+ arr2[i] = arr[i];
+ }
+
+ return arr2;
+ }
+
+ function _nonIterableSpread() {
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
+ }
+
+ var objectPrototypeToString = Object.prototype.toString;
+ var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
+ // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
+
+ jsonDiff.useLongestToken = true;
+ jsonDiff.tokenize = lineDiff.tokenize;
+
+ jsonDiff.castInput = function (value) {
+ var _this$options = this.options,
+ undefinedReplacement = _this$options.undefinedReplacement,
+ _this$options$stringi = _this$options.stringifyReplacer,
+ stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
+ return typeof v === 'undefined' ? undefinedReplacement : v;
+ } : _this$options$stringi;
+ return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
+ };
+
+ jsonDiff.equals = function (left, right) {
+ return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
+ };
+
+ function diffJson(oldObj, newObj, options) {
+ return jsonDiff.diff(oldObj, newObj, options);
+ } // This function handles the presence of circular references by bailing out when encountering an
+ // object that is already on the "stack" of items being processed. Accepts an optional replacer
+
+
+ function canonicalize(obj, stack, replacementStack, replacer, key) {
+ stack = stack || [];
+ replacementStack = replacementStack || [];
+
+ if (replacer) {
+ obj = replacer(key, obj);
+ }
+
+ var i;
+
+ for (i = 0; i < stack.length; i += 1) {
+ if (stack[i] === obj) {
+ return replacementStack[i];
+ }
+ }
+
+ var canonicalizedObj;
+
+ if ('[object Array]' === objectPrototypeToString.call(obj)) {
+ stack.push(obj);
+ canonicalizedObj = new Array(obj.length);
+ replacementStack.push(canonicalizedObj);
+
+ for (i = 0; i < obj.length; i += 1) {
+ canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
+ }
+
+ stack.pop();
+ replacementStack.pop();
+ return canonicalizedObj;
+ }
+
+ if (obj && obj.toJSON) {
+ obj = obj.toJSON();
+ }
+
+ if (_typeof(obj) === 'object' && obj !== null) {
+ stack.push(obj);
+ canonicalizedObj = {};
+ replacementStack.push(canonicalizedObj);
+
+ var sortedKeys = [],
+ _key;
+
+ for (_key in obj) {
+ /* istanbul ignore else */
+ if (obj.hasOwnProperty(_key)) {
+ sortedKeys.push(_key);
+ }
+ }
+
+ sortedKeys.sort();
+
+ for (i = 0; i < sortedKeys.length; i += 1) {
+ _key = sortedKeys[i];
+ canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
+ }
+
+ stack.pop();
+ replacementStack.pop();
+ } else {
+ canonicalizedObj = obj;
+ }
+
+ return canonicalizedObj;
+ }
+
+ var arrayDiff = new Diff();
+
+ arrayDiff.tokenize = function (value) {
+ return value.slice();
+ };
+
+ arrayDiff.join = arrayDiff.removeEmpty = function (value) {
+ return value;
+ };
+
+ function diffArrays(oldArr, newArr, callback) {
+ return arrayDiff.diff(oldArr, newArr, callback);
+ }
+
+ function parsePatch(uniDiff) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
+ delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
+ list = [],
+ i = 0;
+
+ function parseIndex() {
+ var index = {};
+ list.push(index); // Parse diff metadata
+
+ while (i < diffstr.length) {
+ var line = diffstr[i]; // File header found, end parsing diff metadata
+
+ if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
+ break;
+ } // Diff index
+
+
+ var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
+
+ if (header) {
+ index.index = header[1];
+ }
+
+ i++;
+ } // Parse file headers if they are defined. Unified diff requires them, but
+ // there's no technical issues to have an isolated hunk without file header
+
+
+ parseFileHeader(index);
+ parseFileHeader(index); // Parse hunks
+
+ index.hunks = [];
+
+ while (i < diffstr.length) {
+ var _line = diffstr[i];
+
+ if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
+ break;
+ } else if (/^@@/.test(_line)) {
+ index.hunks.push(parseHunk());
+ } else if (_line && options.strict) {
+ // Ignore unexpected content unless in strict mode
+ throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
+ } else {
+ i++;
+ }
+ }
+ } // Parses the --- and +++ headers, if none are found, no lines
+ // are consumed.
+
+
+ function parseFileHeader(index) {
+ var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
+
+ if (fileHeader) {
+ var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
+ var data = fileHeader[2].split('\t', 2);
+ var fileName = data[0].replace(/\\\\/g, '\\');
+
+ if (/^".*"$/.test(fileName)) {
+ fileName = fileName.substr(1, fileName.length - 2);
+ }
+
+ index[keyPrefix + 'FileName'] = fileName;
+ index[keyPrefix + 'Header'] = (data[1] || '').trim();
+ i++;
+ }
+ } // Parses a hunk
+ // This assumes that we are at the start of a hunk.
+
+
+ function parseHunk() {
+ var chunkHeaderIndex = i,
+ chunkHeaderLine = diffstr[i++],
+ chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
+ var hunk = {
+ oldStart: +chunkHeader[1],
+ oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],
+ newStart: +chunkHeader[3],
+ newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],
+ lines: [],
+ linedelimiters: []
+ }; // Unified Diff Format quirk: If the chunk size is 0,
+ // the first number is one lower than one would expect.
+ // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
+
+ if (hunk.oldLines === 0) {
+ hunk.oldStart += 1;
+ }
+
+ if (hunk.newLines === 0) {
+ hunk.newStart += 1;
+ }
+
+ var addCount = 0,
+ removeCount = 0;
+
+ for (; i < diffstr.length; i++) {
+ // Lines starting with '---' could be mistaken for the "remove line" operation
+ // But they could be the header for the next file. Therefore prune such cases out.
+ if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
+ break;
+ }
+
+ var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
+
+ if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
+ hunk.lines.push(diffstr[i]);
+ hunk.linedelimiters.push(delimiters[i] || '\n');
+
+ if (operation === '+') {
+ addCount++;
+ } else if (operation === '-') {
+ removeCount++;
+ } else if (operation === ' ') {
+ addCount++;
+ removeCount++;
+ }
+ } else {
+ break;
+ }
+ } // Handle the empty block count case
+
+
+ if (!addCount && hunk.newLines === 1) {
+ hunk.newLines = 0;
+ }
+
+ if (!removeCount && hunk.oldLines === 1) {
+ hunk.oldLines = 0;
+ } // Perform optional sanity checking
+
+
+ if (options.strict) {
+ if (addCount !== hunk.newLines) {
+ throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
+ }
+
+ if (removeCount !== hunk.oldLines) {
+ throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
+ }
+ }
+
+ return hunk;
+ }
+
+ while (i < diffstr.length) {
+ parseIndex();
+ }
+
+ return list;
+ } // Iterator that traverses in the range of [min, max], stepping
+ // by distance from a given start position. I.e. for [0, 4], with
+ // start of 2, this will iterate 2, 3, 1, 4, 0.
+
+
+ function distanceIterator(start, minLine, maxLine) {
+ var wantForward = true,
+ backwardExhausted = false,
+ forwardExhausted = false,
+ localOffset = 1;
+ return function iterator() {
+ if (wantForward && !forwardExhausted) {
+ if (backwardExhausted) {
+ localOffset++;
+ } else {
+ wantForward = false;
+ } // Check if trying to fit beyond text length, and if not, check it fits
+ // after offset location (or desired location on first iteration)
+
+
+ if (start + localOffset <= maxLine) {
+ return localOffset;
+ }
+
+ forwardExhausted = true;
+ }
+
+ if (!backwardExhausted) {
+ if (!forwardExhausted) {
+ wantForward = true;
+ } // Check if trying to fit before text beginning, and if not, check it fits
+ // before offset location
+
+
+ if (minLine <= start - localOffset) {
+ return -localOffset++;
+ }
+
+ backwardExhausted = true;
+ return iterator();
+ } // We tried to fit hunk before text beginning and beyond text length, then
+ // hunk can't fit on the text. Return undefined
+
+ };
+ }
+
+ function applyPatch(source, uniDiff) {
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+
+ if (typeof uniDiff === 'string') {
+ uniDiff = parsePatch(uniDiff);
+ }
+
+ if (Array.isArray(uniDiff)) {
+ if (uniDiff.length > 1) {
+ throw new Error('applyPatch only works with a single input.');
+ }
+
+ uniDiff = uniDiff[0];
+ } // Apply the diff to the input
+
+
+ var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
+ delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
+ hunks = uniDiff.hunks,
+ compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
+ return line === patchContent;
+ },
+ errorCount = 0,
+ fuzzFactor = options.fuzzFactor || 0,
+ minLine = 0,
+ offset = 0,
+ removeEOFNL,
+ addEOFNL;
+ /**
+ * Checks if the hunk exactly fits on the provided location
+ */
+
+
+ function hunkFits(hunk, toPos) {
+ for (var j = 0; j < hunk.lines.length; j++) {
+ var line = hunk.lines[j],
+ operation = line.length > 0 ? line[0] : ' ',
+ content = line.length > 0 ? line.substr(1) : line;
+
+ if (operation === ' ' || operation === '-') {
+ // Context sanity check
+ if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
+ errorCount++;
+
+ if (errorCount > fuzzFactor) {
+ return false;
+ }
+ }
+
+ toPos++;
+ }
+ }
+
+ return true;
+ } // Search best fit offsets for each hunk based on the previous ones
+
+
+ for (var i = 0; i < hunks.length; i++) {
+ var hunk = hunks[i],
+ maxLine = lines.length - hunk.oldLines,
+ localOffset = 0,
+ toPos = offset + hunk.oldStart - 1;
+ var iterator = distanceIterator(toPos, minLine, maxLine);
+
+ for (; localOffset !== undefined; localOffset = iterator()) {
+ if (hunkFits(hunk, toPos + localOffset)) {
+ hunk.offset = offset += localOffset;
+ break;
+ }
+ }
+
+ if (localOffset === undefined) {
+ return false;
+ } // Set lower text limit to end of the current hunk, so next ones don't try
+ // to fit over already patched text
+
+
+ minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
+ } // Apply patch hunks
+
+
+ var diffOffset = 0;
+
+ for (var _i = 0; _i < hunks.length; _i++) {
+ var _hunk = hunks[_i],
+ _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
+
+ diffOffset += _hunk.newLines - _hunk.oldLines;
+
+ for (var j = 0; j < _hunk.lines.length; j++) {
+ var line = _hunk.lines[j],
+ operation = line.length > 0 ? line[0] : ' ',
+ content = line.length > 0 ? line.substr(1) : line,
+ delimiter = _hunk.linedelimiters[j];
+
+ if (operation === ' ') {
+ _toPos++;
+ } else if (operation === '-') {
+ lines.splice(_toPos, 1);
+ delimiters.splice(_toPos, 1);
+ /* istanbul ignore else */
+ } else if (operation === '+') {
+ lines.splice(_toPos, 0, content);
+ delimiters.splice(_toPos, 0, delimiter);
+ _toPos++;
+ } else if (operation === '\\') {
+ var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
+
+ if (previousOperation === '+') {
+ removeEOFNL = true;
+ } else if (previousOperation === '-') {
+ addEOFNL = true;
+ }
+ }
+ }
+ } // Handle EOFNL insertion/removal
+
+
+ if (removeEOFNL) {
+ while (!lines[lines.length - 1]) {
+ lines.pop();
+ delimiters.pop();
+ }
+ } else if (addEOFNL) {
+ lines.push('');
+ delimiters.push('\n');
+ }
+
+ for (var _k = 0; _k < lines.length - 1; _k++) {
+ lines[_k] = lines[_k] + delimiters[_k];
+ }
+
+ return lines.join('');
+ } // Wrapper that supports multiple file patches via callbacks.
+
+
+ function applyPatches(uniDiff, options) {
+ if (typeof uniDiff === 'string') {
+ uniDiff = parsePatch(uniDiff);
+ }
+
+ var currentIndex = 0;
+
+ function processIndex() {
+ var index = uniDiff[currentIndex++];
+
+ if (!index) {
+ return options.complete();
+ }
+
+ options.loadFile(index, function (err, data) {
+ if (err) {
+ return options.complete(err);
+ }
+
+ var updatedContent = applyPatch(data, index, options);
+ options.patched(index, updatedContent, function (err) {
+ if (err) {
+ return options.complete(err);
+ }
+
+ processIndex();
+ });
+ });
+ }
+
+ processIndex();
+ }
+
+ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
+ if (!options) {
+ options = {};
+ }
+
+ if (typeof options.context === 'undefined') {
+ options.context = 4;
+ }
+
+ var diff = diffLines(oldStr, newStr, options);
+ diff.push({
+ value: '',
+ lines: []
+ }); // Append an empty value to make cleanup easier
+
+ function contextLines(lines) {
+ return lines.map(function (entry) {
+ return ' ' + entry;
+ });
+ }
+
+ var hunks = [];
+ var oldRangeStart = 0,
+ newRangeStart = 0,
+ curRange = [],
+ oldLine = 1,
+ newLine = 1;
+
+ var _loop = function _loop(i) {
+ var current = diff[i],
+ lines = current.lines || current.value.replace(/\n$/, '').split('\n');
+ current.lines = lines;
+
+ if (current.added || current.removed) {
+ var _curRange; // If we have previous context, start with that
+
+
+ if (!oldRangeStart) {
+ var prev = diff[i - 1];
+ oldRangeStart = oldLine;
+ newRangeStart = newLine;
+
+ if (prev) {
+ curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
+ oldRangeStart -= curRange.length;
+ newRangeStart -= curRange.length;
+ }
+ } // Output our changes
+
+
+ (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
+ return (current.added ? '+' : '-') + entry;
+ }))); // Track the updated file position
+
+
+ if (current.added) {
+ newLine += lines.length;
+ } else {
+ oldLine += lines.length;
+ }
+ } else {
+ // Identical context lines. Track line changes
+ if (oldRangeStart) {
+ // Close out any changes that have been output (or join overlapping)
+ if (lines.length <= options.context * 2 && i < diff.length - 2) {
+ var _curRange2; // Overlapping
+
+
+ (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
+ } else {
+ var _curRange3; // end the range and output
+
+
+ var contextSize = Math.min(lines.length, options.context);
+
+ (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
+
+ var hunk = {
+ oldStart: oldRangeStart,
+ oldLines: oldLine - oldRangeStart + contextSize,
+ newStart: newRangeStart,
+ newLines: newLine - newRangeStart + contextSize,
+ lines: curRange
+ };
+
+ if (i >= diff.length - 2 && lines.length <= options.context) {
+ // EOF is inside this hunk
+ var oldEOFNewline = /\n$/.test(oldStr);
+ var newEOFNewline = /\n$/.test(newStr);
+ var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
+
+ if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) {
+ // special case: old has no eol and no trailing context; no-nl can end up before adds
+ // however, if the old file is empty, do not output the no-nl line
+ curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
+ }
+
+ if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
+ curRange.push('\\ No newline at end of file');
+ }
+ }
+
+ hunks.push(hunk);
+ oldRangeStart = 0;
+ newRangeStart = 0;
+ curRange = [];
+ }
+ }
+
+ oldLine += lines.length;
+ newLine += lines.length;
+ }
+ };
+
+ for (var i = 0; i < diff.length; i++) {
+ _loop(i);
+ }
+
+ return {
+ oldFileName: oldFileName,
+ newFileName: newFileName,
+ oldHeader: oldHeader,
+ newHeader: newHeader,
+ hunks: hunks
+ };
+ }
+
+ function formatPatch(diff) {
+ var ret = [];
+
+ if (diff.oldFileName == diff.newFileName) {
+ ret.push('Index: ' + diff.oldFileName);
+ }
+
+ ret.push('===================================================================');
+ ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
+ ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
+
+ for (var i = 0; i < diff.hunks.length; i++) {
+ var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0,
+ // the first number is one lower than one would expect.
+ // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
+
+ if (hunk.oldLines === 0) {
+ hunk.oldStart -= 1;
+ }
+
+ if (hunk.newLines === 0) {
+ hunk.newStart -= 1;
+ }
+
+ ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
+ ret.push.apply(ret, hunk.lines);
+ }
+
+ return ret.join('\n') + '\n';
+ }
+
+ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
+ return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options));
+ }
+
+ function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
+ return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
+ }
+
+ function arrayEqual(a, b) {
+ if (a.length !== b.length) {
+ return false;
+ }
+
+ return arrayStartsWith(a, b);
+ }
+
+ function arrayStartsWith(array, start) {
+ if (start.length > array.length) {
+ return false;
+ }
+
+ for (var i = 0; i < start.length; i++) {
+ if (start[i] !== array[i]) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ function calcLineCount(hunk) {
+ var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
+ oldLines = _calcOldNewLineCount.oldLines,
+ newLines = _calcOldNewLineCount.newLines;
+
+ if (oldLines !== undefined) {
+ hunk.oldLines = oldLines;
+ } else {
+ delete hunk.oldLines;
+ }
+
+ if (newLines !== undefined) {
+ hunk.newLines = newLines;
+ } else {
+ delete hunk.newLines;
+ }
+ }
+
+ function merge(mine, theirs, base) {
+ mine = loadPatch(mine, base);
+ theirs = loadPatch(theirs, base);
+ var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
+ // Leaving sanity checks on this to the API consumer that may know more about the
+ // meaning in their own context.
+
+ if (mine.index || theirs.index) {
+ ret.index = mine.index || theirs.index;
+ }
+
+ if (mine.newFileName || theirs.newFileName) {
+ if (!fileNameChanged(mine)) {
+ // No header or no change in ours, use theirs (and ours if theirs does not exist)
+ ret.oldFileName = theirs.oldFileName || mine.oldFileName;
+ ret.newFileName = theirs.newFileName || mine.newFileName;
+ ret.oldHeader = theirs.oldHeader || mine.oldHeader;
+ ret.newHeader = theirs.newHeader || mine.newHeader;
+ } else if (!fileNameChanged(theirs)) {
+ // No header or no change in theirs, use ours
+ ret.oldFileName = mine.oldFileName;
+ ret.newFileName = mine.newFileName;
+ ret.oldHeader = mine.oldHeader;
+ ret.newHeader = mine.newHeader;
+ } else {
+ // Both changed... figure it out
+ ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
+ ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
+ ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
+ ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
+ }
+ }
+
+ ret.hunks = [];
+ var mineIndex = 0,
+ theirsIndex = 0,
+ mineOffset = 0,
+ theirsOffset = 0;
+
+ while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
+ var mineCurrent = mine.hunks[mineIndex] || {
+ oldStart: Infinity
+ },
+ theirsCurrent = theirs.hunks[theirsIndex] || {
+ oldStart: Infinity
+ };
+
+ if (hunkBefore(mineCurrent, theirsCurrent)) {
+ // This patch does not overlap with any of the others, yay.
+ ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
+ mineIndex++;
+ theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
+ } else if (hunkBefore(theirsCurrent, mineCurrent)) {
+ // This patch does not overlap with any of the others, yay.
+ ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
+ theirsIndex++;
+ mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
+ } else {
+ // Overlap, merge as best we can
+ var mergedHunk = {
+ oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
+ oldLines: 0,
+ newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
+ newLines: 0,
+ lines: []
+ };
+ mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
+ theirsIndex++;
+ mineIndex++;
+ ret.hunks.push(mergedHunk);
+ }
+ }
+
+ return ret;
+ }
+
+ function loadPatch(param, base) {
+ if (typeof param === 'string') {
+ if (/^@@/m.test(param) || /^Index:/m.test(param)) {
+ return parsePatch(param)[0];
+ }
+
+ if (!base) {
+ throw new Error('Must provide a base reference or pass in a patch');
+ }
+
+ return structuredPatch(undefined, undefined, base, param);
+ }
+
+ return param;
+ }
+
+ function fileNameChanged(patch) {
+ return patch.newFileName && patch.newFileName !== patch.oldFileName;
+ }
+
+ function selectField(index, mine, theirs) {
+ if (mine === theirs) {
+ return mine;
+ } else {
+ index.conflict = true;
+ return {
+ mine: mine,
+ theirs: theirs
+ };
+ }
+ }
+
+ function hunkBefore(test, check) {
+ return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
+ }
+
+ function cloneHunk(hunk, offset) {
+ return {
+ oldStart: hunk.oldStart,
+ oldLines: hunk.oldLines,
+ newStart: hunk.newStart + offset,
+ newLines: hunk.newLines,
+ lines: hunk.lines
+ };
+ }
+
+ function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
+ // This will generally result in a conflicted hunk, but there are cases where the context
+ // is the only overlap where we can successfully merge the content here.
+ var mine = {
+ offset: mineOffset,
+ lines: mineLines,
+ index: 0
+ },
+ their = {
+ offset: theirOffset,
+ lines: theirLines,
+ index: 0
+ }; // Handle any leading content
+
+ insertLeading(hunk, mine, their);
+ insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
+
+ while (mine.index < mine.lines.length && their.index < their.lines.length) {
+ var mineCurrent = mine.lines[mine.index],
+ theirCurrent = their.lines[their.index];
+
+ if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
+ // Both modified ...
+ mutualChange(hunk, mine, their);
+ } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
+ var _hunk$lines; // Mine inserted
+
+
+ (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
+ } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
+ var _hunk$lines2; // Theirs inserted
+
+
+ (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
+ } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
+ // Mine removed or edited
+ removal(hunk, mine, their);
+ } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
+ // Their removed or edited
+ removal(hunk, their, mine, true);
+ } else if (mineCurrent === theirCurrent) {
+ // Context identity
+ hunk.lines.push(mineCurrent);
+ mine.index++;
+ their.index++;
+ } else {
+ // Context mismatch
+ conflict(hunk, collectChange(mine), collectChange(their));
+ }
+ } // Now push anything that may be remaining
+
+
+ insertTrailing(hunk, mine);
+ insertTrailing(hunk, their);
+ calcLineCount(hunk);
+ }
+
+ function mutualChange(hunk, mine, their) {
+ var myChanges = collectChange(mine),
+ theirChanges = collectChange(their);
+
+ if (allRemoves(myChanges) && allRemoves(theirChanges)) {
+ // Special case for remove changes that are supersets of one another
+ if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
+ var _hunk$lines3;
+
+ (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
+
+ return;
+ } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
+ var _hunk$lines4;
+
+ (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
+
+ return;
+ }
+ } else if (arrayEqual(myChanges, theirChanges)) {
+ var _hunk$lines5;
+
+ (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
+
+ return;
+ }
+
+ conflict(hunk, myChanges, theirChanges);
+ }
+
+ function removal(hunk, mine, their, swap) {
+ var myChanges = collectChange(mine),
+ theirChanges = collectContext(their, myChanges);
+
+ if (theirChanges.merged) {
+ var _hunk$lines6;
+
+ (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
+ } else {
+ conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
+ }
+ }
+
+ function conflict(hunk, mine, their) {
+ hunk.conflict = true;
+ hunk.lines.push({
+ conflict: true,
+ mine: mine,
+ theirs: their
+ });
+ }
+
+ function insertLeading(hunk, insert, their) {
+ while (insert.offset < their.offset && insert.index < insert.lines.length) {
+ var line = insert.lines[insert.index++];
+ hunk.lines.push(line);
+ insert.offset++;
+ }
+ }
+
+ function insertTrailing(hunk, insert) {
+ while (insert.index < insert.lines.length) {
+ var line = insert.lines[insert.index++];
+ hunk.lines.push(line);
+ }
+ }
+
+ function collectChange(state) {
+ var ret = [],
+ operation = state.lines[state.index][0];
+
+ while (state.index < state.lines.length) {
+ var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
+
+ if (operation === '-' && line[0] === '+') {
+ operation = '+';
+ }
+
+ if (operation === line[0]) {
+ ret.push(line);
+ state.index++;
+ } else {
+ break;
+ }
+ }
+
+ return ret;
+ }
+
+ function collectContext(state, matchChanges) {
+ var changes = [],
+ merged = [],
+ matchIndex = 0,
+ contextChanges = false,
+ conflicted = false;
+
+ while (matchIndex < matchChanges.length && state.index < state.lines.length) {
+ var change = state.lines[state.index],
+ match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
+
+ if (match[0] === '+') {
+ break;
+ }
+
+ contextChanges = contextChanges || change[0] !== ' ';
+ merged.push(match);
+ matchIndex++; // Consume any additions in the other block as a conflict to attempt
+ // to pull in the remaining context after this
+
+ if (change[0] === '+') {
+ conflicted = true;
+
+ while (change[0] === '+') {
+ changes.push(change);
+ change = state.lines[++state.index];
+ }
+ }
+
+ if (match.substr(1) === change.substr(1)) {
+ changes.push(change);
+ state.index++;
+ } else {
+ conflicted = true;
+ }
+ }
+
+ if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
+ conflicted = true;
+ }
+
+ if (conflicted) {
+ return changes;
+ }
+
+ while (matchIndex < matchChanges.length) {
+ merged.push(matchChanges[matchIndex++]);
+ }
+
+ return {
+ merged: merged,
+ changes: changes
+ };
+ }
+
+ function allRemoves(changes) {
+ return changes.reduce(function (prev, change) {
+ return prev && change[0] === '-';
+ }, true);
+ }
+
+ function skipRemoveSuperset(state, removeChanges, delta) {
+ for (var i = 0; i < delta; i++) {
+ var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
+
+ if (state.lines[state.index + i] !== ' ' + changeContent) {
+ return false;
+ }
+ }
+
+ state.index += delta;
+ return true;
+ }
+
+ function calcOldNewLineCount(lines) {
+ var oldLines = 0;
+ var newLines = 0;
+ lines.forEach(function (line) {
+ if (typeof line !== 'string') {
+ var myCount = calcOldNewLineCount(line.mine);
+ var theirCount = calcOldNewLineCount(line.theirs);
+
+ if (oldLines !== undefined) {
+ if (myCount.oldLines === theirCount.oldLines) {
+ oldLines += myCount.oldLines;
+ } else {
+ oldLines = undefined;
+ }
+ }
+
+ if (newLines !== undefined) {
+ if (myCount.newLines === theirCount.newLines) {
+ newLines += myCount.newLines;
+ } else {
+ newLines = undefined;
+ }
+ }
+ } else {
+ if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
+ newLines++;
+ }
+
+ if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
+ oldLines++;
+ }
+ }
+ });
+ return {
+ oldLines: oldLines,
+ newLines: newLines
+ };
+ } // See: http://code.google.com/p/google-diff-match-patch/wiki/API
+
+
+ function convertChangesToDMP(changes) {
+ var ret = [],
+ change,
+ operation;
+
+ for (var i = 0; i < changes.length; i++) {
+ change = changes[i];
+
+ if (change.added) {
+ operation = 1;
+ } else if (change.removed) {
+ operation = -1;
+ } else {
+ operation = 0;
+ }
+
+ ret.push([operation, change.value]);
+ }
+
+ return ret;
+ }
+
+ function convertChangesToXML(changes) {
+ var ret = [];
+
+ for (var i = 0; i < changes.length; i++) {
+ var change = changes[i];
+
+ if (change.added) {
+ ret.push('');
+ } else if (change.removed) {
+ ret.push('');
+ }
+
+ ret.push(escapeHTML(change.value));
+
+ if (change.added) {
+ ret.push(' ');
+ } else if (change.removed) {
+ ret.push('');
+ }
+ }
+
+ return ret.join('');
+ }
+
+ function escapeHTML(s) {
+ var n = s;
+ n = n.replace(/&/g, '&');
+ n = n.replace(//g, '>');
+ n = n.replace(/"/g, '"');
+ return n;
+ }
+
+ exports.Diff = Diff;
+ exports.applyPatch = applyPatch;
+ exports.applyPatches = applyPatches;
+ exports.canonicalize = canonicalize;
+ exports.convertChangesToDMP = convertChangesToDMP;
+ exports.convertChangesToXML = convertChangesToXML;
+ exports.createPatch = createPatch;
+ exports.createTwoFilesPatch = createTwoFilesPatch;
+ exports.diffArrays = diffArrays;
+ exports.diffChars = diffChars;
+ exports.diffCss = diffCss;
+ exports.diffJson = diffJson;
+ exports.diffLines = diffLines;
+ exports.diffSentences = diffSentences;
+ exports.diffTrimmedLines = diffTrimmedLines;
+ exports.diffWords = diffWords;
+ exports.diffWordsWithSpace = diffWordsWithSpace;
+ exports.merge = merge;
+ exports.parsePatch = parsePatch;
+ exports.structuredPatch = structuredPatch;
+ Object.defineProperty(exports, '__esModule', {
+ value: true
+ });
+ });
+ });
+
+ /**
+ * Helpers.
+ */
+ var s$1 = 1000;
+ var m$1 = s$1 * 60;
+ var h$1 = m$1 * 60;
+ var d$1 = h$1 * 24;
+ var w$1 = d$1 * 7;
+ var y$1 = d$1 * 365.25;
+ /**
+ * Parse or format the given `val`.
+ *
+ * Options:
+ *
+ * - `long` verbose formatting [false]
+ *
+ * @param {String|Number} val
+ * @param {Object} [options]
+ * @throws {Error} throw an error if val is not a non-empty string or a number
+ * @return {String|Number}
+ * @api public
+ */
+
+ var ms$1 = function ms(val, options) {
+ options = options || {};
+
+ var type = _typeof(val);
+
+ if (type === 'string' && val.length > 0) {
+ return parse$1(val);
+ } else if (type === 'number' && isFinite(val)) {
+ return options["long"] ? fmtLong$1(val) : fmtShort$1(val);
+ }
+
+ throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val));
+ };
+ /**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
+
+
+ function parse$1(str) {
+ str = String(str);
+
+ if (str.length > 100) {
+ return;
+ }
+
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
+
+ if (!match) {
+ return;
+ }
+
+ var n = parseFloat(match[1]);
+ var type = (match[2] || 'ms').toLowerCase();
+
+ switch (type) {
+ case 'years':
+ case 'year':
+ case 'yrs':
+ case 'yr':
+ case 'y':
+ return n * y$1;
+
+ case 'weeks':
+ case 'week':
+ case 'w':
+ return n * w$1;
+
+ case 'days':
+ case 'day':
+ case 'd':
+ return n * d$1;
+
+ case 'hours':
+ case 'hour':
+ case 'hrs':
+ case 'hr':
+ case 'h':
+ return n * h$1;
+
+ case 'minutes':
+ case 'minute':
+ case 'mins':
+ case 'min':
+ case 'm':
+ return n * m$1;
+
+ case 'seconds':
+ case 'second':
+ case 'secs':
+ case 'sec':
+ case 's':
+ return n * s$1;
+
+ case 'milliseconds':
+ case 'millisecond':
+ case 'msecs':
+ case 'msec':
+ case 'ms':
+ return n;
+
+ default:
+ return undefined;
+ }
+ }
+ /**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+
+ function fmtShort$1(ms) {
+ var msAbs = Math.abs(ms);
+
+ if (msAbs >= d$1) {
+ return Math.round(ms / d$1) + 'd';
+ }
+
+ if (msAbs >= h$1) {
+ return Math.round(ms / h$1) + 'h';
+ }
+
+ if (msAbs >= m$1) {
+ return Math.round(ms / m$1) + 'm';
+ }
+
+ if (msAbs >= s$1) {
+ return Math.round(ms / s$1) + 's';
+ }
+
+ return ms + 'ms';
+ }
+ /**
+ * Long format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+
+ function fmtLong$1(ms) {
+ var msAbs = Math.abs(ms);
+
+ if (msAbs >= d$1) {
+ return plural$1(ms, msAbs, d$1, 'day');
+ }
+
+ if (msAbs >= h$1) {
+ return plural$1(ms, msAbs, h$1, 'hour');
+ }
+
+ if (msAbs >= m$1) {
+ return plural$1(ms, msAbs, m$1, 'minute');
+ }
+
+ if (msAbs >= s$1) {
+ return plural$1(ms, msAbs, s$1, 'second');
+ }
+
+ return ms + ' ms';
+ }
+ /**
+ * Pluralization helper.
+ */
+
+
+ function plural$1(ms, msAbs, n, name) {
+ var isPlural = msAbs >= n * 1.5;
+ return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
+ }
+
+ var freezing = !fails(function () {
+ // eslint-disable-next-line es/no-object-isextensible, es/no-object-preventextensions -- required for testing
+ return Object.isExtensible(Object.preventExtensions({}));
+ });
+
+ var internalMetadata = createCommonjsModule(function (module) {
+ var defineProperty = objectDefineProperty.f;
+
+
+
+
+
+ var REQUIRED = false;
+ var METADATA = uid('meta');
+ var id = 0;
+
+ // eslint-disable-next-line es/no-object-isextensible -- safe
+ var isExtensible = Object.isExtensible || function () {
+ return true;
+ };
+
+ var setMetadata = function (it) {
+ defineProperty(it, METADATA, { value: {
+ objectID: 'O' + id++, // object ID
+ weakData: {} // weak collections IDs
+ } });
+ };
+
+ var fastKey = function (it, create) {
+ // return a primitive with prefix
+ if (!isObject$1(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
+ if (!has$1(it, METADATA)) {
+ // can't set metadata to uncaught frozen object
+ if (!isExtensible(it)) return 'F';
+ // not necessary to add metadata
+ if (!create) return 'E';
+ // add missing metadata
+ setMetadata(it);
+ // return object ID
+ } return it[METADATA].objectID;
+ };
+
+ var getWeakData = function (it, create) {
+ if (!has$1(it, METADATA)) {
+ // can't set metadata to uncaught frozen object
+ if (!isExtensible(it)) return true;
+ // not necessary to add metadata
+ if (!create) return false;
+ // add missing metadata
+ setMetadata(it);
+ // return the store of weak collections IDs
+ } return it[METADATA].weakData;
+ };
+
+ // add metadata on freeze-family methods calling
+ var onFreeze = function (it) {
+ if (freezing && REQUIRED && isExtensible(it) && !has$1(it, METADATA)) setMetadata(it);
+ return it;
+ };
+
+ var enable = function () {
+ meta.enable = function () { /* empty */ };
+ REQUIRED = true;
+ var getOwnPropertyNames = objectGetOwnPropertyNames.f;
+ var splice = [].splice;
+ var test = {};
+ test[METADATA] = 1;
+
+ // prevent exposing of metadata key
+ if (getOwnPropertyNames(test).length) {
+ objectGetOwnPropertyNames.f = function (it) {
+ var result = getOwnPropertyNames(it);
+ for (var i = 0, length = result.length; i < length; i++) {
+ if (result[i] === METADATA) {
+ splice.call(result, i, 1);
+ break;
+ }
+ } return result;
+ };
+
+ _export({ target: 'Object', stat: true, forced: true }, {
+ getOwnPropertyNames: objectGetOwnPropertyNamesExternal.f
+ });
+ }
+ };
+
+ var meta = module.exports = {
+ enable: enable,
+ fastKey: fastKey,
+ getWeakData: getWeakData,
+ onFreeze: onFreeze
+ };
+
+ hiddenKeys$1[METADATA] = true;
+ });
+
+ var collection = function (CONSTRUCTOR_NAME, wrapper, common) {
+ var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== -1;
+ var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== -1;
+ var ADDER = IS_MAP ? 'set' : 'add';
+ var NativeConstructor = global_1[CONSTRUCTOR_NAME];
+ var NativePrototype = NativeConstructor && NativeConstructor.prototype;
+ var Constructor = NativeConstructor;
+ var exported = {};
+
+ var fixMethod = function (KEY) {
+ var nativeMethod = NativePrototype[KEY];
+ redefine(NativePrototype, KEY,
+ KEY == 'add' ? function add(value) {
+ nativeMethod.call(this, value === 0 ? 0 : value);
+ return this;
+ } : KEY == 'delete' ? function (key) {
+ return IS_WEAK && !isObject$1(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key);
+ } : KEY == 'get' ? function get(key) {
+ return IS_WEAK && !isObject$1(key) ? undefined : nativeMethod.call(this, key === 0 ? 0 : key);
+ } : KEY == 'has' ? function has(key) {
+ return IS_WEAK && !isObject$1(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key);
+ } : function set(key, value) {
+ nativeMethod.call(this, key === 0 ? 0 : key, value);
+ return this;
+ }
+ );
+ };
+
+ var REPLACE = isForced_1(
+ CONSTRUCTOR_NAME,
+ !isCallable(NativeConstructor) || !(IS_WEAK || NativePrototype.forEach && !fails(function () {
+ new NativeConstructor().entries().next();
+ }))
+ );
+
+ if (REPLACE) {
+ // create collection constructor
+ Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER);
+ internalMetadata.enable();
+ } else if (isForced_1(CONSTRUCTOR_NAME, true)) {
+ var instance = new Constructor();
+ // early implementations not supports chaining
+ var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;
+ // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
+ var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); });
+ // most early implementations doesn't supports iterables, most modern - not close it correctly
+ // eslint-disable-next-line no-new -- required for testing
+ var ACCEPT_ITERABLES = checkCorrectnessOfIteration(function (iterable) { new NativeConstructor(iterable); });
+ // for early implementations -0 and +0 not the same
+ var BUGGY_ZERO = !IS_WEAK && fails(function () {
+ // V8 ~ Chromium 42- fails only with 5+ elements
+ var $instance = new NativeConstructor();
+ var index = 5;
+ while (index--) $instance[ADDER](index, index);
+ return !$instance.has(-0);
+ });
+
+ if (!ACCEPT_ITERABLES) {
+ Constructor = wrapper(function (dummy, iterable) {
+ anInstance(dummy, Constructor, CONSTRUCTOR_NAME);
+ var that = inheritIfRequired(new NativeConstructor(), dummy, Constructor);
+ if (iterable != undefined) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP });
+ return that;
+ });
+ Constructor.prototype = NativePrototype;
+ NativePrototype.constructor = Constructor;
+ }
+
+ if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {
+ fixMethod('delete');
+ fixMethod('has');
+ IS_MAP && fixMethod('get');
+ }
+
+ if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);
+
+ // weak collections should not contains .clear method
+ if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear;
+ }
+
+ exported[CONSTRUCTOR_NAME] = Constructor;
+ _export({ global: true, forced: Constructor != NativeConstructor }, exported);
+
+ setToStringTag(Constructor, CONSTRUCTOR_NAME);
+
+ if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP);
+
+ return Constructor;
+ };
+
+ var defineProperty$1 = objectDefineProperty.f;
+
+
+
+
+
+
+
+
+ var fastKey = internalMetadata.fastKey;
+
+
+ var setInternalState = internalState.set;
+ var internalStateGetterFor = internalState.getterFor;
+
+ var collectionStrong = {
+ getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) {
+ var C = wrapper(function (that, iterable) {
+ anInstance(that, C, CONSTRUCTOR_NAME);
+ setInternalState(that, {
+ type: CONSTRUCTOR_NAME,
+ index: objectCreate(null),
+ first: undefined,
+ last: undefined,
+ size: 0
+ });
+ if (!descriptors) that.size = 0;
+ if (iterable != undefined) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP });
+ });
+
+ var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME);
+
+ var define = function (that, key, value) {
+ var state = getInternalState(that);
+ var entry = getEntry(that, key);
+ var previous, index;
+ // change existing entry
+ if (entry) {
+ entry.value = value;
+ // create new entry
+ } else {
+ state.last = entry = {
+ index: index = fastKey(key, true),
+ key: key,
+ value: value,
+ previous: previous = state.last,
+ next: undefined,
+ removed: false
+ };
+ if (!state.first) state.first = entry;
+ if (previous) previous.next = entry;
+ if (descriptors) state.size++;
+ else that.size++;
+ // add to index
+ if (index !== 'F') state.index[index] = entry;
+ } return that;
+ };
+
+ var getEntry = function (that, key) {
+ var state = getInternalState(that);
+ // fast case
+ var index = fastKey(key);
+ var entry;
+ if (index !== 'F') return state.index[index];
+ // frozen object case
+ for (entry = state.first; entry; entry = entry.next) {
+ if (entry.key == key) return entry;
+ }
+ };
+
+ redefineAll(C.prototype, {
+ // `{ Map, Set }.prototype.clear()` methods
+ // https://tc39.es/ecma262/#sec-map.prototype.clear
+ // https://tc39.es/ecma262/#sec-set.prototype.clear
+ clear: function clear() {
+ var that = this;
+ var state = getInternalState(that);
+ var data = state.index;
+ var entry = state.first;
+ while (entry) {
+ entry.removed = true;
+ if (entry.previous) entry.previous = entry.previous.next = undefined;
+ delete data[entry.index];
+ entry = entry.next;
+ }
+ state.first = state.last = undefined;
+ if (descriptors) state.size = 0;
+ else that.size = 0;
+ },
+ // `{ Map, Set }.prototype.delete(key)` methods
+ // https://tc39.es/ecma262/#sec-map.prototype.delete
+ // https://tc39.es/ecma262/#sec-set.prototype.delete
+ 'delete': function (key) {
+ var that = this;
+ var state = getInternalState(that);
+ var entry = getEntry(that, key);
+ if (entry) {
+ var next = entry.next;
+ var prev = entry.previous;
+ delete state.index[entry.index];
+ entry.removed = true;
+ if (prev) prev.next = next;
+ if (next) next.previous = prev;
+ if (state.first == entry) state.first = next;
+ if (state.last == entry) state.last = prev;
+ if (descriptors) state.size--;
+ else that.size--;
+ } return !!entry;
+ },
+ // `{ Map, Set }.prototype.forEach(callbackfn, thisArg = undefined)` methods
+ // https://tc39.es/ecma262/#sec-map.prototype.foreach
+ // https://tc39.es/ecma262/#sec-set.prototype.foreach
+ forEach: function forEach(callbackfn /* , that = undefined */) {
+ var state = getInternalState(this);
+ var boundFunction = functionBindContext(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);
+ var entry;
+ while (entry = entry ? entry.next : state.first) {
+ boundFunction(entry.value, entry.key, this);
+ // revert to the last existing entry
+ while (entry && entry.removed) entry = entry.previous;
+ }
+ },
+ // `{ Map, Set}.prototype.has(key)` methods
+ // https://tc39.es/ecma262/#sec-map.prototype.has
+ // https://tc39.es/ecma262/#sec-set.prototype.has
+ has: function has(key) {
+ return !!getEntry(this, key);
+ }
+ });
+
+ redefineAll(C.prototype, IS_MAP ? {
+ // `Map.prototype.get(key)` method
+ // https://tc39.es/ecma262/#sec-map.prototype.get
+ get: function get(key) {
+ var entry = getEntry(this, key);
+ return entry && entry.value;
+ },
+ // `Map.prototype.set(key, value)` method
+ // https://tc39.es/ecma262/#sec-map.prototype.set
+ set: function set(key, value) {
+ return define(this, key === 0 ? 0 : key, value);
+ }
+ } : {
+ // `Set.prototype.add(value)` method
+ // https://tc39.es/ecma262/#sec-set.prototype.add
+ add: function add(value) {
+ return define(this, value = value === 0 ? 0 : value, value);
+ }
+ });
+ if (descriptors) defineProperty$1(C.prototype, 'size', {
+ get: function () {
+ return getInternalState(this).size;
+ }
+ });
+ return C;
+ },
+ setStrong: function (C, CONSTRUCTOR_NAME, IS_MAP) {
+ var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator';
+ var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME);
+ var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME);
+ // `{ Map, Set }.prototype.{ keys, values, entries, @@iterator }()` methods
+ // https://tc39.es/ecma262/#sec-map.prototype.entries
+ // https://tc39.es/ecma262/#sec-map.prototype.keys
+ // https://tc39.es/ecma262/#sec-map.prototype.values
+ // https://tc39.es/ecma262/#sec-map.prototype-@@iterator
+ // https://tc39.es/ecma262/#sec-set.prototype.entries
+ // https://tc39.es/ecma262/#sec-set.prototype.keys
+ // https://tc39.es/ecma262/#sec-set.prototype.values
+ // https://tc39.es/ecma262/#sec-set.prototype-@@iterator
+ defineIterator(C, CONSTRUCTOR_NAME, function (iterated, kind) {
+ setInternalState(this, {
+ type: ITERATOR_NAME,
+ target: iterated,
+ state: getInternalCollectionState(iterated),
+ kind: kind,
+ last: undefined
+ });
+ }, function () {
+ var state = getInternalIteratorState(this);
+ var kind = state.kind;
+ var entry = state.last;
+ // revert to the last existing entry
+ while (entry && entry.removed) entry = entry.previous;
+ // get next entry
+ if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) {
+ // or finish the iteration
+ state.target = undefined;
+ return { value: undefined, done: true };
+ }
+ // return step by kind
+ if (kind == 'keys') return { value: entry.key, done: false };
+ if (kind == 'values') return { value: entry.value, done: false };
+ return { value: [entry.key, entry.value], done: false };
+ }, IS_MAP ? 'entries' : 'values', !IS_MAP, true);
+
+ // `{ Map, Set }.prototype[@@species]` accessors
+ // https://tc39.es/ecma262/#sec-get-map-@@species
+ // https://tc39.es/ecma262/#sec-get-set-@@species
+ setSpecies(CONSTRUCTOR_NAME);
+ }
+ };
+
+ // `Set` constructor
+ // https://tc39.es/ecma262/#sec-set-objects
+ collection('Set', function (init) {
+ return function Set() { return init(this, arguments.length ? arguments[0] : undefined); };
+ }, collectionStrong);
+
+ // eslint-disable-next-line es/no-object-assign -- safe
+ var $assign = Object.assign;
+ // eslint-disable-next-line es/no-object-defineproperty -- required for testing
+ var defineProperty = Object.defineProperty;
+
+ // `Object.assign` method
+ // https://tc39.es/ecma262/#sec-object.assign
+ var objectAssign = !$assign || fails(function () {
+ // should have correct order of operations (Edge bug)
+ if (descriptors && $assign({ b: 1 }, $assign(defineProperty({}, 'a', {
+ enumerable: true,
+ get: function () {
+ defineProperty(this, 'b', {
+ value: 3,
+ enumerable: false
+ });
+ }
+ }), { b: 2 })).b !== 1) return true;
+ // should work with symbols and should have deterministic property order (V8 bug)
+ var A = {};
+ var B = {};
+ // eslint-disable-next-line es/no-symbol -- safe
+ var symbol = Symbol();
+ var alphabet = 'abcdefghijklmnopqrst';
+ A[symbol] = 7;
+ alphabet.split('').forEach(function (chr) { B[chr] = chr; });
+ return $assign({}, A)[symbol] != 7 || objectKeys($assign({}, B)).join('') != alphabet;
+ }) ? function assign(target, source) { // eslint-disable-line no-unused-vars -- required for `.length`
+ var T = toObject(target);
+ var argumentsLength = arguments.length;
+ var index = 1;
+ var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
+ var propertyIsEnumerable = objectPropertyIsEnumerable.f;
+ while (argumentsLength > index) {
+ var S = indexedObject(arguments[index++]);
+ var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);
+ var length = keys.length;
+ var j = 0;
+ var key;
+ while (length > j) {
+ key = keys[j++];
+ if (!descriptors || propertyIsEnumerable.call(S, key)) T[key] = S[key];
+ }
+ } return T;
+ } : $assign;
+
+ // `Object.assign` method
+ // https://tc39.es/ecma262/#sec-object.assign
+ // eslint-disable-next-line es/no-object-assign -- required for testing
+ _export({ target: 'Object', stat: true, forced: Object.assign !== objectAssign }, {
+ assign: objectAssign
+ });
+
+ var onFreeze = internalMetadata.onFreeze;
+
+ // eslint-disable-next-line es/no-object-freeze -- safe
+ var $freeze = Object.freeze;
+ var FAILS_ON_PRIMITIVES = fails(function () { $freeze(1); });
+
+ // `Object.freeze` method
+ // https://tc39.es/ecma262/#sec-object.freeze
+ _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !freezing }, {
+ freeze: function freeze(it) {
+ return $freeze && isObject$1(it) ? $freeze(onFreeze(it)) : it;
+ }
+ });
+
+ var browser$2 = true;
+
+ // This alphabet uses `A-Za-z0-9_-` symbols. The genetic algorithm helped
+ // optimize the gzip compression for this alphabet.
+ var urlAlphabet = 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW';
+
+ var customAlphabet = function customAlphabet(alphabet, size) {
+ return function () {
+ var id = ''; // A compact alternative for `for (var i = 0; i < step; i++)`.
+
+ var i = size;
+
+ while (i--) {
+ // `| 0` is more compact and faster than `Math.floor()`.
+ id += alphabet[Math.random() * alphabet.length | 0];
+ }
+
+ return id;
+ };
+ };
+
+ var nanoid = function nanoid() {
+ var size = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 21;
+ var id = ''; // A compact alternative for `for (var i = 0; i < step; i++)`.
+
+ var i = size;
+
+ while (i--) {
+ // `| 0` is more compact and faster than `Math.floor()`.
+ id += urlAlphabet[Math.random() * 64 | 0];
+ }
+
+ return id;
+ };
+
+ var nonSecure = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ nanoid: nanoid,
+ customAlphabet: customAlphabet
+ });
+
+ var he = createCommonjsModule(function (module, exports) {
+
+ (function (root) {
+ // Detect free variables `exports`.
+ var freeExports = exports; // Detect free variable `module`.
+
+ var freeModule = module && module.exports == freeExports && module; // Detect free variable `global`, from Node.js or Browserified code,
+ // and use it as `root`.
+
+ var freeGlobal = _typeof(commonjsGlobal) == 'object' && commonjsGlobal;
+
+ if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
+ root = freeGlobal;
+ }
+ /*--------------------------------------------------------------------------*/
+ // All astral symbols.
+
+
+ var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; // All ASCII symbols (not just printable ASCII) except those listed in the
+ // first column of the overrides table.
+ // https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides
+
+ var regexAsciiWhitelist = /[\x01-\x7F]/g; // All BMP symbols that are not ASCII newlines, printable ASCII symbols, or
+ // code points listed in the first column of the overrides table on
+ // https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides.
+
+ var regexBmpWhitelist = /[\x01-\t\x0B\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g;
+ var regexEncodeNonAscii = /<\u20D2|=\u20E5|>\u20D2|\u205F\u200A|\u219D\u0338|\u2202\u0338|\u2220\u20D2|\u2229\uFE00|\u222A\uFE00|\u223C\u20D2|\u223D\u0331|\u223E\u0333|\u2242\u0338|\u224B\u0338|\u224D\u20D2|\u224E\u0338|\u224F\u0338|\u2250\u0338|\u2261\u20E5|\u2264\u20D2|\u2265\u20D2|\u2266\u0338|\u2267\u0338|\u2268\uFE00|\u2269\uFE00|\u226A\u0338|\u226A\u20D2|\u226B\u0338|\u226B\u20D2|\u227F\u0338|\u2282\u20D2|\u2283\u20D2|\u228A\uFE00|\u228B\uFE00|\u228F\u0338|\u2290\u0338|\u2293\uFE00|\u2294\uFE00|\u22B4\u20D2|\u22B5\u20D2|\u22D8\u0338|\u22D9\u0338|\u22DA\uFE00|\u22DB\uFE00|\u22F5\u0338|\u22F9\u0338|\u2933\u0338|\u29CF\u0338|\u29D0\u0338|\u2A6D\u0338|\u2A70\u0338|\u2A7D\u0338|\u2A7E\u0338|\u2AA1\u0338|\u2AA2\u0338|\u2AAC\uFE00|\u2AAD\uFE00|\u2AAF\u0338|\u2AB0\u0338|\u2AC5\u0338|\u2AC6\u0338|\u2ACB\uFE00|\u2ACC\uFE00|\u2AFD\u20E5|[\xA0-\u0113\u0116-\u0122\u0124-\u012B\u012E-\u014D\u0150-\u017E\u0192\u01B5\u01F5\u0237\u02C6\u02C7\u02D8-\u02DD\u0311\u0391-\u03A1\u03A3-\u03A9\u03B1-\u03C9\u03D1\u03D2\u03D5\u03D6\u03DC\u03DD\u03F0\u03F1\u03F5\u03F6\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E\u045F\u2002-\u2005\u2007-\u2010\u2013-\u2016\u2018-\u201A\u201C-\u201E\u2020-\u2022\u2025\u2026\u2030-\u2035\u2039\u203A\u203E\u2041\u2043\u2044\u204F\u2057\u205F-\u2063\u20AC\u20DB\u20DC\u2102\u2105\u210A-\u2113\u2115-\u211E\u2122\u2124\u2127-\u2129\u212C\u212D\u212F-\u2131\u2133-\u2138\u2145-\u2148\u2153-\u215E\u2190-\u219B\u219D-\u21A7\u21A9-\u21AE\u21B0-\u21B3\u21B5-\u21B7\u21BA-\u21DB\u21DD\u21E4\u21E5\u21F5\u21FD-\u2205\u2207-\u2209\u220B\u220C\u220F-\u2214\u2216-\u2218\u221A\u221D-\u2238\u223A-\u2257\u2259\u225A\u225C\u225F-\u2262\u2264-\u228B\u228D-\u229B\u229D-\u22A5\u22A7-\u22B0\u22B2-\u22BB\u22BD-\u22DB\u22DE-\u22E3\u22E6-\u22F7\u22F9-\u22FE\u2305\u2306\u2308-\u2310\u2312\u2313\u2315\u2316\u231C-\u231F\u2322\u2323\u232D\u232E\u2336\u233D\u233F\u237C\u23B0\u23B1\u23B4-\u23B6\u23DC-\u23DF\u23E2\u23E7\u2423\u24C8\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2550-\u256C\u2580\u2584\u2588\u2591-\u2593\u25A1\u25AA\u25AB\u25AD\u25AE\u25B1\u25B3-\u25B5\u25B8\u25B9\u25BD-\u25BF\u25C2\u25C3\u25CA\u25CB\u25EC\u25EF\u25F8-\u25FC\u2605\u2606\u260E\u2640\u2642\u2660\u2663\u2665\u2666\u266A\u266D-\u266F\u2713\u2717\u2720\u2736\u2758\u2772\u2773\u27C8\u27C9\u27E6-\u27ED\u27F5-\u27FA\u27FC\u27FF\u2902-\u2905\u290C-\u2913\u2916\u2919-\u2920\u2923-\u292A\u2933\u2935-\u2939\u293C\u293D\u2945\u2948-\u294B\u294E-\u2976\u2978\u2979\u297B-\u297F\u2985\u2986\u298B-\u2996\u299A\u299C\u299D\u29A4-\u29B7\u29B9\u29BB\u29BC\u29BE-\u29C5\u29C9\u29CD-\u29D0\u29DC-\u29DE\u29E3-\u29E5\u29EB\u29F4\u29F6\u2A00-\u2A02\u2A04\u2A06\u2A0C\u2A0D\u2A10-\u2A17\u2A22-\u2A27\u2A29\u2A2A\u2A2D-\u2A31\u2A33-\u2A3C\u2A3F\u2A40\u2A42-\u2A4D\u2A50\u2A53-\u2A58\u2A5A-\u2A5D\u2A5F\u2A66\u2A6A\u2A6D-\u2A75\u2A77-\u2A9A\u2A9D-\u2AA2\u2AA4-\u2AB0\u2AB3-\u2AC8\u2ACB\u2ACC\u2ACF-\u2ADB\u2AE4\u2AE6-\u2AE9\u2AEB-\u2AF3\u2AFD\uFB00-\uFB04]|\uD835[\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDCCF\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDD6B]/g;
+ var encodeMap = {
+ '\xAD': 'shy',
+ "\u200C": 'zwnj',
+ "\u200D": 'zwj',
+ "\u200E": 'lrm',
+ "\u2063": 'ic',
+ "\u2062": 'it',
+ "\u2061": 'af',
+ "\u200F": 'rlm',
+ "\u200B": 'ZeroWidthSpace',
+ "\u2060": 'NoBreak',
+ "\u0311": 'DownBreve',
+ "\u20DB": 'tdot',
+ "\u20DC": 'DotDot',
+ '\t': 'Tab',
+ '\n': 'NewLine',
+ "\u2008": 'puncsp',
+ "\u205F": 'MediumSpace',
+ "\u2009": 'thinsp',
+ "\u200A": 'hairsp',
+ "\u2004": 'emsp13',
+ "\u2002": 'ensp',
+ "\u2005": 'emsp14',
+ "\u2003": 'emsp',
+ "\u2007": 'numsp',
+ '\xA0': 'nbsp',
+ "\u205F\u200A": 'ThickSpace',
+ "\u203E": 'oline',
+ '_': 'lowbar',
+ "\u2010": 'dash',
+ "\u2013": 'ndash',
+ "\u2014": 'mdash',
+ "\u2015": 'horbar',
+ ',': 'comma',
+ ';': 'semi',
+ "\u204F": 'bsemi',
+ ':': 'colon',
+ "\u2A74": 'Colone',
+ '!': 'excl',
+ '\xA1': 'iexcl',
+ '?': 'quest',
+ '\xBF': 'iquest',
+ '.': 'period',
+ "\u2025": 'nldr',
+ "\u2026": 'mldr',
+ '\xB7': 'middot',
+ '\'': 'apos',
+ "\u2018": 'lsquo',
+ "\u2019": 'rsquo',
+ "\u201A": 'sbquo',
+ "\u2039": 'lsaquo',
+ "\u203A": 'rsaquo',
+ '"': 'quot',
+ "\u201C": 'ldquo',
+ "\u201D": 'rdquo',
+ "\u201E": 'bdquo',
+ '\xAB': 'laquo',
+ '\xBB': 'raquo',
+ '(': 'lpar',
+ ')': 'rpar',
+ '[': 'lsqb',
+ ']': 'rsqb',
+ '{': 'lcub',
+ '}': 'rcub',
+ "\u2308": 'lceil',
+ "\u2309": 'rceil',
+ "\u230A": 'lfloor',
+ "\u230B": 'rfloor',
+ "\u2985": 'lopar',
+ "\u2986": 'ropar',
+ "\u298B": 'lbrke',
+ "\u298C": 'rbrke',
+ "\u298D": 'lbrkslu',
+ "\u298E": 'rbrksld',
+ "\u298F": 'lbrksld',
+ "\u2990": 'rbrkslu',
+ "\u2991": 'langd',
+ "\u2992": 'rangd',
+ "\u2993": 'lparlt',
+ "\u2994": 'rpargt',
+ "\u2995": 'gtlPar',
+ "\u2996": 'ltrPar',
+ "\u27E6": 'lobrk',
+ "\u27E7": 'robrk',
+ "\u27E8": 'lang',
+ "\u27E9": 'rang',
+ "\u27EA": 'Lang',
+ "\u27EB": 'Rang',
+ "\u27EC": 'loang',
+ "\u27ED": 'roang',
+ "\u2772": 'lbbrk',
+ "\u2773": 'rbbrk',
+ "\u2016": 'Vert',
+ '\xA7': 'sect',
+ '\xB6': 'para',
+ '@': 'commat',
+ '*': 'ast',
+ '/': 'sol',
+ 'undefined': null,
+ '&': 'amp',
+ '#': 'num',
+ '%': 'percnt',
+ "\u2030": 'permil',
+ "\u2031": 'pertenk',
+ "\u2020": 'dagger',
+ "\u2021": 'Dagger',
+ "\u2022": 'bull',
+ "\u2043": 'hybull',
+ "\u2032": 'prime',
+ "\u2033": 'Prime',
+ "\u2034": 'tprime',
+ "\u2057": 'qprime',
+ "\u2035": 'bprime',
+ "\u2041": 'caret',
+ '`': 'grave',
+ '\xB4': 'acute',
+ "\u02DC": 'tilde',
+ '^': 'Hat',
+ '\xAF': 'macr',
+ "\u02D8": 'breve',
+ "\u02D9": 'dot',
+ '\xA8': 'die',
+ "\u02DA": 'ring',
+ "\u02DD": 'dblac',
+ '\xB8': 'cedil',
+ "\u02DB": 'ogon',
+ "\u02C6": 'circ',
+ "\u02C7": 'caron',
+ '\xB0': 'deg',
+ '\xA9': 'copy',
+ '\xAE': 'reg',
+ "\u2117": 'copysr',
+ "\u2118": 'wp',
+ "\u211E": 'rx',
+ "\u2127": 'mho',
+ "\u2129": 'iiota',
+ "\u2190": 'larr',
+ "\u219A": 'nlarr',
+ "\u2192": 'rarr',
+ "\u219B": 'nrarr',
+ "\u2191": 'uarr',
+ "\u2193": 'darr',
+ "\u2194": 'harr',
+ "\u21AE": 'nharr',
+ "\u2195": 'varr',
+ "\u2196": 'nwarr',
+ "\u2197": 'nearr',
+ "\u2198": 'searr',
+ "\u2199": 'swarr',
+ "\u219D": 'rarrw',
+ "\u219D\u0338": 'nrarrw',
+ "\u219E": 'Larr',
+ "\u219F": 'Uarr',
+ "\u21A0": 'Rarr',
+ "\u21A1": 'Darr',
+ "\u21A2": 'larrtl',
+ "\u21A3": 'rarrtl',
+ "\u21A4": 'mapstoleft',
+ "\u21A5": 'mapstoup',
+ "\u21A6": 'map',
+ "\u21A7": 'mapstodown',
+ "\u21A9": 'larrhk',
+ "\u21AA": 'rarrhk',
+ "\u21AB": 'larrlp',
+ "\u21AC": 'rarrlp',
+ "\u21AD": 'harrw',
+ "\u21B0": 'lsh',
+ "\u21B1": 'rsh',
+ "\u21B2": 'ldsh',
+ "\u21B3": 'rdsh',
+ "\u21B5": 'crarr',
+ "\u21B6": 'cularr',
+ "\u21B7": 'curarr',
+ "\u21BA": 'olarr',
+ "\u21BB": 'orarr',
+ "\u21BC": 'lharu',
+ "\u21BD": 'lhard',
+ "\u21BE": 'uharr',
+ "\u21BF": 'uharl',
+ "\u21C0": 'rharu',
+ "\u21C1": 'rhard',
+ "\u21C2": 'dharr',
+ "\u21C3": 'dharl',
+ "\u21C4": 'rlarr',
+ "\u21C5": 'udarr',
+ "\u21C6": 'lrarr',
+ "\u21C7": 'llarr',
+ "\u21C8": 'uuarr',
+ "\u21C9": 'rrarr',
+ "\u21CA": 'ddarr',
+ "\u21CB": 'lrhar',
+ "\u21CC": 'rlhar',
+ "\u21D0": 'lArr',
+ "\u21CD": 'nlArr',
+ "\u21D1": 'uArr',
+ "\u21D2": 'rArr',
+ "\u21CF": 'nrArr',
+ "\u21D3": 'dArr',
+ "\u21D4": 'iff',
+ "\u21CE": 'nhArr',
+ "\u21D5": 'vArr',
+ "\u21D6": 'nwArr',
+ "\u21D7": 'neArr',
+ "\u21D8": 'seArr',
+ "\u21D9": 'swArr',
+ "\u21DA": 'lAarr',
+ "\u21DB": 'rAarr',
+ "\u21DD": 'zigrarr',
+ "\u21E4": 'larrb',
+ "\u21E5": 'rarrb',
+ "\u21F5": 'duarr',
+ "\u21FD": 'loarr',
+ "\u21FE": 'roarr',
+ "\u21FF": 'hoarr',
+ "\u2200": 'forall',
+ "\u2201": 'comp',
+ "\u2202": 'part',
+ "\u2202\u0338": 'npart',
+ "\u2203": 'exist',
+ "\u2204": 'nexist',
+ "\u2205": 'empty',
+ "\u2207": 'Del',
+ "\u2208": 'in',
+ "\u2209": 'notin',
+ "\u220B": 'ni',
+ "\u220C": 'notni',
+ "\u03F6": 'bepsi',
+ "\u220F": 'prod',
+ "\u2210": 'coprod',
+ "\u2211": 'sum',
+ '+': 'plus',
+ '\xB1': 'pm',
+ '\xF7': 'div',
+ '\xD7': 'times',
+ '<': 'lt',
+ "\u226E": 'nlt',
+ "<\u20D2": 'nvlt',
+ '=': 'equals',
+ "\u2260": 'ne',
+ "=\u20E5": 'bne',
+ "\u2A75": 'Equal',
+ '>': 'gt',
+ "\u226F": 'ngt',
+ ">\u20D2": 'nvgt',
+ '\xAC': 'not',
+ '|': 'vert',
+ '\xA6': 'brvbar',
+ "\u2212": 'minus',
+ "\u2213": 'mp',
+ "\u2214": 'plusdo',
+ "\u2044": 'frasl',
+ "\u2216": 'setmn',
+ "\u2217": 'lowast',
+ "\u2218": 'compfn',
+ "\u221A": 'Sqrt',
+ "\u221D": 'prop',
+ "\u221E": 'infin',
+ "\u221F": 'angrt',
+ "\u2220": 'ang',
+ "\u2220\u20D2": 'nang',
+ "\u2221": 'angmsd',
+ "\u2222": 'angsph',
+ "\u2223": 'mid',
+ "\u2224": 'nmid',
+ "\u2225": 'par',
+ "\u2226": 'npar',
+ "\u2227": 'and',
+ "\u2228": 'or',
+ "\u2229": 'cap',
+ "\u2229\uFE00": 'caps',
+ "\u222A": 'cup',
+ "\u222A\uFE00": 'cups',
+ "\u222B": 'int',
+ "\u222C": 'Int',
+ "\u222D": 'tint',
+ "\u2A0C": 'qint',
+ "\u222E": 'oint',
+ "\u222F": 'Conint',
+ "\u2230": 'Cconint',
+ "\u2231": 'cwint',
+ "\u2232": 'cwconint',
+ "\u2233": 'awconint',
+ "\u2234": 'there4',
+ "\u2235": 'becaus',
+ "\u2236": 'ratio',
+ "\u2237": 'Colon',
+ "\u2238": 'minusd',
+ "\u223A": 'mDDot',
+ "\u223B": 'homtht',
+ "\u223C": 'sim',
+ "\u2241": 'nsim',
+ "\u223C\u20D2": 'nvsim',
+ "\u223D": 'bsim',
+ "\u223D\u0331": 'race',
+ "\u223E": 'ac',
+ "\u223E\u0333": 'acE',
+ "\u223F": 'acd',
+ "\u2240": 'wr',
+ "\u2242": 'esim',
+ "\u2242\u0338": 'nesim',
+ "\u2243": 'sime',
+ "\u2244": 'nsime',
+ "\u2245": 'cong',
+ "\u2247": 'ncong',
+ "\u2246": 'simne',
+ "\u2248": 'ap',
+ "\u2249": 'nap',
+ "\u224A": 'ape',
+ "\u224B": 'apid',
+ "\u224B\u0338": 'napid',
+ "\u224C": 'bcong',
+ "\u224D": 'CupCap',
+ "\u226D": 'NotCupCap',
+ "\u224D\u20D2": 'nvap',
+ "\u224E": 'bump',
+ "\u224E\u0338": 'nbump',
+ "\u224F": 'bumpe',
+ "\u224F\u0338": 'nbumpe',
+ "\u2250": 'doteq',
+ "\u2250\u0338": 'nedot',
+ "\u2251": 'eDot',
+ "\u2252": 'efDot',
+ "\u2253": 'erDot',
+ "\u2254": 'colone',
+ "\u2255": 'ecolon',
+ "\u2256": 'ecir',
+ "\u2257": 'cire',
+ "\u2259": 'wedgeq',
+ "\u225A": 'veeeq',
+ "\u225C": 'trie',
+ "\u225F": 'equest',
+ "\u2261": 'equiv',
+ "\u2262": 'nequiv',
+ "\u2261\u20E5": 'bnequiv',
+ "\u2264": 'le',
+ "\u2270": 'nle',
+ "\u2264\u20D2": 'nvle',
+ "\u2265": 'ge',
+ "\u2271": 'nge',
+ "\u2265\u20D2": 'nvge',
+ "\u2266": 'lE',
+ "\u2266\u0338": 'nlE',
+ "\u2267": 'gE',
+ "\u2267\u0338": 'ngE',
+ "\u2268\uFE00": 'lvnE',
+ "\u2268": 'lnE',
+ "\u2269": 'gnE',
+ "\u2269\uFE00": 'gvnE',
+ "\u226A": 'll',
+ "\u226A\u0338": 'nLtv',
+ "\u226A\u20D2": 'nLt',
+ "\u226B": 'gg',
+ "\u226B\u0338": 'nGtv',
+ "\u226B\u20D2": 'nGt',
+ "\u226C": 'twixt',
+ "\u2272": 'lsim',
+ "\u2274": 'nlsim',
+ "\u2273": 'gsim',
+ "\u2275": 'ngsim',
+ "\u2276": 'lg',
+ "\u2278": 'ntlg',
+ "\u2277": 'gl',
+ "\u2279": 'ntgl',
+ "\u227A": 'pr',
+ "\u2280": 'npr',
+ "\u227B": 'sc',
+ "\u2281": 'nsc',
+ "\u227C": 'prcue',
+ "\u22E0": 'nprcue',
+ "\u227D": 'sccue',
+ "\u22E1": 'nsccue',
+ "\u227E": 'prsim',
+ "\u227F": 'scsim',
+ "\u227F\u0338": 'NotSucceedsTilde',
+ "\u2282": 'sub',
+ "\u2284": 'nsub',
+ "\u2282\u20D2": 'vnsub',
+ "\u2283": 'sup',
+ "\u2285": 'nsup',
+ "\u2283\u20D2": 'vnsup',
+ "\u2286": 'sube',
+ "\u2288": 'nsube',
+ "\u2287": 'supe',
+ "\u2289": 'nsupe',
+ "\u228A\uFE00": 'vsubne',
+ "\u228A": 'subne',
+ "\u228B\uFE00": 'vsupne',
+ "\u228B": 'supne',
+ "\u228D": 'cupdot',
+ "\u228E": 'uplus',
+ "\u228F": 'sqsub',
+ "\u228F\u0338": 'NotSquareSubset',
+ "\u2290": 'sqsup',
+ "\u2290\u0338": 'NotSquareSuperset',
+ "\u2291": 'sqsube',
+ "\u22E2": 'nsqsube',
+ "\u2292": 'sqsupe',
+ "\u22E3": 'nsqsupe',
+ "\u2293": 'sqcap',
+ "\u2293\uFE00": 'sqcaps',
+ "\u2294": 'sqcup',
+ "\u2294\uFE00": 'sqcups',
+ "\u2295": 'oplus',
+ "\u2296": 'ominus',
+ "\u2297": 'otimes',
+ "\u2298": 'osol',
+ "\u2299": 'odot',
+ "\u229A": 'ocir',
+ "\u229B": 'oast',
+ "\u229D": 'odash',
+ "\u229E": 'plusb',
+ "\u229F": 'minusb',
+ "\u22A0": 'timesb',
+ "\u22A1": 'sdotb',
+ "\u22A2": 'vdash',
+ "\u22AC": 'nvdash',
+ "\u22A3": 'dashv',
+ "\u22A4": 'top',
+ "\u22A5": 'bot',
+ "\u22A7": 'models',
+ "\u22A8": 'vDash',
+ "\u22AD": 'nvDash',
+ "\u22A9": 'Vdash',
+ "\u22AE": 'nVdash',
+ "\u22AA": 'Vvdash',
+ "\u22AB": 'VDash',
+ "\u22AF": 'nVDash',
+ "\u22B0": 'prurel',
+ "\u22B2": 'vltri',
+ "\u22EA": 'nltri',
+ "\u22B3": 'vrtri',
+ "\u22EB": 'nrtri',
+ "\u22B4": 'ltrie',
+ "\u22EC": 'nltrie',
+ "\u22B4\u20D2": 'nvltrie',
+ "\u22B5": 'rtrie',
+ "\u22ED": 'nrtrie',
+ "\u22B5\u20D2": 'nvrtrie',
+ "\u22B6": 'origof',
+ "\u22B7": 'imof',
+ "\u22B8": 'mumap',
+ "\u22B9": 'hercon',
+ "\u22BA": 'intcal',
+ "\u22BB": 'veebar',
+ "\u22BD": 'barvee',
+ "\u22BE": 'angrtvb',
+ "\u22BF": 'lrtri',
+ "\u22C0": 'Wedge',
+ "\u22C1": 'Vee',
+ "\u22C2": 'xcap',
+ "\u22C3": 'xcup',
+ "\u22C4": 'diam',
+ "\u22C5": 'sdot',
+ "\u22C6": 'Star',
+ "\u22C7": 'divonx',
+ "\u22C8": 'bowtie',
+ "\u22C9": 'ltimes',
+ "\u22CA": 'rtimes',
+ "\u22CB": 'lthree',
+ "\u22CC": 'rthree',
+ "\u22CD": 'bsime',
+ "\u22CE": 'cuvee',
+ "\u22CF": 'cuwed',
+ "\u22D0": 'Sub',
+ "\u22D1": 'Sup',
+ "\u22D2": 'Cap',
+ "\u22D3": 'Cup',
+ "\u22D4": 'fork',
+ "\u22D5": 'epar',
+ "\u22D6": 'ltdot',
+ "\u22D7": 'gtdot',
+ "\u22D8": 'Ll',
+ "\u22D8\u0338": 'nLl',
+ "\u22D9": 'Gg',
+ "\u22D9\u0338": 'nGg',
+ "\u22DA\uFE00": 'lesg',
+ "\u22DA": 'leg',
+ "\u22DB": 'gel',
+ "\u22DB\uFE00": 'gesl',
+ "\u22DE": 'cuepr',
+ "\u22DF": 'cuesc',
+ "\u22E6": 'lnsim',
+ "\u22E7": 'gnsim',
+ "\u22E8": 'prnsim',
+ "\u22E9": 'scnsim',
+ "\u22EE": 'vellip',
+ "\u22EF": 'ctdot',
+ "\u22F0": 'utdot',
+ "\u22F1": 'dtdot',
+ "\u22F2": 'disin',
+ "\u22F3": 'isinsv',
+ "\u22F4": 'isins',
+ "\u22F5": 'isindot',
+ "\u22F5\u0338": 'notindot',
+ "\u22F6": 'notinvc',
+ "\u22F7": 'notinvb',
+ "\u22F9": 'isinE',
+ "\u22F9\u0338": 'notinE',
+ "\u22FA": 'nisd',
+ "\u22FB": 'xnis',
+ "\u22FC": 'nis',
+ "\u22FD": 'notnivc',
+ "\u22FE": 'notnivb',
+ "\u2305": 'barwed',
+ "\u2306": 'Barwed',
+ "\u230C": 'drcrop',
+ "\u230D": 'dlcrop',
+ "\u230E": 'urcrop',
+ "\u230F": 'ulcrop',
+ "\u2310": 'bnot',
+ "\u2312": 'profline',
+ "\u2313": 'profsurf',
+ "\u2315": 'telrec',
+ "\u2316": 'target',
+ "\u231C": 'ulcorn',
+ "\u231D": 'urcorn',
+ "\u231E": 'dlcorn',
+ "\u231F": 'drcorn',
+ "\u2322": 'frown',
+ "\u2323": 'smile',
+ "\u232D": 'cylcty',
+ "\u232E": 'profalar',
+ "\u2336": 'topbot',
+ "\u233D": 'ovbar',
+ "\u233F": 'solbar',
+ "\u237C": 'angzarr',
+ "\u23B0": 'lmoust',
+ "\u23B1": 'rmoust',
+ "\u23B4": 'tbrk',
+ "\u23B5": 'bbrk',
+ "\u23B6": 'bbrktbrk',
+ "\u23DC": 'OverParenthesis',
+ "\u23DD": 'UnderParenthesis',
+ "\u23DE": 'OverBrace',
+ "\u23DF": 'UnderBrace',
+ "\u23E2": 'trpezium',
+ "\u23E7": 'elinters',
+ "\u2423": 'blank',
+ "\u2500": 'boxh',
+ "\u2502": 'boxv',
+ "\u250C": 'boxdr',
+ "\u2510": 'boxdl',
+ "\u2514": 'boxur',
+ "\u2518": 'boxul',
+ "\u251C": 'boxvr',
+ "\u2524": 'boxvl',
+ "\u252C": 'boxhd',
+ "\u2534": 'boxhu',
+ "\u253C": 'boxvh',
+ "\u2550": 'boxH',
+ "\u2551": 'boxV',
+ "\u2552": 'boxdR',
+ "\u2553": 'boxDr',
+ "\u2554": 'boxDR',
+ "\u2555": 'boxdL',
+ "\u2556": 'boxDl',
+ "\u2557": 'boxDL',
+ "\u2558": 'boxuR',
+ "\u2559": 'boxUr',
+ "\u255A": 'boxUR',
+ "\u255B": 'boxuL',
+ "\u255C": 'boxUl',
+ "\u255D": 'boxUL',
+ "\u255E": 'boxvR',
+ "\u255F": 'boxVr',
+ "\u2560": 'boxVR',
+ "\u2561": 'boxvL',
+ "\u2562": 'boxVl',
+ "\u2563": 'boxVL',
+ "\u2564": 'boxHd',
+ "\u2565": 'boxhD',
+ "\u2566": 'boxHD',
+ "\u2567": 'boxHu',
+ "\u2568": 'boxhU',
+ "\u2569": 'boxHU',
+ "\u256A": 'boxvH',
+ "\u256B": 'boxVh',
+ "\u256C": 'boxVH',
+ "\u2580": 'uhblk',
+ "\u2584": 'lhblk',
+ "\u2588": 'block',
+ "\u2591": 'blk14',
+ "\u2592": 'blk12',
+ "\u2593": 'blk34',
+ "\u25A1": 'squ',
+ "\u25AA": 'squf',
+ "\u25AB": 'EmptyVerySmallSquare',
+ "\u25AD": 'rect',
+ "\u25AE": 'marker',
+ "\u25B1": 'fltns',
+ "\u25B3": 'xutri',
+ "\u25B4": 'utrif',
+ "\u25B5": 'utri',
+ "\u25B8": 'rtrif',
+ "\u25B9": 'rtri',
+ "\u25BD": 'xdtri',
+ "\u25BE": 'dtrif',
+ "\u25BF": 'dtri',
+ "\u25C2": 'ltrif',
+ "\u25C3": 'ltri',
+ "\u25CA": 'loz',
+ "\u25CB": 'cir',
+ "\u25EC": 'tridot',
+ "\u25EF": 'xcirc',
+ "\u25F8": 'ultri',
+ "\u25F9": 'urtri',
+ "\u25FA": 'lltri',
+ "\u25FB": 'EmptySmallSquare',
+ "\u25FC": 'FilledSmallSquare',
+ "\u2605": 'starf',
+ "\u2606": 'star',
+ "\u260E": 'phone',
+ "\u2640": 'female',
+ "\u2642": 'male',
+ "\u2660": 'spades',
+ "\u2663": 'clubs',
+ "\u2665": 'hearts',
+ "\u2666": 'diams',
+ "\u266A": 'sung',
+ "\u2713": 'check',
+ "\u2717": 'cross',
+ "\u2720": 'malt',
+ "\u2736": 'sext',
+ "\u2758": 'VerticalSeparator',
+ "\u27C8": 'bsolhsub',
+ "\u27C9": 'suphsol',
+ "\u27F5": 'xlarr',
+ "\u27F6": 'xrarr',
+ "\u27F7": 'xharr',
+ "\u27F8": 'xlArr',
+ "\u27F9": 'xrArr',
+ "\u27FA": 'xhArr',
+ "\u27FC": 'xmap',
+ "\u27FF": 'dzigrarr',
+ "\u2902": 'nvlArr',
+ "\u2903": 'nvrArr',
+ "\u2904": 'nvHarr',
+ "\u2905": 'Map',
+ "\u290C": 'lbarr',
+ "\u290D": 'rbarr',
+ "\u290E": 'lBarr',
+ "\u290F": 'rBarr',
+ "\u2910": 'RBarr',
+ "\u2911": 'DDotrahd',
+ "\u2912": 'UpArrowBar',
+ "\u2913": 'DownArrowBar',
+ "\u2916": 'Rarrtl',
+ "\u2919": 'latail',
+ "\u291A": 'ratail',
+ "\u291B": 'lAtail',
+ "\u291C": 'rAtail',
+ "\u291D": 'larrfs',
+ "\u291E": 'rarrfs',
+ "\u291F": 'larrbfs',
+ "\u2920": 'rarrbfs',
+ "\u2923": 'nwarhk',
+ "\u2924": 'nearhk',
+ "\u2925": 'searhk',
+ "\u2926": 'swarhk',
+ "\u2927": 'nwnear',
+ "\u2928": 'toea',
+ "\u2929": 'tosa',
+ "\u292A": 'swnwar',
+ "\u2933": 'rarrc',
+ "\u2933\u0338": 'nrarrc',
+ "\u2935": 'cudarrr',
+ "\u2936": 'ldca',
+ "\u2937": 'rdca',
+ "\u2938": 'cudarrl',
+ "\u2939": 'larrpl',
+ "\u293C": 'curarrm',
+ "\u293D": 'cularrp',
+ "\u2945": 'rarrpl',
+ "\u2948": 'harrcir',
+ "\u2949": 'Uarrocir',
+ "\u294A": 'lurdshar',
+ "\u294B": 'ldrushar',
+ "\u294E": 'LeftRightVector',
+ "\u294F": 'RightUpDownVector',
+ "\u2950": 'DownLeftRightVector',
+ "\u2951": 'LeftUpDownVector',
+ "\u2952": 'LeftVectorBar',
+ "\u2953": 'RightVectorBar',
+ "\u2954": 'RightUpVectorBar',
+ "\u2955": 'RightDownVectorBar',
+ "\u2956": 'DownLeftVectorBar',
+ "\u2957": 'DownRightVectorBar',
+ "\u2958": 'LeftUpVectorBar',
+ "\u2959": 'LeftDownVectorBar',
+ "\u295A": 'LeftTeeVector',
+ "\u295B": 'RightTeeVector',
+ "\u295C": 'RightUpTeeVector',
+ "\u295D": 'RightDownTeeVector',
+ "\u295E": 'DownLeftTeeVector',
+ "\u295F": 'DownRightTeeVector',
+ "\u2960": 'LeftUpTeeVector',
+ "\u2961": 'LeftDownTeeVector',
+ "\u2962": 'lHar',
+ "\u2963": 'uHar',
+ "\u2964": 'rHar',
+ "\u2965": 'dHar',
+ "\u2966": 'luruhar',
+ "\u2967": 'ldrdhar',
+ "\u2968": 'ruluhar',
+ "\u2969": 'rdldhar',
+ "\u296A": 'lharul',
+ "\u296B": 'llhard',
+ "\u296C": 'rharul',
+ "\u296D": 'lrhard',
+ "\u296E": 'udhar',
+ "\u296F": 'duhar',
+ "\u2970": 'RoundImplies',
+ "\u2971": 'erarr',
+ "\u2972": 'simrarr',
+ "\u2973": 'larrsim',
+ "\u2974": 'rarrsim',
+ "\u2975": 'rarrap',
+ "\u2976": 'ltlarr',
+ "\u2978": 'gtrarr',
+ "\u2979": 'subrarr',
+ "\u297B": 'suplarr',
+ "\u297C": 'lfisht',
+ "\u297D": 'rfisht',
+ "\u297E": 'ufisht',
+ "\u297F": 'dfisht',
+ "\u299A": 'vzigzag',
+ "\u299C": 'vangrt',
+ "\u299D": 'angrtvbd',
+ "\u29A4": 'ange',
+ "\u29A5": 'range',
+ "\u29A6": 'dwangle',
+ "\u29A7": 'uwangle',
+ "\u29A8": 'angmsdaa',
+ "\u29A9": 'angmsdab',
+ "\u29AA": 'angmsdac',
+ "\u29AB": 'angmsdad',
+ "\u29AC": 'angmsdae',
+ "\u29AD": 'angmsdaf',
+ "\u29AE": 'angmsdag',
+ "\u29AF": 'angmsdah',
+ "\u29B0": 'bemptyv',
+ "\u29B1": 'demptyv',
+ "\u29B2": 'cemptyv',
+ "\u29B3": 'raemptyv',
+ "\u29B4": 'laemptyv',
+ "\u29B5": 'ohbar',
+ "\u29B6": 'omid',
+ "\u29B7": 'opar',
+ "\u29B9": 'operp',
+ "\u29BB": 'olcross',
+ "\u29BC": 'odsold',
+ "\u29BE": 'olcir',
+ "\u29BF": 'ofcir',
+ "\u29C0": 'olt',
+ "\u29C1": 'ogt',
+ "\u29C2": 'cirscir',
+ "\u29C3": 'cirE',
+ "\u29C4": 'solb',
+ "\u29C5": 'bsolb',
+ "\u29C9": 'boxbox',
+ "\u29CD": 'trisb',
+ "\u29CE": 'rtriltri',
+ "\u29CF": 'LeftTriangleBar',
+ "\u29CF\u0338": 'NotLeftTriangleBar',
+ "\u29D0": 'RightTriangleBar',
+ "\u29D0\u0338": 'NotRightTriangleBar',
+ "\u29DC": 'iinfin',
+ "\u29DD": 'infintie',
+ "\u29DE": 'nvinfin',
+ "\u29E3": 'eparsl',
+ "\u29E4": 'smeparsl',
+ "\u29E5": 'eqvparsl',
+ "\u29EB": 'lozf',
+ "\u29F4": 'RuleDelayed',
+ "\u29F6": 'dsol',
+ "\u2A00": 'xodot',
+ "\u2A01": 'xoplus',
+ "\u2A02": 'xotime',
+ "\u2A04": 'xuplus',
+ "\u2A06": 'xsqcup',
+ "\u2A0D": 'fpartint',
+ "\u2A10": 'cirfnint',
+ "\u2A11": 'awint',
+ "\u2A12": 'rppolint',
+ "\u2A13": 'scpolint',
+ "\u2A14": 'npolint',
+ "\u2A15": 'pointint',
+ "\u2A16": 'quatint',
+ "\u2A17": 'intlarhk',
+ "\u2A22": 'pluscir',
+ "\u2A23": 'plusacir',
+ "\u2A24": 'simplus',
+ "\u2A25": 'plusdu',
+ "\u2A26": 'plussim',
+ "\u2A27": 'plustwo',
+ "\u2A29": 'mcomma',
+ "\u2A2A": 'minusdu',
+ "\u2A2D": 'loplus',
+ "\u2A2E": 'roplus',
+ "\u2A2F": 'Cross',
+ "\u2A30": 'timesd',
+ "\u2A31": 'timesbar',
+ "\u2A33": 'smashp',
+ "\u2A34": 'lotimes',
+ "\u2A35": 'rotimes',
+ "\u2A36": 'otimesas',
+ "\u2A37": 'Otimes',
+ "\u2A38": 'odiv',
+ "\u2A39": 'triplus',
+ "\u2A3A": 'triminus',
+ "\u2A3B": 'tritime',
+ "\u2A3C": 'iprod',
+ "\u2A3F": 'amalg',
+ "\u2A40": 'capdot',
+ "\u2A42": 'ncup',
+ "\u2A43": 'ncap',
+ "\u2A44": 'capand',
+ "\u2A45": 'cupor',
+ "\u2A46": 'cupcap',
+ "\u2A47": 'capcup',
+ "\u2A48": 'cupbrcap',
+ "\u2A49": 'capbrcup',
+ "\u2A4A": 'cupcup',
+ "\u2A4B": 'capcap',
+ "\u2A4C": 'ccups',
+ "\u2A4D": 'ccaps',
+ "\u2A50": 'ccupssm',
+ "\u2A53": 'And',
+ "\u2A54": 'Or',
+ "\u2A55": 'andand',
+ "\u2A56": 'oror',
+ "\u2A57": 'orslope',
+ "\u2A58": 'andslope',
+ "\u2A5A": 'andv',
+ "\u2A5B": 'orv',
+ "\u2A5C": 'andd',
+ "\u2A5D": 'ord',
+ "\u2A5F": 'wedbar',
+ "\u2A66": 'sdote',
+ "\u2A6A": 'simdot',
+ "\u2A6D": 'congdot',
+ "\u2A6D\u0338": 'ncongdot',
+ "\u2A6E": 'easter',
+ "\u2A6F": 'apacir',
+ "\u2A70": 'apE',
+ "\u2A70\u0338": 'napE',
+ "\u2A71": 'eplus',
+ "\u2A72": 'pluse',
+ "\u2A73": 'Esim',
+ "\u2A77": 'eDDot',
+ "\u2A78": 'equivDD',
+ "\u2A79": 'ltcir',
+ "\u2A7A": 'gtcir',
+ "\u2A7B": 'ltquest',
+ "\u2A7C": 'gtquest',
+ "\u2A7D": 'les',
+ "\u2A7D\u0338": 'nles',
+ "\u2A7E": 'ges',
+ "\u2A7E\u0338": 'nges',
+ "\u2A7F": 'lesdot',
+ "\u2A80": 'gesdot',
+ "\u2A81": 'lesdoto',
+ "\u2A82": 'gesdoto',
+ "\u2A83": 'lesdotor',
+ "\u2A84": 'gesdotol',
+ "\u2A85": 'lap',
+ "\u2A86": 'gap',
+ "\u2A87": 'lne',
+ "\u2A88": 'gne',
+ "\u2A89": 'lnap',
+ "\u2A8A": 'gnap',
+ "\u2A8B": 'lEg',
+ "\u2A8C": 'gEl',
+ "\u2A8D": 'lsime',
+ "\u2A8E": 'gsime',
+ "\u2A8F": 'lsimg',
+ "\u2A90": 'gsiml',
+ "\u2A91": 'lgE',
+ "\u2A92": 'glE',
+ "\u2A93": 'lesges',
+ "\u2A94": 'gesles',
+ "\u2A95": 'els',
+ "\u2A96": 'egs',
+ "\u2A97": 'elsdot',
+ "\u2A98": 'egsdot',
+ "\u2A99": 'el',
+ "\u2A9A": 'eg',
+ "\u2A9D": 'siml',
+ "\u2A9E": 'simg',
+ "\u2A9F": 'simlE',
+ "\u2AA0": 'simgE',
+ "\u2AA1": 'LessLess',
+ "\u2AA1\u0338": 'NotNestedLessLess',
+ "\u2AA2": 'GreaterGreater',
+ "\u2AA2\u0338": 'NotNestedGreaterGreater',
+ "\u2AA4": 'glj',
+ "\u2AA5": 'gla',
+ "\u2AA6": 'ltcc',
+ "\u2AA7": 'gtcc',
+ "\u2AA8": 'lescc',
+ "\u2AA9": 'gescc',
+ "\u2AAA": 'smt',
+ "\u2AAB": 'lat',
+ "\u2AAC": 'smte',
+ "\u2AAC\uFE00": 'smtes',
+ "\u2AAD": 'late',
+ "\u2AAD\uFE00": 'lates',
+ "\u2AAE": 'bumpE',
+ "\u2AAF": 'pre',
+ "\u2AAF\u0338": 'npre',
+ "\u2AB0": 'sce',
+ "\u2AB0\u0338": 'nsce',
+ "\u2AB3": 'prE',
+ "\u2AB4": 'scE',
+ "\u2AB5": 'prnE',
+ "\u2AB6": 'scnE',
+ "\u2AB7": 'prap',
+ "\u2AB8": 'scap',
+ "\u2AB9": 'prnap',
+ "\u2ABA": 'scnap',
+ "\u2ABB": 'Pr',
+ "\u2ABC": 'Sc',
+ "\u2ABD": 'subdot',
+ "\u2ABE": 'supdot',
+ "\u2ABF": 'subplus',
+ "\u2AC0": 'supplus',
+ "\u2AC1": 'submult',
+ "\u2AC2": 'supmult',
+ "\u2AC3": 'subedot',
+ "\u2AC4": 'supedot',
+ "\u2AC5": 'subE',
+ "\u2AC5\u0338": 'nsubE',
+ "\u2AC6": 'supE',
+ "\u2AC6\u0338": 'nsupE',
+ "\u2AC7": 'subsim',
+ "\u2AC8": 'supsim',
+ "\u2ACB\uFE00": 'vsubnE',
+ "\u2ACB": 'subnE',
+ "\u2ACC\uFE00": 'vsupnE',
+ "\u2ACC": 'supnE',
+ "\u2ACF": 'csub',
+ "\u2AD0": 'csup',
+ "\u2AD1": 'csube',
+ "\u2AD2": 'csupe',
+ "\u2AD3": 'subsup',
+ "\u2AD4": 'supsub',
+ "\u2AD5": 'subsub',
+ "\u2AD6": 'supsup',
+ "\u2AD7": 'suphsub',
+ "\u2AD8": 'supdsub',
+ "\u2AD9": 'forkv',
+ "\u2ADA": 'topfork',
+ "\u2ADB": 'mlcp',
+ "\u2AE4": 'Dashv',
+ "\u2AE6": 'Vdashl',
+ "\u2AE7": 'Barv',
+ "\u2AE8": 'vBar',
+ "\u2AE9": 'vBarv',
+ "\u2AEB": 'Vbar',
+ "\u2AEC": 'Not',
+ "\u2AED": 'bNot',
+ "\u2AEE": 'rnmid',
+ "\u2AEF": 'cirmid',
+ "\u2AF0": 'midcir',
+ "\u2AF1": 'topcir',
+ "\u2AF2": 'nhpar',
+ "\u2AF3": 'parsim',
+ "\u2AFD": 'parsl',
+ "\u2AFD\u20E5": 'nparsl',
+ "\u266D": 'flat',
+ "\u266E": 'natur',
+ "\u266F": 'sharp',
+ '\xA4': 'curren',
+ '\xA2': 'cent',
+ '$': 'dollar',
+ '\xA3': 'pound',
+ '\xA5': 'yen',
+ "\u20AC": 'euro',
+ '\xB9': 'sup1',
+ '\xBD': 'half',
+ "\u2153": 'frac13',
+ '\xBC': 'frac14',
+ "\u2155": 'frac15',
+ "\u2159": 'frac16',
+ "\u215B": 'frac18',
+ '\xB2': 'sup2',
+ "\u2154": 'frac23',
+ "\u2156": 'frac25',
+ '\xB3': 'sup3',
+ '\xBE': 'frac34',
+ "\u2157": 'frac35',
+ "\u215C": 'frac38',
+ "\u2158": 'frac45',
+ "\u215A": 'frac56',
+ "\u215D": 'frac58',
+ "\u215E": 'frac78',
+ "\uD835\uDCB6": 'ascr',
+ "\uD835\uDD52": 'aopf',
+ "\uD835\uDD1E": 'afr',
+ "\uD835\uDD38": 'Aopf',
+ "\uD835\uDD04": 'Afr',
+ "\uD835\uDC9C": 'Ascr',
+ '\xAA': 'ordf',
+ '\xE1': 'aacute',
+ '\xC1': 'Aacute',
+ '\xE0': 'agrave',
+ '\xC0': 'Agrave',
+ "\u0103": 'abreve',
+ "\u0102": 'Abreve',
+ '\xE2': 'acirc',
+ '\xC2': 'Acirc',
+ '\xE5': 'aring',
+ '\xC5': 'angst',
+ '\xE4': 'auml',
+ '\xC4': 'Auml',
+ '\xE3': 'atilde',
+ '\xC3': 'Atilde',
+ "\u0105": 'aogon',
+ "\u0104": 'Aogon',
+ "\u0101": 'amacr',
+ "\u0100": 'Amacr',
+ '\xE6': 'aelig',
+ '\xC6': 'AElig',
+ "\uD835\uDCB7": 'bscr',
+ "\uD835\uDD53": 'bopf',
+ "\uD835\uDD1F": 'bfr',
+ "\uD835\uDD39": 'Bopf',
+ "\u212C": 'Bscr',
+ "\uD835\uDD05": 'Bfr',
+ "\uD835\uDD20": 'cfr',
+ "\uD835\uDCB8": 'cscr',
+ "\uD835\uDD54": 'copf',
+ "\u212D": 'Cfr',
+ "\uD835\uDC9E": 'Cscr',
+ "\u2102": 'Copf',
+ "\u0107": 'cacute',
+ "\u0106": 'Cacute',
+ "\u0109": 'ccirc',
+ "\u0108": 'Ccirc',
+ "\u010D": 'ccaron',
+ "\u010C": 'Ccaron',
+ "\u010B": 'cdot',
+ "\u010A": 'Cdot',
+ '\xE7': 'ccedil',
+ '\xC7': 'Ccedil',
+ "\u2105": 'incare',
+ "\uD835\uDD21": 'dfr',
+ "\u2146": 'dd',
+ "\uD835\uDD55": 'dopf',
+ "\uD835\uDCB9": 'dscr',
+ "\uD835\uDC9F": 'Dscr',
+ "\uD835\uDD07": 'Dfr',
+ "\u2145": 'DD',
+ "\uD835\uDD3B": 'Dopf',
+ "\u010F": 'dcaron',
+ "\u010E": 'Dcaron',
+ "\u0111": 'dstrok',
+ "\u0110": 'Dstrok',
+ '\xF0': 'eth',
+ '\xD0': 'ETH',
+ "\u2147": 'ee',
+ "\u212F": 'escr',
+ "\uD835\uDD22": 'efr',
+ "\uD835\uDD56": 'eopf',
+ "\u2130": 'Escr',
+ "\uD835\uDD08": 'Efr',
+ "\uD835\uDD3C": 'Eopf',
+ '\xE9': 'eacute',
+ '\xC9': 'Eacute',
+ '\xE8': 'egrave',
+ '\xC8': 'Egrave',
+ '\xEA': 'ecirc',
+ '\xCA': 'Ecirc',
+ "\u011B": 'ecaron',
+ "\u011A": 'Ecaron',
+ '\xEB': 'euml',
+ '\xCB': 'Euml',
+ "\u0117": 'edot',
+ "\u0116": 'Edot',
+ "\u0119": 'eogon',
+ "\u0118": 'Eogon',
+ "\u0113": 'emacr',
+ "\u0112": 'Emacr',
+ "\uD835\uDD23": 'ffr',
+ "\uD835\uDD57": 'fopf',
+ "\uD835\uDCBB": 'fscr',
+ "\uD835\uDD09": 'Ffr',
+ "\uD835\uDD3D": 'Fopf',
+ "\u2131": 'Fscr',
+ "\uFB00": 'fflig',
+ "\uFB03": 'ffilig',
+ "\uFB04": 'ffllig',
+ "\uFB01": 'filig',
+ 'fj': 'fjlig',
+ "\uFB02": 'fllig',
+ "\u0192": 'fnof',
+ "\u210A": 'gscr',
+ "\uD835\uDD58": 'gopf',
+ "\uD835\uDD24": 'gfr',
+ "\uD835\uDCA2": 'Gscr',
+ "\uD835\uDD3E": 'Gopf',
+ "\uD835\uDD0A": 'Gfr',
+ "\u01F5": 'gacute',
+ "\u011F": 'gbreve',
+ "\u011E": 'Gbreve',
+ "\u011D": 'gcirc',
+ "\u011C": 'Gcirc',
+ "\u0121": 'gdot',
+ "\u0120": 'Gdot',
+ "\u0122": 'Gcedil',
+ "\uD835\uDD25": 'hfr',
+ "\u210E": 'planckh',
+ "\uD835\uDCBD": 'hscr',
+ "\uD835\uDD59": 'hopf',
+ "\u210B": 'Hscr',
+ "\u210C": 'Hfr',
+ "\u210D": 'Hopf',
+ "\u0125": 'hcirc',
+ "\u0124": 'Hcirc',
+ "\u210F": 'hbar',
+ "\u0127": 'hstrok',
+ "\u0126": 'Hstrok',
+ "\uD835\uDD5A": 'iopf',
+ "\uD835\uDD26": 'ifr',
+ "\uD835\uDCBE": 'iscr',
+ "\u2148": 'ii',
+ "\uD835\uDD40": 'Iopf',
+ "\u2110": 'Iscr',
+ "\u2111": 'Im',
+ '\xED': 'iacute',
+ '\xCD': 'Iacute',
+ '\xEC': 'igrave',
+ '\xCC': 'Igrave',
+ '\xEE': 'icirc',
+ '\xCE': 'Icirc',
+ '\xEF': 'iuml',
+ '\xCF': 'Iuml',
+ "\u0129": 'itilde',
+ "\u0128": 'Itilde',
+ "\u0130": 'Idot',
+ "\u012F": 'iogon',
+ "\u012E": 'Iogon',
+ "\u012B": 'imacr',
+ "\u012A": 'Imacr',
+ "\u0133": 'ijlig',
+ "\u0132": 'IJlig',
+ "\u0131": 'imath',
+ "\uD835\uDCBF": 'jscr',
+ "\uD835\uDD5B": 'jopf',
+ "\uD835\uDD27": 'jfr',
+ "\uD835\uDCA5": 'Jscr',
+ "\uD835\uDD0D": 'Jfr',
+ "\uD835\uDD41": 'Jopf',
+ "\u0135": 'jcirc',
+ "\u0134": 'Jcirc',
+ "\u0237": 'jmath',
+ "\uD835\uDD5C": 'kopf',
+ "\uD835\uDCC0": 'kscr',
+ "\uD835\uDD28": 'kfr',
+ "\uD835\uDCA6": 'Kscr',
+ "\uD835\uDD42": 'Kopf',
+ "\uD835\uDD0E": 'Kfr',
+ "\u0137": 'kcedil',
+ "\u0136": 'Kcedil',
+ "\uD835\uDD29": 'lfr',
+ "\uD835\uDCC1": 'lscr',
+ "\u2113": 'ell',
+ "\uD835\uDD5D": 'lopf',
+ "\u2112": 'Lscr',
+ "\uD835\uDD0F": 'Lfr',
+ "\uD835\uDD43": 'Lopf',
+ "\u013A": 'lacute',
+ "\u0139": 'Lacute',
+ "\u013E": 'lcaron',
+ "\u013D": 'Lcaron',
+ "\u013C": 'lcedil',
+ "\u013B": 'Lcedil',
+ "\u0142": 'lstrok',
+ "\u0141": 'Lstrok',
+ "\u0140": 'lmidot',
+ "\u013F": 'Lmidot',
+ "\uD835\uDD2A": 'mfr',
+ "\uD835\uDD5E": 'mopf',
+ "\uD835\uDCC2": 'mscr',
+ "\uD835\uDD10": 'Mfr',
+ "\uD835\uDD44": 'Mopf',
+ "\u2133": 'Mscr',
+ "\uD835\uDD2B": 'nfr',
+ "\uD835\uDD5F": 'nopf',
+ "\uD835\uDCC3": 'nscr',
+ "\u2115": 'Nopf',
+ "\uD835\uDCA9": 'Nscr',
+ "\uD835\uDD11": 'Nfr',
+ "\u0144": 'nacute',
+ "\u0143": 'Nacute',
+ "\u0148": 'ncaron',
+ "\u0147": 'Ncaron',
+ '\xF1': 'ntilde',
+ '\xD1': 'Ntilde',
+ "\u0146": 'ncedil',
+ "\u0145": 'Ncedil',
+ "\u2116": 'numero',
+ "\u014B": 'eng',
+ "\u014A": 'ENG',
+ "\uD835\uDD60": 'oopf',
+ "\uD835\uDD2C": 'ofr',
+ "\u2134": 'oscr',
+ "\uD835\uDCAA": 'Oscr',
+ "\uD835\uDD12": 'Ofr',
+ "\uD835\uDD46": 'Oopf',
+ '\xBA': 'ordm',
+ '\xF3': 'oacute',
+ '\xD3': 'Oacute',
+ '\xF2': 'ograve',
+ '\xD2': 'Ograve',
+ '\xF4': 'ocirc',
+ '\xD4': 'Ocirc',
+ '\xF6': 'ouml',
+ '\xD6': 'Ouml',
+ "\u0151": 'odblac',
+ "\u0150": 'Odblac',
+ '\xF5': 'otilde',
+ '\xD5': 'Otilde',
+ '\xF8': 'oslash',
+ '\xD8': 'Oslash',
+ "\u014D": 'omacr',
+ "\u014C": 'Omacr',
+ "\u0153": 'oelig',
+ "\u0152": 'OElig',
+ "\uD835\uDD2D": 'pfr',
+ "\uD835\uDCC5": 'pscr',
+ "\uD835\uDD61": 'popf',
+ "\u2119": 'Popf',
+ "\uD835\uDD13": 'Pfr',
+ "\uD835\uDCAB": 'Pscr',
+ "\uD835\uDD62": 'qopf',
+ "\uD835\uDD2E": 'qfr',
+ "\uD835\uDCC6": 'qscr',
+ "\uD835\uDCAC": 'Qscr',
+ "\uD835\uDD14": 'Qfr',
+ "\u211A": 'Qopf',
+ "\u0138": 'kgreen',
+ "\uD835\uDD2F": 'rfr',
+ "\uD835\uDD63": 'ropf',
+ "\uD835\uDCC7": 'rscr',
+ "\u211B": 'Rscr',
+ "\u211C": 'Re',
+ "\u211D": 'Ropf',
+ "\u0155": 'racute',
+ "\u0154": 'Racute',
+ "\u0159": 'rcaron',
+ "\u0158": 'Rcaron',
+ "\u0157": 'rcedil',
+ "\u0156": 'Rcedil',
+ "\uD835\uDD64": 'sopf',
+ "\uD835\uDCC8": 'sscr',
+ "\uD835\uDD30": 'sfr',
+ "\uD835\uDD4A": 'Sopf',
+ "\uD835\uDD16": 'Sfr',
+ "\uD835\uDCAE": 'Sscr',
+ "\u24C8": 'oS',
+ "\u015B": 'sacute',
+ "\u015A": 'Sacute',
+ "\u015D": 'scirc',
+ "\u015C": 'Scirc',
+ "\u0161": 'scaron',
+ "\u0160": 'Scaron',
+ "\u015F": 'scedil',
+ "\u015E": 'Scedil',
+ '\xDF': 'szlig',
+ "\uD835\uDD31": 'tfr',
+ "\uD835\uDCC9": 'tscr',
+ "\uD835\uDD65": 'topf',
+ "\uD835\uDCAF": 'Tscr',
+ "\uD835\uDD17": 'Tfr',
+ "\uD835\uDD4B": 'Topf',
+ "\u0165": 'tcaron',
+ "\u0164": 'Tcaron',
+ "\u0163": 'tcedil',
+ "\u0162": 'Tcedil',
+ "\u2122": 'trade',
+ "\u0167": 'tstrok',
+ "\u0166": 'Tstrok',
+ "\uD835\uDCCA": 'uscr',
+ "\uD835\uDD66": 'uopf',
+ "\uD835\uDD32": 'ufr',
+ "\uD835\uDD4C": 'Uopf',
+ "\uD835\uDD18": 'Ufr',
+ "\uD835\uDCB0": 'Uscr',
+ '\xFA': 'uacute',
+ '\xDA': 'Uacute',
+ '\xF9': 'ugrave',
+ '\xD9': 'Ugrave',
+ "\u016D": 'ubreve',
+ "\u016C": 'Ubreve',
+ '\xFB': 'ucirc',
+ '\xDB': 'Ucirc',
+ "\u016F": 'uring',
+ "\u016E": 'Uring',
+ '\xFC': 'uuml',
+ '\xDC': 'Uuml',
+ "\u0171": 'udblac',
+ "\u0170": 'Udblac',
+ "\u0169": 'utilde',
+ "\u0168": 'Utilde',
+ "\u0173": 'uogon',
+ "\u0172": 'Uogon',
+ "\u016B": 'umacr',
+ "\u016A": 'Umacr',
+ "\uD835\uDD33": 'vfr',
+ "\uD835\uDD67": 'vopf',
+ "\uD835\uDCCB": 'vscr',
+ "\uD835\uDD19": 'Vfr',
+ "\uD835\uDD4D": 'Vopf',
+ "\uD835\uDCB1": 'Vscr',
+ "\uD835\uDD68": 'wopf',
+ "\uD835\uDCCC": 'wscr',
+ "\uD835\uDD34": 'wfr',
+ "\uD835\uDCB2": 'Wscr',
+ "\uD835\uDD4E": 'Wopf',
+ "\uD835\uDD1A": 'Wfr',
+ "\u0175": 'wcirc',
+ "\u0174": 'Wcirc',
+ "\uD835\uDD35": 'xfr',
+ "\uD835\uDCCD": 'xscr',
+ "\uD835\uDD69": 'xopf',
+ "\uD835\uDD4F": 'Xopf',
+ "\uD835\uDD1B": 'Xfr',
+ "\uD835\uDCB3": 'Xscr',
+ "\uD835\uDD36": 'yfr',
+ "\uD835\uDCCE": 'yscr',
+ "\uD835\uDD6A": 'yopf',
+ "\uD835\uDCB4": 'Yscr',
+ "\uD835\uDD1C": 'Yfr',
+ "\uD835\uDD50": 'Yopf',
+ '\xFD': 'yacute',
+ '\xDD': 'Yacute',
+ "\u0177": 'ycirc',
+ "\u0176": 'Ycirc',
+ '\xFF': 'yuml',
+ "\u0178": 'Yuml',
+ "\uD835\uDCCF": 'zscr',
+ "\uD835\uDD37": 'zfr',
+ "\uD835\uDD6B": 'zopf',
+ "\u2128": 'Zfr',
+ "\u2124": 'Zopf',
+ "\uD835\uDCB5": 'Zscr',
+ "\u017A": 'zacute',
+ "\u0179": 'Zacute',
+ "\u017E": 'zcaron',
+ "\u017D": 'Zcaron',
+ "\u017C": 'zdot',
+ "\u017B": 'Zdot',
+ "\u01B5": 'imped',
+ '\xFE': 'thorn',
+ '\xDE': 'THORN',
+ "\u0149": 'napos',
+ "\u03B1": 'alpha',
+ "\u0391": 'Alpha',
+ "\u03B2": 'beta',
+ "\u0392": 'Beta',
+ "\u03B3": 'gamma',
+ "\u0393": 'Gamma',
+ "\u03B4": 'delta',
+ "\u0394": 'Delta',
+ "\u03B5": 'epsi',
+ "\u03F5": 'epsiv',
+ "\u0395": 'Epsilon',
+ "\u03DD": 'gammad',
+ "\u03DC": 'Gammad',
+ "\u03B6": 'zeta',
+ "\u0396": 'Zeta',
+ "\u03B7": 'eta',
+ "\u0397": 'Eta',
+ "\u03B8": 'theta',
+ "\u03D1": 'thetav',
+ "\u0398": 'Theta',
+ "\u03B9": 'iota',
+ "\u0399": 'Iota',
+ "\u03BA": 'kappa',
+ "\u03F0": 'kappav',
+ "\u039A": 'Kappa',
+ "\u03BB": 'lambda',
+ "\u039B": 'Lambda',
+ "\u03BC": 'mu',
+ '\xB5': 'micro',
+ "\u039C": 'Mu',
+ "\u03BD": 'nu',
+ "\u039D": 'Nu',
+ "\u03BE": 'xi',
+ "\u039E": 'Xi',
+ "\u03BF": 'omicron',
+ "\u039F": 'Omicron',
+ "\u03C0": 'pi',
+ "\u03D6": 'piv',
+ "\u03A0": 'Pi',
+ "\u03C1": 'rho',
+ "\u03F1": 'rhov',
+ "\u03A1": 'Rho',
+ "\u03C3": 'sigma',
+ "\u03A3": 'Sigma',
+ "\u03C2": 'sigmaf',
+ "\u03C4": 'tau',
+ "\u03A4": 'Tau',
+ "\u03C5": 'upsi',
+ "\u03A5": 'Upsilon',
+ "\u03D2": 'Upsi',
+ "\u03C6": 'phi',
+ "\u03D5": 'phiv',
+ "\u03A6": 'Phi',
+ "\u03C7": 'chi',
+ "\u03A7": 'Chi',
+ "\u03C8": 'psi',
+ "\u03A8": 'Psi',
+ "\u03C9": 'omega',
+ "\u03A9": 'ohm',
+ "\u0430": 'acy',
+ "\u0410": 'Acy',
+ "\u0431": 'bcy',
+ "\u0411": 'Bcy',
+ "\u0432": 'vcy',
+ "\u0412": 'Vcy',
+ "\u0433": 'gcy',
+ "\u0413": 'Gcy',
+ "\u0453": 'gjcy',
+ "\u0403": 'GJcy',
+ "\u0434": 'dcy',
+ "\u0414": 'Dcy',
+ "\u0452": 'djcy',
+ "\u0402": 'DJcy',
+ "\u0435": 'iecy',
+ "\u0415": 'IEcy',
+ "\u0451": 'iocy',
+ "\u0401": 'IOcy',
+ "\u0454": 'jukcy',
+ "\u0404": 'Jukcy',
+ "\u0436": 'zhcy',
+ "\u0416": 'ZHcy',
+ "\u0437": 'zcy',
+ "\u0417": 'Zcy',
+ "\u0455": 'dscy',
+ "\u0405": 'DScy',
+ "\u0438": 'icy',
+ "\u0418": 'Icy',
+ "\u0456": 'iukcy',
+ "\u0406": 'Iukcy',
+ "\u0457": 'yicy',
+ "\u0407": 'YIcy',
+ "\u0439": 'jcy',
+ "\u0419": 'Jcy',
+ "\u0458": 'jsercy',
+ "\u0408": 'Jsercy',
+ "\u043A": 'kcy',
+ "\u041A": 'Kcy',
+ "\u045C": 'kjcy',
+ "\u040C": 'KJcy',
+ "\u043B": 'lcy',
+ "\u041B": 'Lcy',
+ "\u0459": 'ljcy',
+ "\u0409": 'LJcy',
+ "\u043C": 'mcy',
+ "\u041C": 'Mcy',
+ "\u043D": 'ncy',
+ "\u041D": 'Ncy',
+ "\u045A": 'njcy',
+ "\u040A": 'NJcy',
+ "\u043E": 'ocy',
+ "\u041E": 'Ocy',
+ "\u043F": 'pcy',
+ "\u041F": 'Pcy',
+ "\u0440": 'rcy',
+ "\u0420": 'Rcy',
+ "\u0441": 'scy',
+ "\u0421": 'Scy',
+ "\u0442": 'tcy',
+ "\u0422": 'Tcy',
+ "\u045B": 'tshcy',
+ "\u040B": 'TSHcy',
+ "\u0443": 'ucy',
+ "\u0423": 'Ucy',
+ "\u045E": 'ubrcy',
+ "\u040E": 'Ubrcy',
+ "\u0444": 'fcy',
+ "\u0424": 'Fcy',
+ "\u0445": 'khcy',
+ "\u0425": 'KHcy',
+ "\u0446": 'tscy',
+ "\u0426": 'TScy',
+ "\u0447": 'chcy',
+ "\u0427": 'CHcy',
+ "\u045F": 'dzcy',
+ "\u040F": 'DZcy',
+ "\u0448": 'shcy',
+ "\u0428": 'SHcy',
+ "\u0449": 'shchcy',
+ "\u0429": 'SHCHcy',
+ "\u044A": 'hardcy',
+ "\u042A": 'HARDcy',
+ "\u044B": 'ycy',
+ "\u042B": 'Ycy',
+ "\u044C": 'softcy',
+ "\u042C": 'SOFTcy',
+ "\u044D": 'ecy',
+ "\u042D": 'Ecy',
+ "\u044E": 'yucy',
+ "\u042E": 'YUcy',
+ "\u044F": 'yacy',
+ "\u042F": 'YAcy',
+ "\u2135": 'aleph',
+ "\u2136": 'beth',
+ "\u2137": 'gimel',
+ "\u2138": 'daleth'
+ };
+ var regexEscape = /["&'<>`]/g;
+ var escapeMap = {
+ '"': '"',
+ '&': '&',
+ '\'': ''',
+ '<': '<',
+ // See https://mathiasbynens.be/notes/ambiguous-ampersands: in HTML, the
+ // following is not strictly necessary unless it’s part of a tag or an
+ // unquoted attribute value. We’re only escaping it to support those
+ // situations, and for XML support.
+ '>': '>',
+ // In Internet Explorer ≤ 8, the backtick character can be used
+ // to break out of (un)quoted attribute values or HTML comments.
+ // See http://html5sec.org/#102, http://html5sec.org/#108, and
+ // http://html5sec.org/#133.
+ '`': '`'
+ };
+ var regexInvalidEntity = /(?:[xX][^a-fA-F0-9]|[^0-9xX])/;
+ var regexInvalidRawCodePoint = /[\0-\x08\x0B\x0E-\x1F\x7F-\x9F\uFDD0-\uFDEF\uFFFE\uFFFF]|[\uD83F\uD87F\uD8BF\uD8FF\uD93F\uD97F\uD9BF\uD9FF\uDA3F\uDA7F\uDABF\uDAFF\uDB3F\uDB7F\uDBBF\uDBFF][\uDFFE\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
+ var regexDecode = /&(CounterClockwiseContourIntegral|DoubleLongLeftRightArrow|ClockwiseContourIntegral|NotNestedGreaterGreater|NotSquareSupersetEqual|DiacriticalDoubleAcute|NotRightTriangleEqual|NotSucceedsSlantEqual|NotPrecedesSlantEqual|CloseCurlyDoubleQuote|NegativeVeryThinSpace|DoubleContourIntegral|FilledVerySmallSquare|CapitalDifferentialD|OpenCurlyDoubleQuote|EmptyVerySmallSquare|NestedGreaterGreater|DoubleLongRightArrow|NotLeftTriangleEqual|NotGreaterSlantEqual|ReverseUpEquilibrium|DoubleLeftRightArrow|NotSquareSubsetEqual|NotDoubleVerticalBar|RightArrowLeftArrow|NotGreaterFullEqual|NotRightTriangleBar|SquareSupersetEqual|DownLeftRightVector|DoubleLongLeftArrow|leftrightsquigarrow|LeftArrowRightArrow|NegativeMediumSpace|blacktriangleright|RightDownVectorBar|PrecedesSlantEqual|RightDoubleBracket|SucceedsSlantEqual|NotLeftTriangleBar|RightTriangleEqual|SquareIntersection|RightDownTeeVector|ReverseEquilibrium|NegativeThickSpace|longleftrightarrow|Longleftrightarrow|LongLeftRightArrow|DownRightTeeVector|DownRightVectorBar|GreaterSlantEqual|SquareSubsetEqual|LeftDownVectorBar|LeftDoubleBracket|VerticalSeparator|rightleftharpoons|NotGreaterGreater|NotSquareSuperset|blacktriangleleft|blacktriangledown|NegativeThinSpace|LeftDownTeeVector|NotLessSlantEqual|leftrightharpoons|DoubleUpDownArrow|DoubleVerticalBar|LeftTriangleEqual|FilledSmallSquare|twoheadrightarrow|NotNestedLessLess|DownLeftTeeVector|DownLeftVectorBar|RightAngleBracket|NotTildeFullEqual|NotReverseElement|RightUpDownVector|DiacriticalTilde|NotSucceedsTilde|circlearrowright|NotPrecedesEqual|rightharpoondown|DoubleRightArrow|NotSucceedsEqual|NonBreakingSpace|NotRightTriangle|LessEqualGreater|RightUpTeeVector|LeftAngleBracket|GreaterFullEqual|DownArrowUpArrow|RightUpVectorBar|twoheadleftarrow|GreaterEqualLess|downharpoonright|RightTriangleBar|ntrianglerighteq|NotSupersetEqual|LeftUpDownVector|DiacriticalAcute|rightrightarrows|vartriangleright|UpArrowDownArrow|DiacriticalGrave|UnderParenthesis|EmptySmallSquare|LeftUpVectorBar|leftrightarrows|DownRightVector|downharpoonleft|trianglerighteq|ShortRightArrow|OverParenthesis|DoubleLeftArrow|DoubleDownArrow|NotSquareSubset|bigtriangledown|ntrianglelefteq|UpperRightArrow|curvearrowright|vartriangleleft|NotLeftTriangle|nleftrightarrow|LowerRightArrow|NotHumpDownHump|NotGreaterTilde|rightthreetimes|LeftUpTeeVector|NotGreaterEqual|straightepsilon|LeftTriangleBar|rightsquigarrow|ContourIntegral|rightleftarrows|CloseCurlyQuote|RightDownVector|LeftRightVector|nLeftrightarrow|leftharpoondown|circlearrowleft|SquareSuperset|OpenCurlyQuote|hookrightarrow|HorizontalLine|DiacriticalDot|NotLessGreater|ntriangleright|DoubleRightTee|InvisibleComma|InvisibleTimes|LowerLeftArrow|DownLeftVector|NotSubsetEqual|curvearrowleft|trianglelefteq|NotVerticalBar|TildeFullEqual|downdownarrows|NotGreaterLess|RightTeeVector|ZeroWidthSpace|looparrowright|LongRightArrow|doublebarwedge|ShortLeftArrow|ShortDownArrow|RightVectorBar|GreaterGreater|ReverseElement|rightharpoonup|LessSlantEqual|leftthreetimes|upharpoonright|rightarrowtail|LeftDownVector|Longrightarrow|NestedLessLess|UpperLeftArrow|nshortparallel|leftleftarrows|leftrightarrow|Leftrightarrow|LeftRightArrow|longrightarrow|upharpoonleft|RightArrowBar|ApplyFunction|LeftTeeVector|leftarrowtail|NotEqualTilde|varsubsetneqq|varsupsetneqq|RightTeeArrow|SucceedsEqual|SucceedsTilde|LeftVectorBar|SupersetEqual|hookleftarrow|DifferentialD|VerticalTilde|VeryThinSpace|blacktriangle|bigtriangleup|LessFullEqual|divideontimes|leftharpoonup|UpEquilibrium|ntriangleleft|RightTriangle|measuredangle|shortparallel|longleftarrow|Longleftarrow|LongLeftArrow|DoubleLeftTee|Poincareplane|PrecedesEqual|triangleright|DoubleUpArrow|RightUpVector|fallingdotseq|looparrowleft|PrecedesTilde|NotTildeEqual|NotTildeTilde|smallsetminus|Proportional|triangleleft|triangledown|UnderBracket|NotHumpEqual|exponentiale|ExponentialE|NotLessTilde|HilbertSpace|RightCeiling|blacklozenge|varsupsetneq|HumpDownHump|GreaterEqual|VerticalLine|LeftTeeArrow|NotLessEqual|DownTeeArrow|LeftTriangle|varsubsetneq|Intersection|NotCongruent|DownArrowBar|LeftUpVector|LeftArrowBar|risingdotseq|GreaterTilde|RoundImplies|SquareSubset|ShortUpArrow|NotSuperset|quaternions|precnapprox|backepsilon|preccurlyeq|OverBracket|blacksquare|MediumSpace|VerticalBar|circledcirc|circleddash|CircleMinus|CircleTimes|LessGreater|curlyeqprec|curlyeqsucc|diamondsuit|UpDownArrow|Updownarrow|RuleDelayed|Rrightarrow|updownarrow|RightVector|nRightarrow|nrightarrow|eqslantless|LeftCeiling|Equilibrium|SmallCircle|expectation|NotSucceeds|thickapprox|GreaterLess|SquareUnion|NotPrecedes|NotLessLess|straightphi|succnapprox|succcurlyeq|SubsetEqual|sqsupseteq|Proportion|Laplacetrf|ImaginaryI|supsetneqq|NotGreater|gtreqqless|NotElement|ThickSpace|TildeEqual|TildeTilde|Fouriertrf|rmoustache|EqualTilde|eqslantgtr|UnderBrace|LeftVector|UpArrowBar|nLeftarrow|nsubseteqq|subsetneqq|nsupseteqq|nleftarrow|succapprox|lessapprox|UpTeeArrow|upuparrows|curlywedge|lesseqqgtr|varepsilon|varnothing|RightFloor|complement|CirclePlus|sqsubseteq|Lleftarrow|circledast|RightArrow|Rightarrow|rightarrow|lmoustache|Bernoullis|precapprox|mapstoleft|mapstodown|longmapsto|dotsquare|downarrow|DoubleDot|nsubseteq|supsetneq|leftarrow|nsupseteq|subsetneq|ThinSpace|ngeqslant|subseteqq|HumpEqual|NotSubset|triangleq|NotCupCap|lesseqgtr|heartsuit|TripleDot|Leftarrow|Coproduct|Congruent|varpropto|complexes|gvertneqq|LeftArrow|LessTilde|supseteqq|MinusPlus|CircleDot|nleqslant|NotExists|gtreqless|nparallel|UnionPlus|LeftFloor|checkmark|CenterDot|centerdot|Mellintrf|gtrapprox|bigotimes|OverBrace|spadesuit|therefore|pitchfork|rationals|PlusMinus|Backslash|Therefore|DownBreve|backsimeq|backprime|DownArrow|nshortmid|Downarrow|lvertneqq|eqvparsl|imagline|imagpart|infintie|integers|Integral|intercal|LessLess|Uarrocir|intlarhk|sqsupset|angmsdaf|sqsubset|llcorner|vartheta|cupbrcap|lnapprox|Superset|SuchThat|succnsim|succneqq|angmsdag|biguplus|curlyvee|trpezium|Succeeds|NotTilde|bigwedge|angmsdah|angrtvbd|triminus|cwconint|fpartint|lrcorner|smeparsl|subseteq|urcorner|lurdshar|laemptyv|DDotrahd|approxeq|ldrushar|awconint|mapstoup|backcong|shortmid|triangle|geqslant|gesdotol|timesbar|circledR|circledS|setminus|multimap|naturals|scpolint|ncongdot|RightTee|boxminus|gnapprox|boxtimes|andslope|thicksim|angmsdaa|varsigma|cirfnint|rtriltri|angmsdab|rppolint|angmsdac|barwedge|drbkarow|clubsuit|thetasym|bsolhsub|capbrcup|dzigrarr|doteqdot|DotEqual|dotminus|UnderBar|NotEqual|realpart|otimesas|ulcorner|hksearow|hkswarow|parallel|PartialD|elinters|emptyset|plusacir|bbrktbrk|angmsdad|pointint|bigoplus|angmsdae|Precedes|bigsqcup|varkappa|notindot|supseteq|precneqq|precnsim|profalar|profline|profsurf|leqslant|lesdotor|raemptyv|subplus|notnivb|notnivc|subrarr|zigrarr|vzigzag|submult|subedot|Element|between|cirscir|larrbfs|larrsim|lotimes|lbrksld|lbrkslu|lozenge|ldrdhar|dbkarow|bigcirc|epsilon|simrarr|simplus|ltquest|Epsilon|luruhar|gtquest|maltese|npolint|eqcolon|npreceq|bigodot|ddagger|gtrless|bnequiv|harrcir|ddotseq|equivDD|backsim|demptyv|nsqsube|nsqsupe|Upsilon|nsubset|upsilon|minusdu|nsucceq|swarrow|nsupset|coloneq|searrow|boxplus|napprox|natural|asympeq|alefsym|congdot|nearrow|bigstar|diamond|supplus|tritime|LeftTee|nvinfin|triplus|NewLine|nvltrie|nvrtrie|nwarrow|nexists|Diamond|ruluhar|Implies|supmult|angzarr|suplarr|suphsub|questeq|because|digamma|Because|olcross|bemptyv|omicron|Omicron|rotimes|NoBreak|intprod|angrtvb|orderof|uwangle|suphsol|lesdoto|orslope|DownTee|realine|cudarrl|rdldhar|OverBar|supedot|lessdot|supdsub|topfork|succsim|rbrkslu|rbrksld|pertenk|cudarrr|isindot|planckh|lessgtr|pluscir|gesdoto|plussim|plustwo|lesssim|cularrp|rarrsim|Cayleys|notinva|notinvb|notinvc|UpArrow|Uparrow|uparrow|NotLess|dwangle|precsim|Product|curarrm|Cconint|dotplus|rarrbfs|ccupssm|Cedilla|cemptyv|notniva|quatint|frac35|frac38|frac45|frac56|frac58|frac78|tridot|xoplus|gacute|gammad|Gammad|lfisht|lfloor|bigcup|sqsupe|gbreve|Gbreve|lharul|sqsube|sqcups|Gcedil|apacir|llhard|lmidot|Lmidot|lmoust|andand|sqcaps|approx|Abreve|spades|circeq|tprime|divide|topcir|Assign|topbot|gesdot|divonx|xuplus|timesd|gesles|atilde|solbar|SOFTcy|loplus|timesb|lowast|lowbar|dlcorn|dlcrop|softcy|dollar|lparlt|thksim|lrhard|Atilde|lsaquo|smashp|bigvee|thinsp|wreath|bkarow|lsquor|lstrok|Lstrok|lthree|ltimes|ltlarr|DotDot|simdot|ltrPar|weierp|xsqcup|angmsd|sigmav|sigmaf|zeetrf|Zcaron|zcaron|mapsto|vsupne|thetav|cirmid|marker|mcomma|Zacute|vsubnE|there4|gtlPar|vsubne|bottom|gtrarr|SHCHcy|shchcy|midast|midcir|middot|minusb|minusd|gtrdot|bowtie|sfrown|mnplus|models|colone|seswar|Colone|mstpos|searhk|gtrsim|nacute|Nacute|boxbox|telrec|hairsp|Tcedil|nbumpe|scnsim|ncaron|Ncaron|ncedil|Ncedil|hamilt|Scedil|nearhk|hardcy|HARDcy|tcedil|Tcaron|commat|nequiv|nesear|tcaron|target|hearts|nexist|varrho|scedil|Scaron|scaron|hellip|Sacute|sacute|hercon|swnwar|compfn|rtimes|rthree|rsquor|rsaquo|zacute|wedgeq|homtht|barvee|barwed|Barwed|rpargt|horbar|conint|swarhk|roplus|nltrie|hslash|hstrok|Hstrok|rmoust|Conint|bprime|hybull|hyphen|iacute|Iacute|supsup|supsub|supsim|varphi|coprod|brvbar|agrave|Supset|supset|igrave|Igrave|notinE|Agrave|iiiint|iinfin|copysr|wedbar|Verbar|vangrt|becaus|incare|verbar|inodot|bullet|drcorn|intcal|drcrop|cularr|vellip|Utilde|bumpeq|cupcap|dstrok|Dstrok|CupCap|cupcup|cupdot|eacute|Eacute|supdot|iquest|easter|ecaron|Ecaron|ecolon|isinsv|utilde|itilde|Itilde|curarr|succeq|Bumpeq|cacute|ulcrop|nparsl|Cacute|nprcue|egrave|Egrave|nrarrc|nrarrw|subsup|subsub|nrtrie|jsercy|nsccue|Jsercy|kappav|kcedil|Kcedil|subsim|ulcorn|nsimeq|egsdot|veebar|kgreen|capand|elsdot|Subset|subset|curren|aacute|lacute|Lacute|emptyv|ntilde|Ntilde|lagran|lambda|Lambda|capcap|Ugrave|langle|subdot|emsp13|numero|emsp14|nvdash|nvDash|nVdash|nVDash|ugrave|ufisht|nvHarr|larrfs|nvlArr|larrhk|larrlp|larrpl|nvrArr|Udblac|nwarhk|larrtl|nwnear|oacute|Oacute|latail|lAtail|sstarf|lbrace|odblac|Odblac|lbrack|udblac|odsold|eparsl|lcaron|Lcaron|ograve|Ograve|lcedil|Lcedil|Aacute|ssmile|ssetmn|squarf|ldquor|capcup|ominus|cylcty|rharul|eqcirc|dagger|rfloor|rfisht|Dagger|daleth|equals|origof|capdot|equest|dcaron|Dcaron|rdquor|oslash|Oslash|otilde|Otilde|otimes|Otimes|urcrop|Ubreve|ubreve|Yacute|Uacute|uacute|Rcedil|rcedil|urcorn|parsim|Rcaron|Vdashl|rcaron|Tstrok|percnt|period|permil|Exists|yacute|rbrack|rbrace|phmmat|ccaron|Ccaron|planck|ccedil|plankv|tstrok|female|plusdo|plusdu|ffilig|plusmn|ffllig|Ccedil|rAtail|dfisht|bernou|ratail|Rarrtl|rarrtl|angsph|rarrpl|rarrlp|rarrhk|xwedge|xotime|forall|ForAll|Vvdash|vsupnE|preceq|bigcap|frac12|frac13|frac14|primes|rarrfs|prnsim|frac15|Square|frac16|square|lesdot|frac18|frac23|propto|prurel|rarrap|rangle|puncsp|frac25|Racute|qprime|racute|lesges|frac34|abreve|AElig|eqsim|utdot|setmn|urtri|Equal|Uring|seArr|uring|searr|dashv|Dashv|mumap|nabla|iogon|Iogon|sdote|sdotb|scsim|napid|napos|equiv|natur|Acirc|dblac|erarr|nbump|iprod|erDot|ucirc|awint|esdot|angrt|ncong|isinE|scnap|Scirc|scirc|ndash|isins|Ubrcy|nearr|neArr|isinv|nedot|ubrcy|acute|Ycirc|iukcy|Iukcy|xutri|nesim|caret|jcirc|Jcirc|caron|twixt|ddarr|sccue|exist|jmath|sbquo|ngeqq|angst|ccaps|lceil|ngsim|UpTee|delta|Delta|rtrif|nharr|nhArr|nhpar|rtrie|jukcy|Jukcy|kappa|rsquo|Kappa|nlarr|nlArr|TSHcy|rrarr|aogon|Aogon|fflig|xrarr|tshcy|ccirc|nleqq|filig|upsih|nless|dharl|nlsim|fjlig|ropar|nltri|dharr|robrk|roarr|fllig|fltns|roang|rnmid|subnE|subne|lAarr|trisb|Ccirc|acirc|ccups|blank|VDash|forkv|Vdash|langd|cedil|blk12|blk14|laquo|strns|diams|notin|vDash|larrb|blk34|block|disin|uplus|vdash|vBarv|aelig|starf|Wedge|check|xrArr|lates|lbarr|lBarr|notni|lbbrk|bcong|frasl|lbrke|frown|vrtri|vprop|vnsup|gamma|Gamma|wedge|xodot|bdquo|srarr|doteq|ldquo|boxdl|boxdL|gcirc|Gcirc|boxDl|boxDL|boxdr|boxdR|boxDr|TRADE|trade|rlhar|boxDR|vnsub|npart|vltri|rlarr|boxhd|boxhD|nprec|gescc|nrarr|nrArr|boxHd|boxHD|boxhu|boxhU|nrtri|boxHu|clubs|boxHU|times|colon|Colon|gimel|xlArr|Tilde|nsime|tilde|nsmid|nspar|THORN|thorn|xlarr|nsube|nsubE|thkap|xhArr|comma|nsucc|boxul|boxuL|nsupe|nsupE|gneqq|gnsim|boxUl|boxUL|grave|boxur|boxuR|boxUr|boxUR|lescc|angle|bepsi|boxvh|varpi|boxvH|numsp|Theta|gsime|gsiml|theta|boxVh|boxVH|boxvl|gtcir|gtdot|boxvL|boxVl|boxVL|crarr|cross|Cross|nvsim|boxvr|nwarr|nwArr|sqsup|dtdot|Uogon|lhard|lharu|dtrif|ocirc|Ocirc|lhblk|duarr|odash|sqsub|Hacek|sqcup|llarr|duhar|oelig|OElig|ofcir|boxvR|uogon|lltri|boxVr|csube|uuarr|ohbar|csupe|ctdot|olarr|olcir|harrw|oline|sqcap|omacr|Omacr|omega|Omega|boxVR|aleph|lneqq|lnsim|loang|loarr|rharu|lobrk|hcirc|operp|oplus|rhard|Hcirc|orarr|Union|order|ecirc|Ecirc|cuepr|szlig|cuesc|breve|reals|eDDot|Breve|hoarr|lopar|utrif|rdquo|Umacr|umacr|efDot|swArr|ultri|alpha|rceil|ovbar|swarr|Wcirc|wcirc|smtes|smile|bsemi|lrarr|aring|parsl|lrhar|bsime|uhblk|lrtri|cupor|Aring|uharr|uharl|slarr|rbrke|bsolb|lsime|rbbrk|RBarr|lsimg|phone|rBarr|rbarr|icirc|lsquo|Icirc|emacr|Emacr|ratio|simne|plusb|simlE|simgE|simeq|pluse|ltcir|ltdot|empty|xharr|xdtri|iexcl|Alpha|ltrie|rarrw|pound|ltrif|xcirc|bumpe|prcue|bumpE|asymp|amacr|cuvee|Sigma|sigma|iiint|udhar|iiota|ijlig|IJlig|supnE|imacr|Imacr|prime|Prime|image|prnap|eogon|Eogon|rarrc|mdash|mDDot|cuwed|imath|supne|imped|Amacr|udarr|prsim|micro|rarrb|cwint|raquo|infin|eplus|range|rangd|Ucirc|radic|minus|amalg|veeeq|rAarr|epsiv|ycirc|quest|sharp|quot|zwnj|Qscr|race|qscr|Qopf|qopf|qint|rang|Rang|Zscr|zscr|Zopf|zopf|rarr|rArr|Rarr|Pscr|pscr|prop|prod|prnE|prec|ZHcy|zhcy|prap|Zeta|zeta|Popf|popf|Zdot|plus|zdot|Yuml|yuml|phiv|YUcy|yucy|Yscr|yscr|perp|Yopf|yopf|part|para|YIcy|Ouml|rcub|yicy|YAcy|rdca|ouml|osol|Oscr|rdsh|yacy|real|oscr|xvee|andd|rect|andv|Xscr|oror|ordm|ordf|xscr|ange|aopf|Aopf|rHar|Xopf|opar|Oopf|xopf|xnis|rhov|oopf|omid|xmap|oint|apid|apos|ogon|ascr|Ascr|odot|odiv|xcup|xcap|ocir|oast|nvlt|nvle|nvgt|nvge|nvap|Wscr|wscr|auml|ntlg|ntgl|nsup|nsub|nsim|Nscr|nscr|nsce|Wopf|ring|npre|wopf|npar|Auml|Barv|bbrk|Nopf|nopf|nmid|nLtv|beta|ropf|Ropf|Beta|beth|nles|rpar|nleq|bnot|bNot|nldr|NJcy|rscr|Rscr|Vscr|vscr|rsqb|njcy|bopf|nisd|Bopf|rtri|Vopf|nGtv|ngtr|vopf|boxh|boxH|boxv|nges|ngeq|boxV|bscr|scap|Bscr|bsim|Vert|vert|bsol|bull|bump|caps|cdot|ncup|scnE|ncap|nbsp|napE|Cdot|cent|sdot|Vbar|nang|vBar|chcy|Mscr|mscr|sect|semi|CHcy|Mopf|mopf|sext|circ|cire|mldr|mlcp|cirE|comp|shcy|SHcy|vArr|varr|cong|copf|Copf|copy|COPY|malt|male|macr|lvnE|cscr|ltri|sime|ltcc|simg|Cscr|siml|csub|Uuml|lsqb|lsim|uuml|csup|Lscr|lscr|utri|smid|lpar|cups|smte|lozf|darr|Lopf|Uscr|solb|lopf|sopf|Sopf|lneq|uscr|spar|dArr|lnap|Darr|dash|Sqrt|LJcy|ljcy|lHar|dHar|Upsi|upsi|diam|lesg|djcy|DJcy|leqq|dopf|Dopf|dscr|Dscr|dscy|ldsh|ldca|squf|DScy|sscr|Sscr|dsol|lcub|late|star|Star|Uopf|Larr|lArr|larr|uopf|dtri|dzcy|sube|subE|Lang|lang|Kscr|kscr|Kopf|kopf|KJcy|kjcy|KHcy|khcy|DZcy|ecir|edot|eDot|Jscr|jscr|succ|Jopf|jopf|Edot|uHar|emsp|ensp|Iuml|iuml|eopf|isin|Iscr|iscr|Eopf|epar|sung|epsi|escr|sup1|sup2|sup3|Iota|iota|supe|supE|Iopf|iopf|IOcy|iocy|Escr|esim|Esim|imof|Uarr|QUOT|uArr|uarr|euml|IEcy|iecy|Idot|Euml|euro|excl|Hscr|hscr|Hopf|hopf|TScy|tscy|Tscr|hbar|tscr|flat|tbrk|fnof|hArr|harr|half|fopf|Fopf|tdot|gvnE|fork|trie|gtcc|fscr|Fscr|gdot|gsim|Gscr|gscr|Gopf|gopf|gneq|Gdot|tosa|gnap|Topf|topf|geqq|toea|GJcy|gjcy|tint|gesl|mid|Sfr|ggg|top|ges|gla|glE|glj|geq|gne|gEl|gel|gnE|Gcy|gcy|gap|Tfr|tfr|Tcy|tcy|Hat|Tau|Ffr|tau|Tab|hfr|Hfr|ffr|Fcy|fcy|icy|Icy|iff|ETH|eth|ifr|Ifr|Eta|eta|int|Int|Sup|sup|ucy|Ucy|Sum|sum|jcy|ENG|ufr|Ufr|eng|Jcy|jfr|els|ell|egs|Efr|efr|Jfr|uml|kcy|Kcy|Ecy|ecy|kfr|Kfr|lap|Sub|sub|lat|lcy|Lcy|leg|Dot|dot|lEg|leq|les|squ|div|die|lfr|Lfr|lgE|Dfr|dfr|Del|deg|Dcy|dcy|lne|lnE|sol|loz|smt|Cup|lrm|cup|lsh|Lsh|sim|shy|map|Map|mcy|Mcy|mfr|Mfr|mho|gfr|Gfr|sfr|cir|Chi|chi|nap|Cfr|vcy|Vcy|cfr|Scy|scy|ncy|Ncy|vee|Vee|Cap|cap|nfr|scE|sce|Nfr|nge|ngE|nGg|vfr|Vfr|ngt|bot|nGt|nis|niv|Rsh|rsh|nle|nlE|bne|Bfr|bfr|nLl|nlt|nLt|Bcy|bcy|not|Not|rlm|wfr|Wfr|npr|nsc|num|ocy|ast|Ocy|ofr|xfr|Xfr|Ofr|ogt|ohm|apE|olt|Rho|ape|rho|Rfr|rfr|ord|REG|ang|reg|orv|And|and|AMP|Rcy|amp|Afr|ycy|Ycy|yen|yfr|Yfr|rcy|par|pcy|Pcy|pfr|Pfr|phi|Phi|afr|Acy|acy|zcy|Zcy|piv|acE|acd|zfr|Zfr|pre|prE|psi|Psi|qfr|Qfr|zwj|Or|ge|Gg|gt|gg|el|oS|lt|Lt|LT|Re|lg|gl|eg|ne|Im|it|le|DD|wp|wr|nu|Nu|dd|lE|Sc|sc|pi|Pi|ee|af|ll|Ll|rx|gE|xi|pm|Xi|ic|pr|Pr|in|ni|mp|mu|ac|Mu|or|ap|Gt|GT|ii);|&(Aacute|Agrave|Atilde|Ccedil|Eacute|Egrave|Iacute|Igrave|Ntilde|Oacute|Ograve|Oslash|Otilde|Uacute|Ugrave|Yacute|aacute|agrave|atilde|brvbar|ccedil|curren|divide|eacute|egrave|frac12|frac14|frac34|iacute|igrave|iquest|middot|ntilde|oacute|ograve|oslash|otilde|plusmn|uacute|ugrave|yacute|AElig|Acirc|Aring|Ecirc|Icirc|Ocirc|THORN|Ucirc|acirc|acute|aelig|aring|cedil|ecirc|icirc|iexcl|laquo|micro|ocirc|pound|raquo|szlig|thorn|times|ucirc|Auml|COPY|Euml|Iuml|Ouml|QUOT|Uuml|auml|cent|copy|euml|iuml|macr|nbsp|ordf|ordm|ouml|para|quot|sect|sup1|sup2|sup3|uuml|yuml|AMP|ETH|REG|amp|deg|eth|not|reg|shy|uml|yen|GT|LT|gt|lt)(?!;)([=a-zA-Z0-9]?)|([0-9]+)(;?)|[xX]([a-fA-F0-9]+)(;?)|&([0-9a-zA-Z]+)/g;
+ var decodeMap = {
+ 'aacute': '\xE1',
+ 'Aacute': '\xC1',
+ 'abreve': "\u0103",
+ 'Abreve': "\u0102",
+ 'ac': "\u223E",
+ 'acd': "\u223F",
+ 'acE': "\u223E\u0333",
+ 'acirc': '\xE2',
+ 'Acirc': '\xC2',
+ 'acute': '\xB4',
+ 'acy': "\u0430",
+ 'Acy': "\u0410",
+ 'aelig': '\xE6',
+ 'AElig': '\xC6',
+ 'af': "\u2061",
+ 'afr': "\uD835\uDD1E",
+ 'Afr': "\uD835\uDD04",
+ 'agrave': '\xE0',
+ 'Agrave': '\xC0',
+ 'alefsym': "\u2135",
+ 'aleph': "\u2135",
+ 'alpha': "\u03B1",
+ 'Alpha': "\u0391",
+ 'amacr': "\u0101",
+ 'Amacr': "\u0100",
+ 'amalg': "\u2A3F",
+ 'amp': '&',
+ 'AMP': '&',
+ 'and': "\u2227",
+ 'And': "\u2A53",
+ 'andand': "\u2A55",
+ 'andd': "\u2A5C",
+ 'andslope': "\u2A58",
+ 'andv': "\u2A5A",
+ 'ang': "\u2220",
+ 'ange': "\u29A4",
+ 'angle': "\u2220",
+ 'angmsd': "\u2221",
+ 'angmsdaa': "\u29A8",
+ 'angmsdab': "\u29A9",
+ 'angmsdac': "\u29AA",
+ 'angmsdad': "\u29AB",
+ 'angmsdae': "\u29AC",
+ 'angmsdaf': "\u29AD",
+ 'angmsdag': "\u29AE",
+ 'angmsdah': "\u29AF",
+ 'angrt': "\u221F",
+ 'angrtvb': "\u22BE",
+ 'angrtvbd': "\u299D",
+ 'angsph': "\u2222",
+ 'angst': '\xC5',
+ 'angzarr': "\u237C",
+ 'aogon': "\u0105",
+ 'Aogon': "\u0104",
+ 'aopf': "\uD835\uDD52",
+ 'Aopf': "\uD835\uDD38",
+ 'ap': "\u2248",
+ 'apacir': "\u2A6F",
+ 'ape': "\u224A",
+ 'apE': "\u2A70",
+ 'apid': "\u224B",
+ 'apos': '\'',
+ 'ApplyFunction': "\u2061",
+ 'approx': "\u2248",
+ 'approxeq': "\u224A",
+ 'aring': '\xE5',
+ 'Aring': '\xC5',
+ 'ascr': "\uD835\uDCB6",
+ 'Ascr': "\uD835\uDC9C",
+ 'Assign': "\u2254",
+ 'ast': '*',
+ 'asymp': "\u2248",
+ 'asympeq': "\u224D",
+ 'atilde': '\xE3',
+ 'Atilde': '\xC3',
+ 'auml': '\xE4',
+ 'Auml': '\xC4',
+ 'awconint': "\u2233",
+ 'awint': "\u2A11",
+ 'backcong': "\u224C",
+ 'backepsilon': "\u03F6",
+ 'backprime': "\u2035",
+ 'backsim': "\u223D",
+ 'backsimeq': "\u22CD",
+ 'Backslash': "\u2216",
+ 'Barv': "\u2AE7",
+ 'barvee': "\u22BD",
+ 'barwed': "\u2305",
+ 'Barwed': "\u2306",
+ 'barwedge': "\u2305",
+ 'bbrk': "\u23B5",
+ 'bbrktbrk': "\u23B6",
+ 'bcong': "\u224C",
+ 'bcy': "\u0431",
+ 'Bcy': "\u0411",
+ 'bdquo': "\u201E",
+ 'becaus': "\u2235",
+ 'because': "\u2235",
+ 'Because': "\u2235",
+ 'bemptyv': "\u29B0",
+ 'bepsi': "\u03F6",
+ 'bernou': "\u212C",
+ 'Bernoullis': "\u212C",
+ 'beta': "\u03B2",
+ 'Beta': "\u0392",
+ 'beth': "\u2136",
+ 'between': "\u226C",
+ 'bfr': "\uD835\uDD1F",
+ 'Bfr': "\uD835\uDD05",
+ 'bigcap': "\u22C2",
+ 'bigcirc': "\u25EF",
+ 'bigcup': "\u22C3",
+ 'bigodot': "\u2A00",
+ 'bigoplus': "\u2A01",
+ 'bigotimes': "\u2A02",
+ 'bigsqcup': "\u2A06",
+ 'bigstar': "\u2605",
+ 'bigtriangledown': "\u25BD",
+ 'bigtriangleup': "\u25B3",
+ 'biguplus': "\u2A04",
+ 'bigvee': "\u22C1",
+ 'bigwedge': "\u22C0",
+ 'bkarow': "\u290D",
+ 'blacklozenge': "\u29EB",
+ 'blacksquare': "\u25AA",
+ 'blacktriangle': "\u25B4",
+ 'blacktriangledown': "\u25BE",
+ 'blacktriangleleft': "\u25C2",
+ 'blacktriangleright': "\u25B8",
+ 'blank': "\u2423",
+ 'blk12': "\u2592",
+ 'blk14': "\u2591",
+ 'blk34': "\u2593",
+ 'block': "\u2588",
+ 'bne': "=\u20E5",
+ 'bnequiv': "\u2261\u20E5",
+ 'bnot': "\u2310",
+ 'bNot': "\u2AED",
+ 'bopf': "\uD835\uDD53",
+ 'Bopf': "\uD835\uDD39",
+ 'bot': "\u22A5",
+ 'bottom': "\u22A5",
+ 'bowtie': "\u22C8",
+ 'boxbox': "\u29C9",
+ 'boxdl': "\u2510",
+ 'boxdL': "\u2555",
+ 'boxDl': "\u2556",
+ 'boxDL': "\u2557",
+ 'boxdr': "\u250C",
+ 'boxdR': "\u2552",
+ 'boxDr': "\u2553",
+ 'boxDR': "\u2554",
+ 'boxh': "\u2500",
+ 'boxH': "\u2550",
+ 'boxhd': "\u252C",
+ 'boxhD': "\u2565",
+ 'boxHd': "\u2564",
+ 'boxHD': "\u2566",
+ 'boxhu': "\u2534",
+ 'boxhU': "\u2568",
+ 'boxHu': "\u2567",
+ 'boxHU': "\u2569",
+ 'boxminus': "\u229F",
+ 'boxplus': "\u229E",
+ 'boxtimes': "\u22A0",
+ 'boxul': "\u2518",
+ 'boxuL': "\u255B",
+ 'boxUl': "\u255C",
+ 'boxUL': "\u255D",
+ 'boxur': "\u2514",
+ 'boxuR': "\u2558",
+ 'boxUr': "\u2559",
+ 'boxUR': "\u255A",
+ 'boxv': "\u2502",
+ 'boxV': "\u2551",
+ 'boxvh': "\u253C",
+ 'boxvH': "\u256A",
+ 'boxVh': "\u256B",
+ 'boxVH': "\u256C",
+ 'boxvl': "\u2524",
+ 'boxvL': "\u2561",
+ 'boxVl': "\u2562",
+ 'boxVL': "\u2563",
+ 'boxvr': "\u251C",
+ 'boxvR': "\u255E",
+ 'boxVr': "\u255F",
+ 'boxVR': "\u2560",
+ 'bprime': "\u2035",
+ 'breve': "\u02D8",
+ 'Breve': "\u02D8",
+ 'brvbar': '\xA6',
+ 'bscr': "\uD835\uDCB7",
+ 'Bscr': "\u212C",
+ 'bsemi': "\u204F",
+ 'bsim': "\u223D",
+ 'bsime': "\u22CD",
+ 'bsol': '\\',
+ 'bsolb': "\u29C5",
+ 'bsolhsub': "\u27C8",
+ 'bull': "\u2022",
+ 'bullet': "\u2022",
+ 'bump': "\u224E",
+ 'bumpe': "\u224F",
+ 'bumpE': "\u2AAE",
+ 'bumpeq': "\u224F",
+ 'Bumpeq': "\u224E",
+ 'cacute': "\u0107",
+ 'Cacute': "\u0106",
+ 'cap': "\u2229",
+ 'Cap': "\u22D2",
+ 'capand': "\u2A44",
+ 'capbrcup': "\u2A49",
+ 'capcap': "\u2A4B",
+ 'capcup': "\u2A47",
+ 'capdot': "\u2A40",
+ 'CapitalDifferentialD': "\u2145",
+ 'caps': "\u2229\uFE00",
+ 'caret': "\u2041",
+ 'caron': "\u02C7",
+ 'Cayleys': "\u212D",
+ 'ccaps': "\u2A4D",
+ 'ccaron': "\u010D",
+ 'Ccaron': "\u010C",
+ 'ccedil': '\xE7',
+ 'Ccedil': '\xC7',
+ 'ccirc': "\u0109",
+ 'Ccirc': "\u0108",
+ 'Cconint': "\u2230",
+ 'ccups': "\u2A4C",
+ 'ccupssm': "\u2A50",
+ 'cdot': "\u010B",
+ 'Cdot': "\u010A",
+ 'cedil': '\xB8',
+ 'Cedilla': '\xB8',
+ 'cemptyv': "\u29B2",
+ 'cent': '\xA2',
+ 'centerdot': '\xB7',
+ 'CenterDot': '\xB7',
+ 'cfr': "\uD835\uDD20",
+ 'Cfr': "\u212D",
+ 'chcy': "\u0447",
+ 'CHcy': "\u0427",
+ 'check': "\u2713",
+ 'checkmark': "\u2713",
+ 'chi': "\u03C7",
+ 'Chi': "\u03A7",
+ 'cir': "\u25CB",
+ 'circ': "\u02C6",
+ 'circeq': "\u2257",
+ 'circlearrowleft': "\u21BA",
+ 'circlearrowright': "\u21BB",
+ 'circledast': "\u229B",
+ 'circledcirc': "\u229A",
+ 'circleddash': "\u229D",
+ 'CircleDot': "\u2299",
+ 'circledR': '\xAE',
+ 'circledS': "\u24C8",
+ 'CircleMinus': "\u2296",
+ 'CirclePlus': "\u2295",
+ 'CircleTimes': "\u2297",
+ 'cire': "\u2257",
+ 'cirE': "\u29C3",
+ 'cirfnint': "\u2A10",
+ 'cirmid': "\u2AEF",
+ 'cirscir': "\u29C2",
+ 'ClockwiseContourIntegral': "\u2232",
+ 'CloseCurlyDoubleQuote': "\u201D",
+ 'CloseCurlyQuote': "\u2019",
+ 'clubs': "\u2663",
+ 'clubsuit': "\u2663",
+ 'colon': ':',
+ 'Colon': "\u2237",
+ 'colone': "\u2254",
+ 'Colone': "\u2A74",
+ 'coloneq': "\u2254",
+ 'comma': ',',
+ 'commat': '@',
+ 'comp': "\u2201",
+ 'compfn': "\u2218",
+ 'complement': "\u2201",
+ 'complexes': "\u2102",
+ 'cong': "\u2245",
+ 'congdot': "\u2A6D",
+ 'Congruent': "\u2261",
+ 'conint': "\u222E",
+ 'Conint': "\u222F",
+ 'ContourIntegral': "\u222E",
+ 'copf': "\uD835\uDD54",
+ 'Copf': "\u2102",
+ 'coprod': "\u2210",
+ 'Coproduct': "\u2210",
+ 'copy': '\xA9',
+ 'COPY': '\xA9',
+ 'copysr': "\u2117",
+ 'CounterClockwiseContourIntegral': "\u2233",
+ 'crarr': "\u21B5",
+ 'cross': "\u2717",
+ 'Cross': "\u2A2F",
+ 'cscr': "\uD835\uDCB8",
+ 'Cscr': "\uD835\uDC9E",
+ 'csub': "\u2ACF",
+ 'csube': "\u2AD1",
+ 'csup': "\u2AD0",
+ 'csupe': "\u2AD2",
+ 'ctdot': "\u22EF",
+ 'cudarrl': "\u2938",
+ 'cudarrr': "\u2935",
+ 'cuepr': "\u22DE",
+ 'cuesc': "\u22DF",
+ 'cularr': "\u21B6",
+ 'cularrp': "\u293D",
+ 'cup': "\u222A",
+ 'Cup': "\u22D3",
+ 'cupbrcap': "\u2A48",
+ 'cupcap': "\u2A46",
+ 'CupCap': "\u224D",
+ 'cupcup': "\u2A4A",
+ 'cupdot': "\u228D",
+ 'cupor': "\u2A45",
+ 'cups': "\u222A\uFE00",
+ 'curarr': "\u21B7",
+ 'curarrm': "\u293C",
+ 'curlyeqprec': "\u22DE",
+ 'curlyeqsucc': "\u22DF",
+ 'curlyvee': "\u22CE",
+ 'curlywedge': "\u22CF",
+ 'curren': '\xA4',
+ 'curvearrowleft': "\u21B6",
+ 'curvearrowright': "\u21B7",
+ 'cuvee': "\u22CE",
+ 'cuwed': "\u22CF",
+ 'cwconint': "\u2232",
+ 'cwint': "\u2231",
+ 'cylcty': "\u232D",
+ 'dagger': "\u2020",
+ 'Dagger': "\u2021",
+ 'daleth': "\u2138",
+ 'darr': "\u2193",
+ 'dArr': "\u21D3",
+ 'Darr': "\u21A1",
+ 'dash': "\u2010",
+ 'dashv': "\u22A3",
+ 'Dashv': "\u2AE4",
+ 'dbkarow': "\u290F",
+ 'dblac': "\u02DD",
+ 'dcaron': "\u010F",
+ 'Dcaron': "\u010E",
+ 'dcy': "\u0434",
+ 'Dcy': "\u0414",
+ 'dd': "\u2146",
+ 'DD': "\u2145",
+ 'ddagger': "\u2021",
+ 'ddarr': "\u21CA",
+ 'DDotrahd': "\u2911",
+ 'ddotseq': "\u2A77",
+ 'deg': '\xB0',
+ 'Del': "\u2207",
+ 'delta': "\u03B4",
+ 'Delta': "\u0394",
+ 'demptyv': "\u29B1",
+ 'dfisht': "\u297F",
+ 'dfr': "\uD835\uDD21",
+ 'Dfr': "\uD835\uDD07",
+ 'dHar': "\u2965",
+ 'dharl': "\u21C3",
+ 'dharr': "\u21C2",
+ 'DiacriticalAcute': '\xB4',
+ 'DiacriticalDot': "\u02D9",
+ 'DiacriticalDoubleAcute': "\u02DD",
+ 'DiacriticalGrave': '`',
+ 'DiacriticalTilde': "\u02DC",
+ 'diam': "\u22C4",
+ 'diamond': "\u22C4",
+ 'Diamond': "\u22C4",
+ 'diamondsuit': "\u2666",
+ 'diams': "\u2666",
+ 'die': '\xA8',
+ 'DifferentialD': "\u2146",
+ 'digamma': "\u03DD",
+ 'disin': "\u22F2",
+ 'div': '\xF7',
+ 'divide': '\xF7',
+ 'divideontimes': "\u22C7",
+ 'divonx': "\u22C7",
+ 'djcy': "\u0452",
+ 'DJcy': "\u0402",
+ 'dlcorn': "\u231E",
+ 'dlcrop': "\u230D",
+ 'dollar': '$',
+ 'dopf': "\uD835\uDD55",
+ 'Dopf': "\uD835\uDD3B",
+ 'dot': "\u02D9",
+ 'Dot': '\xA8',
+ 'DotDot': "\u20DC",
+ 'doteq': "\u2250",
+ 'doteqdot': "\u2251",
+ 'DotEqual': "\u2250",
+ 'dotminus': "\u2238",
+ 'dotplus': "\u2214",
+ 'dotsquare': "\u22A1",
+ 'doublebarwedge': "\u2306",
+ 'DoubleContourIntegral': "\u222F",
+ 'DoubleDot': '\xA8',
+ 'DoubleDownArrow': "\u21D3",
+ 'DoubleLeftArrow': "\u21D0",
+ 'DoubleLeftRightArrow': "\u21D4",
+ 'DoubleLeftTee': "\u2AE4",
+ 'DoubleLongLeftArrow': "\u27F8",
+ 'DoubleLongLeftRightArrow': "\u27FA",
+ 'DoubleLongRightArrow': "\u27F9",
+ 'DoubleRightArrow': "\u21D2",
+ 'DoubleRightTee': "\u22A8",
+ 'DoubleUpArrow': "\u21D1",
+ 'DoubleUpDownArrow': "\u21D5",
+ 'DoubleVerticalBar': "\u2225",
+ 'downarrow': "\u2193",
+ 'Downarrow': "\u21D3",
+ 'DownArrow': "\u2193",
+ 'DownArrowBar': "\u2913",
+ 'DownArrowUpArrow': "\u21F5",
+ 'DownBreve': "\u0311",
+ 'downdownarrows': "\u21CA",
+ 'downharpoonleft': "\u21C3",
+ 'downharpoonright': "\u21C2",
+ 'DownLeftRightVector': "\u2950",
+ 'DownLeftTeeVector': "\u295E",
+ 'DownLeftVector': "\u21BD",
+ 'DownLeftVectorBar': "\u2956",
+ 'DownRightTeeVector': "\u295F",
+ 'DownRightVector': "\u21C1",
+ 'DownRightVectorBar': "\u2957",
+ 'DownTee': "\u22A4",
+ 'DownTeeArrow': "\u21A7",
+ 'drbkarow': "\u2910",
+ 'drcorn': "\u231F",
+ 'drcrop': "\u230C",
+ 'dscr': "\uD835\uDCB9",
+ 'Dscr': "\uD835\uDC9F",
+ 'dscy': "\u0455",
+ 'DScy': "\u0405",
+ 'dsol': "\u29F6",
+ 'dstrok': "\u0111",
+ 'Dstrok': "\u0110",
+ 'dtdot': "\u22F1",
+ 'dtri': "\u25BF",
+ 'dtrif': "\u25BE",
+ 'duarr': "\u21F5",
+ 'duhar': "\u296F",
+ 'dwangle': "\u29A6",
+ 'dzcy': "\u045F",
+ 'DZcy': "\u040F",
+ 'dzigrarr': "\u27FF",
+ 'eacute': '\xE9',
+ 'Eacute': '\xC9',
+ 'easter': "\u2A6E",
+ 'ecaron': "\u011B",
+ 'Ecaron': "\u011A",
+ 'ecir': "\u2256",
+ 'ecirc': '\xEA',
+ 'Ecirc': '\xCA',
+ 'ecolon': "\u2255",
+ 'ecy': "\u044D",
+ 'Ecy': "\u042D",
+ 'eDDot': "\u2A77",
+ 'edot': "\u0117",
+ 'eDot': "\u2251",
+ 'Edot': "\u0116",
+ 'ee': "\u2147",
+ 'efDot': "\u2252",
+ 'efr': "\uD835\uDD22",
+ 'Efr': "\uD835\uDD08",
+ 'eg': "\u2A9A",
+ 'egrave': '\xE8',
+ 'Egrave': '\xC8',
+ 'egs': "\u2A96",
+ 'egsdot': "\u2A98",
+ 'el': "\u2A99",
+ 'Element': "\u2208",
+ 'elinters': "\u23E7",
+ 'ell': "\u2113",
+ 'els': "\u2A95",
+ 'elsdot': "\u2A97",
+ 'emacr': "\u0113",
+ 'Emacr': "\u0112",
+ 'empty': "\u2205",
+ 'emptyset': "\u2205",
+ 'EmptySmallSquare': "\u25FB",
+ 'emptyv': "\u2205",
+ 'EmptyVerySmallSquare': "\u25AB",
+ 'emsp': "\u2003",
+ 'emsp13': "\u2004",
+ 'emsp14': "\u2005",
+ 'eng': "\u014B",
+ 'ENG': "\u014A",
+ 'ensp': "\u2002",
+ 'eogon': "\u0119",
+ 'Eogon': "\u0118",
+ 'eopf': "\uD835\uDD56",
+ 'Eopf': "\uD835\uDD3C",
+ 'epar': "\u22D5",
+ 'eparsl': "\u29E3",
+ 'eplus': "\u2A71",
+ 'epsi': "\u03B5",
+ 'epsilon': "\u03B5",
+ 'Epsilon': "\u0395",
+ 'epsiv': "\u03F5",
+ 'eqcirc': "\u2256",
+ 'eqcolon': "\u2255",
+ 'eqsim': "\u2242",
+ 'eqslantgtr': "\u2A96",
+ 'eqslantless': "\u2A95",
+ 'Equal': "\u2A75",
+ 'equals': '=',
+ 'EqualTilde': "\u2242",
+ 'equest': "\u225F",
+ 'Equilibrium': "\u21CC",
+ 'equiv': "\u2261",
+ 'equivDD': "\u2A78",
+ 'eqvparsl': "\u29E5",
+ 'erarr': "\u2971",
+ 'erDot': "\u2253",
+ 'escr': "\u212F",
+ 'Escr': "\u2130",
+ 'esdot': "\u2250",
+ 'esim': "\u2242",
+ 'Esim': "\u2A73",
+ 'eta': "\u03B7",
+ 'Eta': "\u0397",
+ 'eth': '\xF0',
+ 'ETH': '\xD0',
+ 'euml': '\xEB',
+ 'Euml': '\xCB',
+ 'euro': "\u20AC",
+ 'excl': '!',
+ 'exist': "\u2203",
+ 'Exists': "\u2203",
+ 'expectation': "\u2130",
+ 'exponentiale': "\u2147",
+ 'ExponentialE': "\u2147",
+ 'fallingdotseq': "\u2252",
+ 'fcy': "\u0444",
+ 'Fcy': "\u0424",
+ 'female': "\u2640",
+ 'ffilig': "\uFB03",
+ 'fflig': "\uFB00",
+ 'ffllig': "\uFB04",
+ 'ffr': "\uD835\uDD23",
+ 'Ffr': "\uD835\uDD09",
+ 'filig': "\uFB01",
+ 'FilledSmallSquare': "\u25FC",
+ 'FilledVerySmallSquare': "\u25AA",
+ 'fjlig': 'fj',
+ 'flat': "\u266D",
+ 'fllig': "\uFB02",
+ 'fltns': "\u25B1",
+ 'fnof': "\u0192",
+ 'fopf': "\uD835\uDD57",
+ 'Fopf': "\uD835\uDD3D",
+ 'forall': "\u2200",
+ 'ForAll': "\u2200",
+ 'fork': "\u22D4",
+ 'forkv': "\u2AD9",
+ 'Fouriertrf': "\u2131",
+ 'fpartint': "\u2A0D",
+ 'frac12': '\xBD',
+ 'frac13': "\u2153",
+ 'frac14': '\xBC',
+ 'frac15': "\u2155",
+ 'frac16': "\u2159",
+ 'frac18': "\u215B",
+ 'frac23': "\u2154",
+ 'frac25': "\u2156",
+ 'frac34': '\xBE',
+ 'frac35': "\u2157",
+ 'frac38': "\u215C",
+ 'frac45': "\u2158",
+ 'frac56': "\u215A",
+ 'frac58': "\u215D",
+ 'frac78': "\u215E",
+ 'frasl': "\u2044",
+ 'frown': "\u2322",
+ 'fscr': "\uD835\uDCBB",
+ 'Fscr': "\u2131",
+ 'gacute': "\u01F5",
+ 'gamma': "\u03B3",
+ 'Gamma': "\u0393",
+ 'gammad': "\u03DD",
+ 'Gammad': "\u03DC",
+ 'gap': "\u2A86",
+ 'gbreve': "\u011F",
+ 'Gbreve': "\u011E",
+ 'Gcedil': "\u0122",
+ 'gcirc': "\u011D",
+ 'Gcirc': "\u011C",
+ 'gcy': "\u0433",
+ 'Gcy': "\u0413",
+ 'gdot': "\u0121",
+ 'Gdot': "\u0120",
+ 'ge': "\u2265",
+ 'gE': "\u2267",
+ 'gel': "\u22DB",
+ 'gEl': "\u2A8C",
+ 'geq': "\u2265",
+ 'geqq': "\u2267",
+ 'geqslant': "\u2A7E",
+ 'ges': "\u2A7E",
+ 'gescc': "\u2AA9",
+ 'gesdot': "\u2A80",
+ 'gesdoto': "\u2A82",
+ 'gesdotol': "\u2A84",
+ 'gesl': "\u22DB\uFE00",
+ 'gesles': "\u2A94",
+ 'gfr': "\uD835\uDD24",
+ 'Gfr': "\uD835\uDD0A",
+ 'gg': "\u226B",
+ 'Gg': "\u22D9",
+ 'ggg': "\u22D9",
+ 'gimel': "\u2137",
+ 'gjcy': "\u0453",
+ 'GJcy': "\u0403",
+ 'gl': "\u2277",
+ 'gla': "\u2AA5",
+ 'glE': "\u2A92",
+ 'glj': "\u2AA4",
+ 'gnap': "\u2A8A",
+ 'gnapprox': "\u2A8A",
+ 'gne': "\u2A88",
+ 'gnE': "\u2269",
+ 'gneq': "\u2A88",
+ 'gneqq': "\u2269",
+ 'gnsim': "\u22E7",
+ 'gopf': "\uD835\uDD58",
+ 'Gopf': "\uD835\uDD3E",
+ 'grave': '`',
+ 'GreaterEqual': "\u2265",
+ 'GreaterEqualLess': "\u22DB",
+ 'GreaterFullEqual': "\u2267",
+ 'GreaterGreater': "\u2AA2",
+ 'GreaterLess': "\u2277",
+ 'GreaterSlantEqual': "\u2A7E",
+ 'GreaterTilde': "\u2273",
+ 'gscr': "\u210A",
+ 'Gscr': "\uD835\uDCA2",
+ 'gsim': "\u2273",
+ 'gsime': "\u2A8E",
+ 'gsiml': "\u2A90",
+ 'gt': '>',
+ 'Gt': "\u226B",
+ 'GT': '>',
+ 'gtcc': "\u2AA7",
+ 'gtcir': "\u2A7A",
+ 'gtdot': "\u22D7",
+ 'gtlPar': "\u2995",
+ 'gtquest': "\u2A7C",
+ 'gtrapprox': "\u2A86",
+ 'gtrarr': "\u2978",
+ 'gtrdot': "\u22D7",
+ 'gtreqless': "\u22DB",
+ 'gtreqqless': "\u2A8C",
+ 'gtrless': "\u2277",
+ 'gtrsim': "\u2273",
+ 'gvertneqq': "\u2269\uFE00",
+ 'gvnE': "\u2269\uFE00",
+ 'Hacek': "\u02C7",
+ 'hairsp': "\u200A",
+ 'half': '\xBD',
+ 'hamilt': "\u210B",
+ 'hardcy': "\u044A",
+ 'HARDcy': "\u042A",
+ 'harr': "\u2194",
+ 'hArr': "\u21D4",
+ 'harrcir': "\u2948",
+ 'harrw': "\u21AD",
+ 'Hat': '^',
+ 'hbar': "\u210F",
+ 'hcirc': "\u0125",
+ 'Hcirc': "\u0124",
+ 'hearts': "\u2665",
+ 'heartsuit': "\u2665",
+ 'hellip': "\u2026",
+ 'hercon': "\u22B9",
+ 'hfr': "\uD835\uDD25",
+ 'Hfr': "\u210C",
+ 'HilbertSpace': "\u210B",
+ 'hksearow': "\u2925",
+ 'hkswarow': "\u2926",
+ 'hoarr': "\u21FF",
+ 'homtht': "\u223B",
+ 'hookleftarrow': "\u21A9",
+ 'hookrightarrow': "\u21AA",
+ 'hopf': "\uD835\uDD59",
+ 'Hopf': "\u210D",
+ 'horbar': "\u2015",
+ 'HorizontalLine': "\u2500",
+ 'hscr': "\uD835\uDCBD",
+ 'Hscr': "\u210B",
+ 'hslash': "\u210F",
+ 'hstrok': "\u0127",
+ 'Hstrok': "\u0126",
+ 'HumpDownHump': "\u224E",
+ 'HumpEqual': "\u224F",
+ 'hybull': "\u2043",
+ 'hyphen': "\u2010",
+ 'iacute': '\xED',
+ 'Iacute': '\xCD',
+ 'ic': "\u2063",
+ 'icirc': '\xEE',
+ 'Icirc': '\xCE',
+ 'icy': "\u0438",
+ 'Icy': "\u0418",
+ 'Idot': "\u0130",
+ 'iecy': "\u0435",
+ 'IEcy': "\u0415",
+ 'iexcl': '\xA1',
+ 'iff': "\u21D4",
+ 'ifr': "\uD835\uDD26",
+ 'Ifr': "\u2111",
+ 'igrave': '\xEC',
+ 'Igrave': '\xCC',
+ 'ii': "\u2148",
+ 'iiiint': "\u2A0C",
+ 'iiint': "\u222D",
+ 'iinfin': "\u29DC",
+ 'iiota': "\u2129",
+ 'ijlig': "\u0133",
+ 'IJlig': "\u0132",
+ 'Im': "\u2111",
+ 'imacr': "\u012B",
+ 'Imacr': "\u012A",
+ 'image': "\u2111",
+ 'ImaginaryI': "\u2148",
+ 'imagline': "\u2110",
+ 'imagpart': "\u2111",
+ 'imath': "\u0131",
+ 'imof': "\u22B7",
+ 'imped': "\u01B5",
+ 'Implies': "\u21D2",
+ 'in': "\u2208",
+ 'incare': "\u2105",
+ 'infin': "\u221E",
+ 'infintie': "\u29DD",
+ 'inodot': "\u0131",
+ 'int': "\u222B",
+ 'Int': "\u222C",
+ 'intcal': "\u22BA",
+ 'integers': "\u2124",
+ 'Integral': "\u222B",
+ 'intercal': "\u22BA",
+ 'Intersection': "\u22C2",
+ 'intlarhk': "\u2A17",
+ 'intprod': "\u2A3C",
+ 'InvisibleComma': "\u2063",
+ 'InvisibleTimes': "\u2062",
+ 'iocy': "\u0451",
+ 'IOcy': "\u0401",
+ 'iogon': "\u012F",
+ 'Iogon': "\u012E",
+ 'iopf': "\uD835\uDD5A",
+ 'Iopf': "\uD835\uDD40",
+ 'iota': "\u03B9",
+ 'Iota': "\u0399",
+ 'iprod': "\u2A3C",
+ 'iquest': '\xBF',
+ 'iscr': "\uD835\uDCBE",
+ 'Iscr': "\u2110",
+ 'isin': "\u2208",
+ 'isindot': "\u22F5",
+ 'isinE': "\u22F9",
+ 'isins': "\u22F4",
+ 'isinsv': "\u22F3",
+ 'isinv': "\u2208",
+ 'it': "\u2062",
+ 'itilde': "\u0129",
+ 'Itilde': "\u0128",
+ 'iukcy': "\u0456",
+ 'Iukcy': "\u0406",
+ 'iuml': '\xEF',
+ 'Iuml': '\xCF',
+ 'jcirc': "\u0135",
+ 'Jcirc': "\u0134",
+ 'jcy': "\u0439",
+ 'Jcy': "\u0419",
+ 'jfr': "\uD835\uDD27",
+ 'Jfr': "\uD835\uDD0D",
+ 'jmath': "\u0237",
+ 'jopf': "\uD835\uDD5B",
+ 'Jopf': "\uD835\uDD41",
+ 'jscr': "\uD835\uDCBF",
+ 'Jscr': "\uD835\uDCA5",
+ 'jsercy': "\u0458",
+ 'Jsercy': "\u0408",
+ 'jukcy': "\u0454",
+ 'Jukcy': "\u0404",
+ 'kappa': "\u03BA",
+ 'Kappa': "\u039A",
+ 'kappav': "\u03F0",
+ 'kcedil': "\u0137",
+ 'Kcedil': "\u0136",
+ 'kcy': "\u043A",
+ 'Kcy': "\u041A",
+ 'kfr': "\uD835\uDD28",
+ 'Kfr': "\uD835\uDD0E",
+ 'kgreen': "\u0138",
+ 'khcy': "\u0445",
+ 'KHcy': "\u0425",
+ 'kjcy': "\u045C",
+ 'KJcy': "\u040C",
+ 'kopf': "\uD835\uDD5C",
+ 'Kopf': "\uD835\uDD42",
+ 'kscr': "\uD835\uDCC0",
+ 'Kscr': "\uD835\uDCA6",
+ 'lAarr': "\u21DA",
+ 'lacute': "\u013A",
+ 'Lacute': "\u0139",
+ 'laemptyv': "\u29B4",
+ 'lagran': "\u2112",
+ 'lambda': "\u03BB",
+ 'Lambda': "\u039B",
+ 'lang': "\u27E8",
+ 'Lang': "\u27EA",
+ 'langd': "\u2991",
+ 'langle': "\u27E8",
+ 'lap': "\u2A85",
+ 'Laplacetrf': "\u2112",
+ 'laquo': '\xAB',
+ 'larr': "\u2190",
+ 'lArr': "\u21D0",
+ 'Larr': "\u219E",
+ 'larrb': "\u21E4",
+ 'larrbfs': "\u291F",
+ 'larrfs': "\u291D",
+ 'larrhk': "\u21A9",
+ 'larrlp': "\u21AB",
+ 'larrpl': "\u2939",
+ 'larrsim': "\u2973",
+ 'larrtl': "\u21A2",
+ 'lat': "\u2AAB",
+ 'latail': "\u2919",
+ 'lAtail': "\u291B",
+ 'late': "\u2AAD",
+ 'lates': "\u2AAD\uFE00",
+ 'lbarr': "\u290C",
+ 'lBarr': "\u290E",
+ 'lbbrk': "\u2772",
+ 'lbrace': '{',
+ 'lbrack': '[',
+ 'lbrke': "\u298B",
+ 'lbrksld': "\u298F",
+ 'lbrkslu': "\u298D",
+ 'lcaron': "\u013E",
+ 'Lcaron': "\u013D",
+ 'lcedil': "\u013C",
+ 'Lcedil': "\u013B",
+ 'lceil': "\u2308",
+ 'lcub': '{',
+ 'lcy': "\u043B",
+ 'Lcy': "\u041B",
+ 'ldca': "\u2936",
+ 'ldquo': "\u201C",
+ 'ldquor': "\u201E",
+ 'ldrdhar': "\u2967",
+ 'ldrushar': "\u294B",
+ 'ldsh': "\u21B2",
+ 'le': "\u2264",
+ 'lE': "\u2266",
+ 'LeftAngleBracket': "\u27E8",
+ 'leftarrow': "\u2190",
+ 'Leftarrow': "\u21D0",
+ 'LeftArrow': "\u2190",
+ 'LeftArrowBar': "\u21E4",
+ 'LeftArrowRightArrow': "\u21C6",
+ 'leftarrowtail': "\u21A2",
+ 'LeftCeiling': "\u2308",
+ 'LeftDoubleBracket': "\u27E6",
+ 'LeftDownTeeVector': "\u2961",
+ 'LeftDownVector': "\u21C3",
+ 'LeftDownVectorBar': "\u2959",
+ 'LeftFloor': "\u230A",
+ 'leftharpoondown': "\u21BD",
+ 'leftharpoonup': "\u21BC",
+ 'leftleftarrows': "\u21C7",
+ 'leftrightarrow': "\u2194",
+ 'Leftrightarrow': "\u21D4",
+ 'LeftRightArrow': "\u2194",
+ 'leftrightarrows': "\u21C6",
+ 'leftrightharpoons': "\u21CB",
+ 'leftrightsquigarrow': "\u21AD",
+ 'LeftRightVector': "\u294E",
+ 'LeftTee': "\u22A3",
+ 'LeftTeeArrow': "\u21A4",
+ 'LeftTeeVector': "\u295A",
+ 'leftthreetimes': "\u22CB",
+ 'LeftTriangle': "\u22B2",
+ 'LeftTriangleBar': "\u29CF",
+ 'LeftTriangleEqual': "\u22B4",
+ 'LeftUpDownVector': "\u2951",
+ 'LeftUpTeeVector': "\u2960",
+ 'LeftUpVector': "\u21BF",
+ 'LeftUpVectorBar': "\u2958",
+ 'LeftVector': "\u21BC",
+ 'LeftVectorBar': "\u2952",
+ 'leg': "\u22DA",
+ 'lEg': "\u2A8B",
+ 'leq': "\u2264",
+ 'leqq': "\u2266",
+ 'leqslant': "\u2A7D",
+ 'les': "\u2A7D",
+ 'lescc': "\u2AA8",
+ 'lesdot': "\u2A7F",
+ 'lesdoto': "\u2A81",
+ 'lesdotor': "\u2A83",
+ 'lesg': "\u22DA\uFE00",
+ 'lesges': "\u2A93",
+ 'lessapprox': "\u2A85",
+ 'lessdot': "\u22D6",
+ 'lesseqgtr': "\u22DA",
+ 'lesseqqgtr': "\u2A8B",
+ 'LessEqualGreater': "\u22DA",
+ 'LessFullEqual': "\u2266",
+ 'LessGreater': "\u2276",
+ 'lessgtr': "\u2276",
+ 'LessLess': "\u2AA1",
+ 'lesssim': "\u2272",
+ 'LessSlantEqual': "\u2A7D",
+ 'LessTilde': "\u2272",
+ 'lfisht': "\u297C",
+ 'lfloor': "\u230A",
+ 'lfr': "\uD835\uDD29",
+ 'Lfr': "\uD835\uDD0F",
+ 'lg': "\u2276",
+ 'lgE': "\u2A91",
+ 'lHar': "\u2962",
+ 'lhard': "\u21BD",
+ 'lharu': "\u21BC",
+ 'lharul': "\u296A",
+ 'lhblk': "\u2584",
+ 'ljcy': "\u0459",
+ 'LJcy': "\u0409",
+ 'll': "\u226A",
+ 'Ll': "\u22D8",
+ 'llarr': "\u21C7",
+ 'llcorner': "\u231E",
+ 'Lleftarrow': "\u21DA",
+ 'llhard': "\u296B",
+ 'lltri': "\u25FA",
+ 'lmidot': "\u0140",
+ 'Lmidot': "\u013F",
+ 'lmoust': "\u23B0",
+ 'lmoustache': "\u23B0",
+ 'lnap': "\u2A89",
+ 'lnapprox': "\u2A89",
+ 'lne': "\u2A87",
+ 'lnE': "\u2268",
+ 'lneq': "\u2A87",
+ 'lneqq': "\u2268",
+ 'lnsim': "\u22E6",
+ 'loang': "\u27EC",
+ 'loarr': "\u21FD",
+ 'lobrk': "\u27E6",
+ 'longleftarrow': "\u27F5",
+ 'Longleftarrow': "\u27F8",
+ 'LongLeftArrow': "\u27F5",
+ 'longleftrightarrow': "\u27F7",
+ 'Longleftrightarrow': "\u27FA",
+ 'LongLeftRightArrow': "\u27F7",
+ 'longmapsto': "\u27FC",
+ 'longrightarrow': "\u27F6",
+ 'Longrightarrow': "\u27F9",
+ 'LongRightArrow': "\u27F6",
+ 'looparrowleft': "\u21AB",
+ 'looparrowright': "\u21AC",
+ 'lopar': "\u2985",
+ 'lopf': "\uD835\uDD5D",
+ 'Lopf': "\uD835\uDD43",
+ 'loplus': "\u2A2D",
+ 'lotimes': "\u2A34",
+ 'lowast': "\u2217",
+ 'lowbar': '_',
+ 'LowerLeftArrow': "\u2199",
+ 'LowerRightArrow': "\u2198",
+ 'loz': "\u25CA",
+ 'lozenge': "\u25CA",
+ 'lozf': "\u29EB",
+ 'lpar': '(',
+ 'lparlt': "\u2993",
+ 'lrarr': "\u21C6",
+ 'lrcorner': "\u231F",
+ 'lrhar': "\u21CB",
+ 'lrhard': "\u296D",
+ 'lrm': "\u200E",
+ 'lrtri': "\u22BF",
+ 'lsaquo': "\u2039",
+ 'lscr': "\uD835\uDCC1",
+ 'Lscr': "\u2112",
+ 'lsh': "\u21B0",
+ 'Lsh': "\u21B0",
+ 'lsim': "\u2272",
+ 'lsime': "\u2A8D",
+ 'lsimg': "\u2A8F",
+ 'lsqb': '[',
+ 'lsquo': "\u2018",
+ 'lsquor': "\u201A",
+ 'lstrok': "\u0142",
+ 'Lstrok': "\u0141",
+ 'lt': '<',
+ 'Lt': "\u226A",
+ 'LT': '<',
+ 'ltcc': "\u2AA6",
+ 'ltcir': "\u2A79",
+ 'ltdot': "\u22D6",
+ 'lthree': "\u22CB",
+ 'ltimes': "\u22C9",
+ 'ltlarr': "\u2976",
+ 'ltquest': "\u2A7B",
+ 'ltri': "\u25C3",
+ 'ltrie': "\u22B4",
+ 'ltrif': "\u25C2",
+ 'ltrPar': "\u2996",
+ 'lurdshar': "\u294A",
+ 'luruhar': "\u2966",
+ 'lvertneqq': "\u2268\uFE00",
+ 'lvnE': "\u2268\uFE00",
+ 'macr': '\xAF',
+ 'male': "\u2642",
+ 'malt': "\u2720",
+ 'maltese': "\u2720",
+ 'map': "\u21A6",
+ 'Map': "\u2905",
+ 'mapsto': "\u21A6",
+ 'mapstodown': "\u21A7",
+ 'mapstoleft': "\u21A4",
+ 'mapstoup': "\u21A5",
+ 'marker': "\u25AE",
+ 'mcomma': "\u2A29",
+ 'mcy': "\u043C",
+ 'Mcy': "\u041C",
+ 'mdash': "\u2014",
+ 'mDDot': "\u223A",
+ 'measuredangle': "\u2221",
+ 'MediumSpace': "\u205F",
+ 'Mellintrf': "\u2133",
+ 'mfr': "\uD835\uDD2A",
+ 'Mfr': "\uD835\uDD10",
+ 'mho': "\u2127",
+ 'micro': '\xB5',
+ 'mid': "\u2223",
+ 'midast': '*',
+ 'midcir': "\u2AF0",
+ 'middot': '\xB7',
+ 'minus': "\u2212",
+ 'minusb': "\u229F",
+ 'minusd': "\u2238",
+ 'minusdu': "\u2A2A",
+ 'MinusPlus': "\u2213",
+ 'mlcp': "\u2ADB",
+ 'mldr': "\u2026",
+ 'mnplus': "\u2213",
+ 'models': "\u22A7",
+ 'mopf': "\uD835\uDD5E",
+ 'Mopf': "\uD835\uDD44",
+ 'mp': "\u2213",
+ 'mscr': "\uD835\uDCC2",
+ 'Mscr': "\u2133",
+ 'mstpos': "\u223E",
+ 'mu': "\u03BC",
+ 'Mu': "\u039C",
+ 'multimap': "\u22B8",
+ 'mumap': "\u22B8",
+ 'nabla': "\u2207",
+ 'nacute': "\u0144",
+ 'Nacute': "\u0143",
+ 'nang': "\u2220\u20D2",
+ 'nap': "\u2249",
+ 'napE': "\u2A70\u0338",
+ 'napid': "\u224B\u0338",
+ 'napos': "\u0149",
+ 'napprox': "\u2249",
+ 'natur': "\u266E",
+ 'natural': "\u266E",
+ 'naturals': "\u2115",
+ 'nbsp': '\xA0',
+ 'nbump': "\u224E\u0338",
+ 'nbumpe': "\u224F\u0338",
+ 'ncap': "\u2A43",
+ 'ncaron': "\u0148",
+ 'Ncaron': "\u0147",
+ 'ncedil': "\u0146",
+ 'Ncedil': "\u0145",
+ 'ncong': "\u2247",
+ 'ncongdot': "\u2A6D\u0338",
+ 'ncup': "\u2A42",
+ 'ncy': "\u043D",
+ 'Ncy': "\u041D",
+ 'ndash': "\u2013",
+ 'ne': "\u2260",
+ 'nearhk': "\u2924",
+ 'nearr': "\u2197",
+ 'neArr': "\u21D7",
+ 'nearrow': "\u2197",
+ 'nedot': "\u2250\u0338",
+ 'NegativeMediumSpace': "\u200B",
+ 'NegativeThickSpace': "\u200B",
+ 'NegativeThinSpace': "\u200B",
+ 'NegativeVeryThinSpace': "\u200B",
+ 'nequiv': "\u2262",
+ 'nesear': "\u2928",
+ 'nesim': "\u2242\u0338",
+ 'NestedGreaterGreater': "\u226B",
+ 'NestedLessLess': "\u226A",
+ 'NewLine': '\n',
+ 'nexist': "\u2204",
+ 'nexists': "\u2204",
+ 'nfr': "\uD835\uDD2B",
+ 'Nfr': "\uD835\uDD11",
+ 'nge': "\u2271",
+ 'ngE': "\u2267\u0338",
+ 'ngeq': "\u2271",
+ 'ngeqq': "\u2267\u0338",
+ 'ngeqslant': "\u2A7E\u0338",
+ 'nges': "\u2A7E\u0338",
+ 'nGg': "\u22D9\u0338",
+ 'ngsim': "\u2275",
+ 'ngt': "\u226F",
+ 'nGt': "\u226B\u20D2",
+ 'ngtr': "\u226F",
+ 'nGtv': "\u226B\u0338",
+ 'nharr': "\u21AE",
+ 'nhArr': "\u21CE",
+ 'nhpar': "\u2AF2",
+ 'ni': "\u220B",
+ 'nis': "\u22FC",
+ 'nisd': "\u22FA",
+ 'niv': "\u220B",
+ 'njcy': "\u045A",
+ 'NJcy': "\u040A",
+ 'nlarr': "\u219A",
+ 'nlArr': "\u21CD",
+ 'nldr': "\u2025",
+ 'nle': "\u2270",
+ 'nlE': "\u2266\u0338",
+ 'nleftarrow': "\u219A",
+ 'nLeftarrow': "\u21CD",
+ 'nleftrightarrow': "\u21AE",
+ 'nLeftrightarrow': "\u21CE",
+ 'nleq': "\u2270",
+ 'nleqq': "\u2266\u0338",
+ 'nleqslant': "\u2A7D\u0338",
+ 'nles': "\u2A7D\u0338",
+ 'nless': "\u226E",
+ 'nLl': "\u22D8\u0338",
+ 'nlsim': "\u2274",
+ 'nlt': "\u226E",
+ 'nLt': "\u226A\u20D2",
+ 'nltri': "\u22EA",
+ 'nltrie': "\u22EC",
+ 'nLtv': "\u226A\u0338",
+ 'nmid': "\u2224",
+ 'NoBreak': "\u2060",
+ 'NonBreakingSpace': '\xA0',
+ 'nopf': "\uD835\uDD5F",
+ 'Nopf': "\u2115",
+ 'not': '\xAC',
+ 'Not': "\u2AEC",
+ 'NotCongruent': "\u2262",
+ 'NotCupCap': "\u226D",
+ 'NotDoubleVerticalBar': "\u2226",
+ 'NotElement': "\u2209",
+ 'NotEqual': "\u2260",
+ 'NotEqualTilde': "\u2242\u0338",
+ 'NotExists': "\u2204",
+ 'NotGreater': "\u226F",
+ 'NotGreaterEqual': "\u2271",
+ 'NotGreaterFullEqual': "\u2267\u0338",
+ 'NotGreaterGreater': "\u226B\u0338",
+ 'NotGreaterLess': "\u2279",
+ 'NotGreaterSlantEqual': "\u2A7E\u0338",
+ 'NotGreaterTilde': "\u2275",
+ 'NotHumpDownHump': "\u224E\u0338",
+ 'NotHumpEqual': "\u224F\u0338",
+ 'notin': "\u2209",
+ 'notindot': "\u22F5\u0338",
+ 'notinE': "\u22F9\u0338",
+ 'notinva': "\u2209",
+ 'notinvb': "\u22F7",
+ 'notinvc': "\u22F6",
+ 'NotLeftTriangle': "\u22EA",
+ 'NotLeftTriangleBar': "\u29CF\u0338",
+ 'NotLeftTriangleEqual': "\u22EC",
+ 'NotLess': "\u226E",
+ 'NotLessEqual': "\u2270",
+ 'NotLessGreater': "\u2278",
+ 'NotLessLess': "\u226A\u0338",
+ 'NotLessSlantEqual': "\u2A7D\u0338",
+ 'NotLessTilde': "\u2274",
+ 'NotNestedGreaterGreater': "\u2AA2\u0338",
+ 'NotNestedLessLess': "\u2AA1\u0338",
+ 'notni': "\u220C",
+ 'notniva': "\u220C",
+ 'notnivb': "\u22FE",
+ 'notnivc': "\u22FD",
+ 'NotPrecedes': "\u2280",
+ 'NotPrecedesEqual': "\u2AAF\u0338",
+ 'NotPrecedesSlantEqual': "\u22E0",
+ 'NotReverseElement': "\u220C",
+ 'NotRightTriangle': "\u22EB",
+ 'NotRightTriangleBar': "\u29D0\u0338",
+ 'NotRightTriangleEqual': "\u22ED",
+ 'NotSquareSubset': "\u228F\u0338",
+ 'NotSquareSubsetEqual': "\u22E2",
+ 'NotSquareSuperset': "\u2290\u0338",
+ 'NotSquareSupersetEqual': "\u22E3",
+ 'NotSubset': "\u2282\u20D2",
+ 'NotSubsetEqual': "\u2288",
+ 'NotSucceeds': "\u2281",
+ 'NotSucceedsEqual': "\u2AB0\u0338",
+ 'NotSucceedsSlantEqual': "\u22E1",
+ 'NotSucceedsTilde': "\u227F\u0338",
+ 'NotSuperset': "\u2283\u20D2",
+ 'NotSupersetEqual': "\u2289",
+ 'NotTilde': "\u2241",
+ 'NotTildeEqual': "\u2244",
+ 'NotTildeFullEqual': "\u2247",
+ 'NotTildeTilde': "\u2249",
+ 'NotVerticalBar': "\u2224",
+ 'npar': "\u2226",
+ 'nparallel': "\u2226",
+ 'nparsl': "\u2AFD\u20E5",
+ 'npart': "\u2202\u0338",
+ 'npolint': "\u2A14",
+ 'npr': "\u2280",
+ 'nprcue': "\u22E0",
+ 'npre': "\u2AAF\u0338",
+ 'nprec': "\u2280",
+ 'npreceq': "\u2AAF\u0338",
+ 'nrarr': "\u219B",
+ 'nrArr': "\u21CF",
+ 'nrarrc': "\u2933\u0338",
+ 'nrarrw': "\u219D\u0338",
+ 'nrightarrow': "\u219B",
+ 'nRightarrow': "\u21CF",
+ 'nrtri': "\u22EB",
+ 'nrtrie': "\u22ED",
+ 'nsc': "\u2281",
+ 'nsccue': "\u22E1",
+ 'nsce': "\u2AB0\u0338",
+ 'nscr': "\uD835\uDCC3",
+ 'Nscr': "\uD835\uDCA9",
+ 'nshortmid': "\u2224",
+ 'nshortparallel': "\u2226",
+ 'nsim': "\u2241",
+ 'nsime': "\u2244",
+ 'nsimeq': "\u2244",
+ 'nsmid': "\u2224",
+ 'nspar': "\u2226",
+ 'nsqsube': "\u22E2",
+ 'nsqsupe': "\u22E3",
+ 'nsub': "\u2284",
+ 'nsube': "\u2288",
+ 'nsubE': "\u2AC5\u0338",
+ 'nsubset': "\u2282\u20D2",
+ 'nsubseteq': "\u2288",
+ 'nsubseteqq': "\u2AC5\u0338",
+ 'nsucc': "\u2281",
+ 'nsucceq': "\u2AB0\u0338",
+ 'nsup': "\u2285",
+ 'nsupe': "\u2289",
+ 'nsupE': "\u2AC6\u0338",
+ 'nsupset': "\u2283\u20D2",
+ 'nsupseteq': "\u2289",
+ 'nsupseteqq': "\u2AC6\u0338",
+ 'ntgl': "\u2279",
+ 'ntilde': '\xF1',
+ 'Ntilde': '\xD1',
+ 'ntlg': "\u2278",
+ 'ntriangleleft': "\u22EA",
+ 'ntrianglelefteq': "\u22EC",
+ 'ntriangleright': "\u22EB",
+ 'ntrianglerighteq': "\u22ED",
+ 'nu': "\u03BD",
+ 'Nu': "\u039D",
+ 'num': '#',
+ 'numero': "\u2116",
+ 'numsp': "\u2007",
+ 'nvap': "\u224D\u20D2",
+ 'nvdash': "\u22AC",
+ 'nvDash': "\u22AD",
+ 'nVdash': "\u22AE",
+ 'nVDash': "\u22AF",
+ 'nvge': "\u2265\u20D2",
+ 'nvgt': ">\u20D2",
+ 'nvHarr': "\u2904",
+ 'nvinfin': "\u29DE",
+ 'nvlArr': "\u2902",
+ 'nvle': "\u2264\u20D2",
+ 'nvlt': "<\u20D2",
+ 'nvltrie': "\u22B4\u20D2",
+ 'nvrArr': "\u2903",
+ 'nvrtrie': "\u22B5\u20D2",
+ 'nvsim': "\u223C\u20D2",
+ 'nwarhk': "\u2923",
+ 'nwarr': "\u2196",
+ 'nwArr': "\u21D6",
+ 'nwarrow': "\u2196",
+ 'nwnear': "\u2927",
+ 'oacute': '\xF3',
+ 'Oacute': '\xD3',
+ 'oast': "\u229B",
+ 'ocir': "\u229A",
+ 'ocirc': '\xF4',
+ 'Ocirc': '\xD4',
+ 'ocy': "\u043E",
+ 'Ocy': "\u041E",
+ 'odash': "\u229D",
+ 'odblac': "\u0151",
+ 'Odblac': "\u0150",
+ 'odiv': "\u2A38",
+ 'odot': "\u2299",
+ 'odsold': "\u29BC",
+ 'oelig': "\u0153",
+ 'OElig': "\u0152",
+ 'ofcir': "\u29BF",
+ 'ofr': "\uD835\uDD2C",
+ 'Ofr': "\uD835\uDD12",
+ 'ogon': "\u02DB",
+ 'ograve': '\xF2',
+ 'Ograve': '\xD2',
+ 'ogt': "\u29C1",
+ 'ohbar': "\u29B5",
+ 'ohm': "\u03A9",
+ 'oint': "\u222E",
+ 'olarr': "\u21BA",
+ 'olcir': "\u29BE",
+ 'olcross': "\u29BB",
+ 'oline': "\u203E",
+ 'olt': "\u29C0",
+ 'omacr': "\u014D",
+ 'Omacr': "\u014C",
+ 'omega': "\u03C9",
+ 'Omega': "\u03A9",
+ 'omicron': "\u03BF",
+ 'Omicron': "\u039F",
+ 'omid': "\u29B6",
+ 'ominus': "\u2296",
+ 'oopf': "\uD835\uDD60",
+ 'Oopf': "\uD835\uDD46",
+ 'opar': "\u29B7",
+ 'OpenCurlyDoubleQuote': "\u201C",
+ 'OpenCurlyQuote': "\u2018",
+ 'operp': "\u29B9",
+ 'oplus': "\u2295",
+ 'or': "\u2228",
+ 'Or': "\u2A54",
+ 'orarr': "\u21BB",
+ 'ord': "\u2A5D",
+ 'order': "\u2134",
+ 'orderof': "\u2134",
+ 'ordf': '\xAA',
+ 'ordm': '\xBA',
+ 'origof': "\u22B6",
+ 'oror': "\u2A56",
+ 'orslope': "\u2A57",
+ 'orv': "\u2A5B",
+ 'oS': "\u24C8",
+ 'oscr': "\u2134",
+ 'Oscr': "\uD835\uDCAA",
+ 'oslash': '\xF8',
+ 'Oslash': '\xD8',
+ 'osol': "\u2298",
+ 'otilde': '\xF5',
+ 'Otilde': '\xD5',
+ 'otimes': "\u2297",
+ 'Otimes': "\u2A37",
+ 'otimesas': "\u2A36",
+ 'ouml': '\xF6',
+ 'Ouml': '\xD6',
+ 'ovbar': "\u233D",
+ 'OverBar': "\u203E",
+ 'OverBrace': "\u23DE",
+ 'OverBracket': "\u23B4",
+ 'OverParenthesis': "\u23DC",
+ 'par': "\u2225",
+ 'para': '\xB6',
+ 'parallel': "\u2225",
+ 'parsim': "\u2AF3",
+ 'parsl': "\u2AFD",
+ 'part': "\u2202",
+ 'PartialD': "\u2202",
+ 'pcy': "\u043F",
+ 'Pcy': "\u041F",
+ 'percnt': '%',
+ 'period': '.',
+ 'permil': "\u2030",
+ 'perp': "\u22A5",
+ 'pertenk': "\u2031",
+ 'pfr': "\uD835\uDD2D",
+ 'Pfr': "\uD835\uDD13",
+ 'phi': "\u03C6",
+ 'Phi': "\u03A6",
+ 'phiv': "\u03D5",
+ 'phmmat': "\u2133",
+ 'phone': "\u260E",
+ 'pi': "\u03C0",
+ 'Pi': "\u03A0",
+ 'pitchfork': "\u22D4",
+ 'piv': "\u03D6",
+ 'planck': "\u210F",
+ 'planckh': "\u210E",
+ 'plankv': "\u210F",
+ 'plus': '+',
+ 'plusacir': "\u2A23",
+ 'plusb': "\u229E",
+ 'pluscir': "\u2A22",
+ 'plusdo': "\u2214",
+ 'plusdu': "\u2A25",
+ 'pluse': "\u2A72",
+ 'PlusMinus': '\xB1',
+ 'plusmn': '\xB1',
+ 'plussim': "\u2A26",
+ 'plustwo': "\u2A27",
+ 'pm': '\xB1',
+ 'Poincareplane': "\u210C",
+ 'pointint': "\u2A15",
+ 'popf': "\uD835\uDD61",
+ 'Popf': "\u2119",
+ 'pound': '\xA3',
+ 'pr': "\u227A",
+ 'Pr': "\u2ABB",
+ 'prap': "\u2AB7",
+ 'prcue': "\u227C",
+ 'pre': "\u2AAF",
+ 'prE': "\u2AB3",
+ 'prec': "\u227A",
+ 'precapprox': "\u2AB7",
+ 'preccurlyeq': "\u227C",
+ 'Precedes': "\u227A",
+ 'PrecedesEqual': "\u2AAF",
+ 'PrecedesSlantEqual': "\u227C",
+ 'PrecedesTilde': "\u227E",
+ 'preceq': "\u2AAF",
+ 'precnapprox': "\u2AB9",
+ 'precneqq': "\u2AB5",
+ 'precnsim': "\u22E8",
+ 'precsim': "\u227E",
+ 'prime': "\u2032",
+ 'Prime': "\u2033",
+ 'primes': "\u2119",
+ 'prnap': "\u2AB9",
+ 'prnE': "\u2AB5",
+ 'prnsim': "\u22E8",
+ 'prod': "\u220F",
+ 'Product': "\u220F",
+ 'profalar': "\u232E",
+ 'profline': "\u2312",
+ 'profsurf': "\u2313",
+ 'prop': "\u221D",
+ 'Proportion': "\u2237",
+ 'Proportional': "\u221D",
+ 'propto': "\u221D",
+ 'prsim': "\u227E",
+ 'prurel': "\u22B0",
+ 'pscr': "\uD835\uDCC5",
+ 'Pscr': "\uD835\uDCAB",
+ 'psi': "\u03C8",
+ 'Psi': "\u03A8",
+ 'puncsp': "\u2008",
+ 'qfr': "\uD835\uDD2E",
+ 'Qfr': "\uD835\uDD14",
+ 'qint': "\u2A0C",
+ 'qopf': "\uD835\uDD62",
+ 'Qopf': "\u211A",
+ 'qprime': "\u2057",
+ 'qscr': "\uD835\uDCC6",
+ 'Qscr': "\uD835\uDCAC",
+ 'quaternions': "\u210D",
+ 'quatint': "\u2A16",
+ 'quest': '?',
+ 'questeq': "\u225F",
+ 'quot': '"',
+ 'QUOT': '"',
+ 'rAarr': "\u21DB",
+ 'race': "\u223D\u0331",
+ 'racute': "\u0155",
+ 'Racute': "\u0154",
+ 'radic': "\u221A",
+ 'raemptyv': "\u29B3",
+ 'rang': "\u27E9",
+ 'Rang': "\u27EB",
+ 'rangd': "\u2992",
+ 'range': "\u29A5",
+ 'rangle': "\u27E9",
+ 'raquo': '\xBB',
+ 'rarr': "\u2192",
+ 'rArr': "\u21D2",
+ 'Rarr': "\u21A0",
+ 'rarrap': "\u2975",
+ 'rarrb': "\u21E5",
+ 'rarrbfs': "\u2920",
+ 'rarrc': "\u2933",
+ 'rarrfs': "\u291E",
+ 'rarrhk': "\u21AA",
+ 'rarrlp': "\u21AC",
+ 'rarrpl': "\u2945",
+ 'rarrsim': "\u2974",
+ 'rarrtl': "\u21A3",
+ 'Rarrtl': "\u2916",
+ 'rarrw': "\u219D",
+ 'ratail': "\u291A",
+ 'rAtail': "\u291C",
+ 'ratio': "\u2236",
+ 'rationals': "\u211A",
+ 'rbarr': "\u290D",
+ 'rBarr': "\u290F",
+ 'RBarr': "\u2910",
+ 'rbbrk': "\u2773",
+ 'rbrace': '}',
+ 'rbrack': ']',
+ 'rbrke': "\u298C",
+ 'rbrksld': "\u298E",
+ 'rbrkslu': "\u2990",
+ 'rcaron': "\u0159",
+ 'Rcaron': "\u0158",
+ 'rcedil': "\u0157",
+ 'Rcedil': "\u0156",
+ 'rceil': "\u2309",
+ 'rcub': '}',
+ 'rcy': "\u0440",
+ 'Rcy': "\u0420",
+ 'rdca': "\u2937",
+ 'rdldhar': "\u2969",
+ 'rdquo': "\u201D",
+ 'rdquor': "\u201D",
+ 'rdsh': "\u21B3",
+ 'Re': "\u211C",
+ 'real': "\u211C",
+ 'realine': "\u211B",
+ 'realpart': "\u211C",
+ 'reals': "\u211D",
+ 'rect': "\u25AD",
+ 'reg': '\xAE',
+ 'REG': '\xAE',
+ 'ReverseElement': "\u220B",
+ 'ReverseEquilibrium': "\u21CB",
+ 'ReverseUpEquilibrium': "\u296F",
+ 'rfisht': "\u297D",
+ 'rfloor': "\u230B",
+ 'rfr': "\uD835\uDD2F",
+ 'Rfr': "\u211C",
+ 'rHar': "\u2964",
+ 'rhard': "\u21C1",
+ 'rharu': "\u21C0",
+ 'rharul': "\u296C",
+ 'rho': "\u03C1",
+ 'Rho': "\u03A1",
+ 'rhov': "\u03F1",
+ 'RightAngleBracket': "\u27E9",
+ 'rightarrow': "\u2192",
+ 'Rightarrow': "\u21D2",
+ 'RightArrow': "\u2192",
+ 'RightArrowBar': "\u21E5",
+ 'RightArrowLeftArrow': "\u21C4",
+ 'rightarrowtail': "\u21A3",
+ 'RightCeiling': "\u2309",
+ 'RightDoubleBracket': "\u27E7",
+ 'RightDownTeeVector': "\u295D",
+ 'RightDownVector': "\u21C2",
+ 'RightDownVectorBar': "\u2955",
+ 'RightFloor': "\u230B",
+ 'rightharpoondown': "\u21C1",
+ 'rightharpoonup': "\u21C0",
+ 'rightleftarrows': "\u21C4",
+ 'rightleftharpoons': "\u21CC",
+ 'rightrightarrows': "\u21C9",
+ 'rightsquigarrow': "\u219D",
+ 'RightTee': "\u22A2",
+ 'RightTeeArrow': "\u21A6",
+ 'RightTeeVector': "\u295B",
+ 'rightthreetimes': "\u22CC",
+ 'RightTriangle': "\u22B3",
+ 'RightTriangleBar': "\u29D0",
+ 'RightTriangleEqual': "\u22B5",
+ 'RightUpDownVector': "\u294F",
+ 'RightUpTeeVector': "\u295C",
+ 'RightUpVector': "\u21BE",
+ 'RightUpVectorBar': "\u2954",
+ 'RightVector': "\u21C0",
+ 'RightVectorBar': "\u2953",
+ 'ring': "\u02DA",
+ 'risingdotseq': "\u2253",
+ 'rlarr': "\u21C4",
+ 'rlhar': "\u21CC",
+ 'rlm': "\u200F",
+ 'rmoust': "\u23B1",
+ 'rmoustache': "\u23B1",
+ 'rnmid': "\u2AEE",
+ 'roang': "\u27ED",
+ 'roarr': "\u21FE",
+ 'robrk': "\u27E7",
+ 'ropar': "\u2986",
+ 'ropf': "\uD835\uDD63",
+ 'Ropf': "\u211D",
+ 'roplus': "\u2A2E",
+ 'rotimes': "\u2A35",
+ 'RoundImplies': "\u2970",
+ 'rpar': ')',
+ 'rpargt': "\u2994",
+ 'rppolint': "\u2A12",
+ 'rrarr': "\u21C9",
+ 'Rrightarrow': "\u21DB",
+ 'rsaquo': "\u203A",
+ 'rscr': "\uD835\uDCC7",
+ 'Rscr': "\u211B",
+ 'rsh': "\u21B1",
+ 'Rsh': "\u21B1",
+ 'rsqb': ']',
+ 'rsquo': "\u2019",
+ 'rsquor': "\u2019",
+ 'rthree': "\u22CC",
+ 'rtimes': "\u22CA",
+ 'rtri': "\u25B9",
+ 'rtrie': "\u22B5",
+ 'rtrif': "\u25B8",
+ 'rtriltri': "\u29CE",
+ 'RuleDelayed': "\u29F4",
+ 'ruluhar': "\u2968",
+ 'rx': "\u211E",
+ 'sacute': "\u015B",
+ 'Sacute': "\u015A",
+ 'sbquo': "\u201A",
+ 'sc': "\u227B",
+ 'Sc': "\u2ABC",
+ 'scap': "\u2AB8",
+ 'scaron': "\u0161",
+ 'Scaron': "\u0160",
+ 'sccue': "\u227D",
+ 'sce': "\u2AB0",
+ 'scE': "\u2AB4",
+ 'scedil': "\u015F",
+ 'Scedil': "\u015E",
+ 'scirc': "\u015D",
+ 'Scirc': "\u015C",
+ 'scnap': "\u2ABA",
+ 'scnE': "\u2AB6",
+ 'scnsim': "\u22E9",
+ 'scpolint': "\u2A13",
+ 'scsim': "\u227F",
+ 'scy': "\u0441",
+ 'Scy': "\u0421",
+ 'sdot': "\u22C5",
+ 'sdotb': "\u22A1",
+ 'sdote': "\u2A66",
+ 'searhk': "\u2925",
+ 'searr': "\u2198",
+ 'seArr': "\u21D8",
+ 'searrow': "\u2198",
+ 'sect': '\xA7',
+ 'semi': ';',
+ 'seswar': "\u2929",
+ 'setminus': "\u2216",
+ 'setmn': "\u2216",
+ 'sext': "\u2736",
+ 'sfr': "\uD835\uDD30",
+ 'Sfr': "\uD835\uDD16",
+ 'sfrown': "\u2322",
+ 'sharp': "\u266F",
+ 'shchcy': "\u0449",
+ 'SHCHcy': "\u0429",
+ 'shcy': "\u0448",
+ 'SHcy': "\u0428",
+ 'ShortDownArrow': "\u2193",
+ 'ShortLeftArrow': "\u2190",
+ 'shortmid': "\u2223",
+ 'shortparallel': "\u2225",
+ 'ShortRightArrow': "\u2192",
+ 'ShortUpArrow': "\u2191",
+ 'shy': '\xAD',
+ 'sigma': "\u03C3",
+ 'Sigma': "\u03A3",
+ 'sigmaf': "\u03C2",
+ 'sigmav': "\u03C2",
+ 'sim': "\u223C",
+ 'simdot': "\u2A6A",
+ 'sime': "\u2243",
+ 'simeq': "\u2243",
+ 'simg': "\u2A9E",
+ 'simgE': "\u2AA0",
+ 'siml': "\u2A9D",
+ 'simlE': "\u2A9F",
+ 'simne': "\u2246",
+ 'simplus': "\u2A24",
+ 'simrarr': "\u2972",
+ 'slarr': "\u2190",
+ 'SmallCircle': "\u2218",
+ 'smallsetminus': "\u2216",
+ 'smashp': "\u2A33",
+ 'smeparsl': "\u29E4",
+ 'smid': "\u2223",
+ 'smile': "\u2323",
+ 'smt': "\u2AAA",
+ 'smte': "\u2AAC",
+ 'smtes': "\u2AAC\uFE00",
+ 'softcy': "\u044C",
+ 'SOFTcy': "\u042C",
+ 'sol': '/',
+ 'solb': "\u29C4",
+ 'solbar': "\u233F",
+ 'sopf': "\uD835\uDD64",
+ 'Sopf': "\uD835\uDD4A",
+ 'spades': "\u2660",
+ 'spadesuit': "\u2660",
+ 'spar': "\u2225",
+ 'sqcap': "\u2293",
+ 'sqcaps': "\u2293\uFE00",
+ 'sqcup': "\u2294",
+ 'sqcups': "\u2294\uFE00",
+ 'Sqrt': "\u221A",
+ 'sqsub': "\u228F",
+ 'sqsube': "\u2291",
+ 'sqsubset': "\u228F",
+ 'sqsubseteq': "\u2291",
+ 'sqsup': "\u2290",
+ 'sqsupe': "\u2292",
+ 'sqsupset': "\u2290",
+ 'sqsupseteq': "\u2292",
+ 'squ': "\u25A1",
+ 'square': "\u25A1",
+ 'Square': "\u25A1",
+ 'SquareIntersection': "\u2293",
+ 'SquareSubset': "\u228F",
+ 'SquareSubsetEqual': "\u2291",
+ 'SquareSuperset': "\u2290",
+ 'SquareSupersetEqual': "\u2292",
+ 'SquareUnion': "\u2294",
+ 'squarf': "\u25AA",
+ 'squf': "\u25AA",
+ 'srarr': "\u2192",
+ 'sscr': "\uD835\uDCC8",
+ 'Sscr': "\uD835\uDCAE",
+ 'ssetmn': "\u2216",
+ 'ssmile': "\u2323",
+ 'sstarf': "\u22C6",
+ 'star': "\u2606",
+ 'Star': "\u22C6",
+ 'starf': "\u2605",
+ 'straightepsilon': "\u03F5",
+ 'straightphi': "\u03D5",
+ 'strns': '\xAF',
+ 'sub': "\u2282",
+ 'Sub': "\u22D0",
+ 'subdot': "\u2ABD",
+ 'sube': "\u2286",
+ 'subE': "\u2AC5",
+ 'subedot': "\u2AC3",
+ 'submult': "\u2AC1",
+ 'subne': "\u228A",
+ 'subnE': "\u2ACB",
+ 'subplus': "\u2ABF",
+ 'subrarr': "\u2979",
+ 'subset': "\u2282",
+ 'Subset': "\u22D0",
+ 'subseteq': "\u2286",
+ 'subseteqq': "\u2AC5",
+ 'SubsetEqual': "\u2286",
+ 'subsetneq': "\u228A",
+ 'subsetneqq': "\u2ACB",
+ 'subsim': "\u2AC7",
+ 'subsub': "\u2AD5",
+ 'subsup': "\u2AD3",
+ 'succ': "\u227B",
+ 'succapprox': "\u2AB8",
+ 'succcurlyeq': "\u227D",
+ 'Succeeds': "\u227B",
+ 'SucceedsEqual': "\u2AB0",
+ 'SucceedsSlantEqual': "\u227D",
+ 'SucceedsTilde': "\u227F",
+ 'succeq': "\u2AB0",
+ 'succnapprox': "\u2ABA",
+ 'succneqq': "\u2AB6",
+ 'succnsim': "\u22E9",
+ 'succsim': "\u227F",
+ 'SuchThat': "\u220B",
+ 'sum': "\u2211",
+ 'Sum': "\u2211",
+ 'sung': "\u266A",
+ 'sup': "\u2283",
+ 'Sup': "\u22D1",
+ 'sup1': '\xB9',
+ 'sup2': '\xB2',
+ 'sup3': '\xB3',
+ 'supdot': "\u2ABE",
+ 'supdsub': "\u2AD8",
+ 'supe': "\u2287",
+ 'supE': "\u2AC6",
+ 'supedot': "\u2AC4",
+ 'Superset': "\u2283",
+ 'SupersetEqual': "\u2287",
+ 'suphsol': "\u27C9",
+ 'suphsub': "\u2AD7",
+ 'suplarr': "\u297B",
+ 'supmult': "\u2AC2",
+ 'supne': "\u228B",
+ 'supnE': "\u2ACC",
+ 'supplus': "\u2AC0",
+ 'supset': "\u2283",
+ 'Supset': "\u22D1",
+ 'supseteq': "\u2287",
+ 'supseteqq': "\u2AC6",
+ 'supsetneq': "\u228B",
+ 'supsetneqq': "\u2ACC",
+ 'supsim': "\u2AC8",
+ 'supsub': "\u2AD4",
+ 'supsup': "\u2AD6",
+ 'swarhk': "\u2926",
+ 'swarr': "\u2199",
+ 'swArr': "\u21D9",
+ 'swarrow': "\u2199",
+ 'swnwar': "\u292A",
+ 'szlig': '\xDF',
+ 'Tab': '\t',
+ 'target': "\u2316",
+ 'tau': "\u03C4",
+ 'Tau': "\u03A4",
+ 'tbrk': "\u23B4",
+ 'tcaron': "\u0165",
+ 'Tcaron': "\u0164",
+ 'tcedil': "\u0163",
+ 'Tcedil': "\u0162",
+ 'tcy': "\u0442",
+ 'Tcy': "\u0422",
+ 'tdot': "\u20DB",
+ 'telrec': "\u2315",
+ 'tfr': "\uD835\uDD31",
+ 'Tfr': "\uD835\uDD17",
+ 'there4': "\u2234",
+ 'therefore': "\u2234",
+ 'Therefore': "\u2234",
+ 'theta': "\u03B8",
+ 'Theta': "\u0398",
+ 'thetasym': "\u03D1",
+ 'thetav': "\u03D1",
+ 'thickapprox': "\u2248",
+ 'thicksim': "\u223C",
+ 'ThickSpace': "\u205F\u200A",
+ 'thinsp': "\u2009",
+ 'ThinSpace': "\u2009",
+ 'thkap': "\u2248",
+ 'thksim': "\u223C",
+ 'thorn': '\xFE',
+ 'THORN': '\xDE',
+ 'tilde': "\u02DC",
+ 'Tilde': "\u223C",
+ 'TildeEqual': "\u2243",
+ 'TildeFullEqual': "\u2245",
+ 'TildeTilde': "\u2248",
+ 'times': '\xD7',
+ 'timesb': "\u22A0",
+ 'timesbar': "\u2A31",
+ 'timesd': "\u2A30",
+ 'tint': "\u222D",
+ 'toea': "\u2928",
+ 'top': "\u22A4",
+ 'topbot': "\u2336",
+ 'topcir': "\u2AF1",
+ 'topf': "\uD835\uDD65",
+ 'Topf': "\uD835\uDD4B",
+ 'topfork': "\u2ADA",
+ 'tosa': "\u2929",
+ 'tprime': "\u2034",
+ 'trade': "\u2122",
+ 'TRADE': "\u2122",
+ 'triangle': "\u25B5",
+ 'triangledown': "\u25BF",
+ 'triangleleft': "\u25C3",
+ 'trianglelefteq': "\u22B4",
+ 'triangleq': "\u225C",
+ 'triangleright': "\u25B9",
+ 'trianglerighteq': "\u22B5",
+ 'tridot': "\u25EC",
+ 'trie': "\u225C",
+ 'triminus': "\u2A3A",
+ 'TripleDot': "\u20DB",
+ 'triplus': "\u2A39",
+ 'trisb': "\u29CD",
+ 'tritime': "\u2A3B",
+ 'trpezium': "\u23E2",
+ 'tscr': "\uD835\uDCC9",
+ 'Tscr': "\uD835\uDCAF",
+ 'tscy': "\u0446",
+ 'TScy': "\u0426",
+ 'tshcy': "\u045B",
+ 'TSHcy': "\u040B",
+ 'tstrok': "\u0167",
+ 'Tstrok': "\u0166",
+ 'twixt': "\u226C",
+ 'twoheadleftarrow': "\u219E",
+ 'twoheadrightarrow': "\u21A0",
+ 'uacute': '\xFA',
+ 'Uacute': '\xDA',
+ 'uarr': "\u2191",
+ 'uArr': "\u21D1",
+ 'Uarr': "\u219F",
+ 'Uarrocir': "\u2949",
+ 'ubrcy': "\u045E",
+ 'Ubrcy': "\u040E",
+ 'ubreve': "\u016D",
+ 'Ubreve': "\u016C",
+ 'ucirc': '\xFB',
+ 'Ucirc': '\xDB',
+ 'ucy': "\u0443",
+ 'Ucy': "\u0423",
+ 'udarr': "\u21C5",
+ 'udblac': "\u0171",
+ 'Udblac': "\u0170",
+ 'udhar': "\u296E",
+ 'ufisht': "\u297E",
+ 'ufr': "\uD835\uDD32",
+ 'Ufr': "\uD835\uDD18",
+ 'ugrave': '\xF9',
+ 'Ugrave': '\xD9',
+ 'uHar': "\u2963",
+ 'uharl': "\u21BF",
+ 'uharr': "\u21BE",
+ 'uhblk': "\u2580",
+ 'ulcorn': "\u231C",
+ 'ulcorner': "\u231C",
+ 'ulcrop': "\u230F",
+ 'ultri': "\u25F8",
+ 'umacr': "\u016B",
+ 'Umacr': "\u016A",
+ 'uml': '\xA8',
+ 'UnderBar': '_',
+ 'UnderBrace': "\u23DF",
+ 'UnderBracket': "\u23B5",
+ 'UnderParenthesis': "\u23DD",
+ 'Union': "\u22C3",
+ 'UnionPlus': "\u228E",
+ 'uogon': "\u0173",
+ 'Uogon': "\u0172",
+ 'uopf': "\uD835\uDD66",
+ 'Uopf': "\uD835\uDD4C",
+ 'uparrow': "\u2191",
+ 'Uparrow': "\u21D1",
+ 'UpArrow': "\u2191",
+ 'UpArrowBar': "\u2912",
+ 'UpArrowDownArrow': "\u21C5",
+ 'updownarrow': "\u2195",
+ 'Updownarrow': "\u21D5",
+ 'UpDownArrow': "\u2195",
+ 'UpEquilibrium': "\u296E",
+ 'upharpoonleft': "\u21BF",
+ 'upharpoonright': "\u21BE",
+ 'uplus': "\u228E",
+ 'UpperLeftArrow': "\u2196",
+ 'UpperRightArrow': "\u2197",
+ 'upsi': "\u03C5",
+ 'Upsi': "\u03D2",
+ 'upsih': "\u03D2",
+ 'upsilon': "\u03C5",
+ 'Upsilon': "\u03A5",
+ 'UpTee': "\u22A5",
+ 'UpTeeArrow': "\u21A5",
+ 'upuparrows': "\u21C8",
+ 'urcorn': "\u231D",
+ 'urcorner': "\u231D",
+ 'urcrop': "\u230E",
+ 'uring': "\u016F",
+ 'Uring': "\u016E",
+ 'urtri': "\u25F9",
+ 'uscr': "\uD835\uDCCA",
+ 'Uscr': "\uD835\uDCB0",
+ 'utdot': "\u22F0",
+ 'utilde': "\u0169",
+ 'Utilde': "\u0168",
+ 'utri': "\u25B5",
+ 'utrif': "\u25B4",
+ 'uuarr': "\u21C8",
+ 'uuml': '\xFC',
+ 'Uuml': '\xDC',
+ 'uwangle': "\u29A7",
+ 'vangrt': "\u299C",
+ 'varepsilon': "\u03F5",
+ 'varkappa': "\u03F0",
+ 'varnothing': "\u2205",
+ 'varphi': "\u03D5",
+ 'varpi': "\u03D6",
+ 'varpropto': "\u221D",
+ 'varr': "\u2195",
+ 'vArr': "\u21D5",
+ 'varrho': "\u03F1",
+ 'varsigma': "\u03C2",
+ 'varsubsetneq': "\u228A\uFE00",
+ 'varsubsetneqq': "\u2ACB\uFE00",
+ 'varsupsetneq': "\u228B\uFE00",
+ 'varsupsetneqq': "\u2ACC\uFE00",
+ 'vartheta': "\u03D1",
+ 'vartriangleleft': "\u22B2",
+ 'vartriangleright': "\u22B3",
+ 'vBar': "\u2AE8",
+ 'Vbar': "\u2AEB",
+ 'vBarv': "\u2AE9",
+ 'vcy': "\u0432",
+ 'Vcy': "\u0412",
+ 'vdash': "\u22A2",
+ 'vDash': "\u22A8",
+ 'Vdash': "\u22A9",
+ 'VDash': "\u22AB",
+ 'Vdashl': "\u2AE6",
+ 'vee': "\u2228",
+ 'Vee': "\u22C1",
+ 'veebar': "\u22BB",
+ 'veeeq': "\u225A",
+ 'vellip': "\u22EE",
+ 'verbar': '|',
+ 'Verbar': "\u2016",
+ 'vert': '|',
+ 'Vert': "\u2016",
+ 'VerticalBar': "\u2223",
+ 'VerticalLine': '|',
+ 'VerticalSeparator': "\u2758",
+ 'VerticalTilde': "\u2240",
+ 'VeryThinSpace': "\u200A",
+ 'vfr': "\uD835\uDD33",
+ 'Vfr': "\uD835\uDD19",
+ 'vltri': "\u22B2",
+ 'vnsub': "\u2282\u20D2",
+ 'vnsup': "\u2283\u20D2",
+ 'vopf': "\uD835\uDD67",
+ 'Vopf': "\uD835\uDD4D",
+ 'vprop': "\u221D",
+ 'vrtri': "\u22B3",
+ 'vscr': "\uD835\uDCCB",
+ 'Vscr': "\uD835\uDCB1",
+ 'vsubne': "\u228A\uFE00",
+ 'vsubnE': "\u2ACB\uFE00",
+ 'vsupne': "\u228B\uFE00",
+ 'vsupnE': "\u2ACC\uFE00",
+ 'Vvdash': "\u22AA",
+ 'vzigzag': "\u299A",
+ 'wcirc': "\u0175",
+ 'Wcirc': "\u0174",
+ 'wedbar': "\u2A5F",
+ 'wedge': "\u2227",
+ 'Wedge': "\u22C0",
+ 'wedgeq': "\u2259",
+ 'weierp': "\u2118",
+ 'wfr': "\uD835\uDD34",
+ 'Wfr': "\uD835\uDD1A",
+ 'wopf': "\uD835\uDD68",
+ 'Wopf': "\uD835\uDD4E",
+ 'wp': "\u2118",
+ 'wr': "\u2240",
+ 'wreath': "\u2240",
+ 'wscr': "\uD835\uDCCC",
+ 'Wscr': "\uD835\uDCB2",
+ 'xcap': "\u22C2",
+ 'xcirc': "\u25EF",
+ 'xcup': "\u22C3",
+ 'xdtri': "\u25BD",
+ 'xfr': "\uD835\uDD35",
+ 'Xfr': "\uD835\uDD1B",
+ 'xharr': "\u27F7",
+ 'xhArr': "\u27FA",
+ 'xi': "\u03BE",
+ 'Xi': "\u039E",
+ 'xlarr': "\u27F5",
+ 'xlArr': "\u27F8",
+ 'xmap': "\u27FC",
+ 'xnis': "\u22FB",
+ 'xodot': "\u2A00",
+ 'xopf': "\uD835\uDD69",
+ 'Xopf': "\uD835\uDD4F",
+ 'xoplus': "\u2A01",
+ 'xotime': "\u2A02",
+ 'xrarr': "\u27F6",
+ 'xrArr': "\u27F9",
+ 'xscr': "\uD835\uDCCD",
+ 'Xscr': "\uD835\uDCB3",
+ 'xsqcup': "\u2A06",
+ 'xuplus': "\u2A04",
+ 'xutri': "\u25B3",
+ 'xvee': "\u22C1",
+ 'xwedge': "\u22C0",
+ 'yacute': '\xFD',
+ 'Yacute': '\xDD',
+ 'yacy': "\u044F",
+ 'YAcy': "\u042F",
+ 'ycirc': "\u0177",
+ 'Ycirc': "\u0176",
+ 'ycy': "\u044B",
+ 'Ycy': "\u042B",
+ 'yen': '\xA5',
+ 'yfr': "\uD835\uDD36",
+ 'Yfr': "\uD835\uDD1C",
+ 'yicy': "\u0457",
+ 'YIcy': "\u0407",
+ 'yopf': "\uD835\uDD6A",
+ 'Yopf': "\uD835\uDD50",
+ 'yscr': "\uD835\uDCCE",
+ 'Yscr': "\uD835\uDCB4",
+ 'yucy': "\u044E",
+ 'YUcy': "\u042E",
+ 'yuml': '\xFF',
+ 'Yuml': "\u0178",
+ 'zacute': "\u017A",
+ 'Zacute': "\u0179",
+ 'zcaron': "\u017E",
+ 'Zcaron': "\u017D",
+ 'zcy': "\u0437",
+ 'Zcy': "\u0417",
+ 'zdot': "\u017C",
+ 'Zdot': "\u017B",
+ 'zeetrf': "\u2128",
+ 'ZeroWidthSpace': "\u200B",
+ 'zeta': "\u03B6",
+ 'Zeta': "\u0396",
+ 'zfr': "\uD835\uDD37",
+ 'Zfr': "\u2128",
+ 'zhcy': "\u0436",
+ 'ZHcy': "\u0416",
+ 'zigrarr': "\u21DD",
+ 'zopf': "\uD835\uDD6B",
+ 'Zopf': "\u2124",
+ 'zscr': "\uD835\uDCCF",
+ 'Zscr': "\uD835\uDCB5",
+ 'zwj': "\u200D",
+ 'zwnj': "\u200C"
+ };
+ var decodeMapLegacy = {
+ 'aacute': '\xE1',
+ 'Aacute': '\xC1',
+ 'acirc': '\xE2',
+ 'Acirc': '\xC2',
+ 'acute': '\xB4',
+ 'aelig': '\xE6',
+ 'AElig': '\xC6',
+ 'agrave': '\xE0',
+ 'Agrave': '\xC0',
+ 'amp': '&',
+ 'AMP': '&',
+ 'aring': '\xE5',
+ 'Aring': '\xC5',
+ 'atilde': '\xE3',
+ 'Atilde': '\xC3',
+ 'auml': '\xE4',
+ 'Auml': '\xC4',
+ 'brvbar': '\xA6',
+ 'ccedil': '\xE7',
+ 'Ccedil': '\xC7',
+ 'cedil': '\xB8',
+ 'cent': '\xA2',
+ 'copy': '\xA9',
+ 'COPY': '\xA9',
+ 'curren': '\xA4',
+ 'deg': '\xB0',
+ 'divide': '\xF7',
+ 'eacute': '\xE9',
+ 'Eacute': '\xC9',
+ 'ecirc': '\xEA',
+ 'Ecirc': '\xCA',
+ 'egrave': '\xE8',
+ 'Egrave': '\xC8',
+ 'eth': '\xF0',
+ 'ETH': '\xD0',
+ 'euml': '\xEB',
+ 'Euml': '\xCB',
+ 'frac12': '\xBD',
+ 'frac14': '\xBC',
+ 'frac34': '\xBE',
+ 'gt': '>',
+ 'GT': '>',
+ 'iacute': '\xED',
+ 'Iacute': '\xCD',
+ 'icirc': '\xEE',
+ 'Icirc': '\xCE',
+ 'iexcl': '\xA1',
+ 'igrave': '\xEC',
+ 'Igrave': '\xCC',
+ 'iquest': '\xBF',
+ 'iuml': '\xEF',
+ 'Iuml': '\xCF',
+ 'laquo': '\xAB',
+ 'lt': '<',
+ 'LT': '<',
+ 'macr': '\xAF',
+ 'micro': '\xB5',
+ 'middot': '\xB7',
+ 'nbsp': '\xA0',
+ 'not': '\xAC',
+ 'ntilde': '\xF1',
+ 'Ntilde': '\xD1',
+ 'oacute': '\xF3',
+ 'Oacute': '\xD3',
+ 'ocirc': '\xF4',
+ 'Ocirc': '\xD4',
+ 'ograve': '\xF2',
+ 'Ograve': '\xD2',
+ 'ordf': '\xAA',
+ 'ordm': '\xBA',
+ 'oslash': '\xF8',
+ 'Oslash': '\xD8',
+ 'otilde': '\xF5',
+ 'Otilde': '\xD5',
+ 'ouml': '\xF6',
+ 'Ouml': '\xD6',
+ 'para': '\xB6',
+ 'plusmn': '\xB1',
+ 'pound': '\xA3',
+ 'quot': '"',
+ 'QUOT': '"',
+ 'raquo': '\xBB',
+ 'reg': '\xAE',
+ 'REG': '\xAE',
+ 'sect': '\xA7',
+ 'shy': '\xAD',
+ 'sup1': '\xB9',
+ 'sup2': '\xB2',
+ 'sup3': '\xB3',
+ 'szlig': '\xDF',
+ 'thorn': '\xFE',
+ 'THORN': '\xDE',
+ 'times': '\xD7',
+ 'uacute': '\xFA',
+ 'Uacute': '\xDA',
+ 'ucirc': '\xFB',
+ 'Ucirc': '\xDB',
+ 'ugrave': '\xF9',
+ 'Ugrave': '\xD9',
+ 'uml': '\xA8',
+ 'uuml': '\xFC',
+ 'Uuml': '\xDC',
+ 'yacute': '\xFD',
+ 'Yacute': '\xDD',
+ 'yen': '\xA5',
+ 'yuml': '\xFF'
+ };
+ var decodeMapNumeric = {
+ '0': "\uFFFD",
+ '128': "\u20AC",
+ '130': "\u201A",
+ '131': "\u0192",
+ '132': "\u201E",
+ '133': "\u2026",
+ '134': "\u2020",
+ '135': "\u2021",
+ '136': "\u02C6",
+ '137': "\u2030",
+ '138': "\u0160",
+ '139': "\u2039",
+ '140': "\u0152",
+ '142': "\u017D",
+ '145': "\u2018",
+ '146': "\u2019",
+ '147': "\u201C",
+ '148': "\u201D",
+ '149': "\u2022",
+ '150': "\u2013",
+ '151': "\u2014",
+ '152': "\u02DC",
+ '153': "\u2122",
+ '154': "\u0161",
+ '155': "\u203A",
+ '156': "\u0153",
+ '158': "\u017E",
+ '159': "\u0178"
+ };
+ var invalidReferenceCodePoints = [1, 2, 3, 4, 5, 6, 7, 8, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 64976, 64977, 64978, 64979, 64980, 64981, 64982, 64983, 64984, 64985, 64986, 64987, 64988, 64989, 64990, 64991, 64992, 64993, 64994, 64995, 64996, 64997, 64998, 64999, 65000, 65001, 65002, 65003, 65004, 65005, 65006, 65007, 65534, 65535, 131070, 131071, 196606, 196607, 262142, 262143, 327678, 327679, 393214, 393215, 458750, 458751, 524286, 524287, 589822, 589823, 655358, 655359, 720894, 720895, 786430, 786431, 851966, 851967, 917502, 917503, 983038, 983039, 1048574, 1048575, 1114110, 1114111];
+ /*--------------------------------------------------------------------------*/
+
+ var stringFromCharCode = String.fromCharCode;
+ var object = {};
+ var hasOwnProperty = object.hasOwnProperty;
+
+ var has = function has(object, propertyName) {
+ return hasOwnProperty.call(object, propertyName);
+ };
+
+ var contains = function contains(array, value) {
+ var index = -1;
+ var length = array.length;
+
+ while (++index < length) {
+ if (array[index] == value) {
+ return true;
+ }
+ }
+
+ return false;
+ };
+
+ var merge = function merge(options, defaults) {
+ if (!options) {
+ return defaults;
+ }
+
+ var result = {};
+ var key;
+
+ for (key in defaults) {
+ // A `hasOwnProperty` check is not needed here, since only recognized
+ // option names are used anyway. Any others are ignored.
+ result[key] = has(options, key) ? options[key] : defaults[key];
+ }
+
+ return result;
+ }; // Modified version of `ucs2encode`; see https://mths.be/punycode.
+
+
+ var codePointToSymbol = function codePointToSymbol(codePoint, strict) {
+ var output = '';
+
+ if (codePoint >= 0xD800 && codePoint <= 0xDFFF || codePoint > 0x10FFFF) {
+ // See issue #4:
+ // “Otherwise, if the number is in the range 0xD800 to 0xDFFF or is
+ // greater than 0x10FFFF, then this is a parse error. Return a U+FFFD
+ // REPLACEMENT CHARACTER.”
+ if (strict) {
+ parseError('character reference outside the permissible Unicode range');
+ }
+
+ return "\uFFFD";
+ }
+
+ if (has(decodeMapNumeric, codePoint)) {
+ if (strict) {
+ parseError('disallowed character reference');
+ }
+
+ return decodeMapNumeric[codePoint];
+ }
+
+ if (strict && contains(invalidReferenceCodePoints, codePoint)) {
+ parseError('disallowed character reference');
+ }
+
+ if (codePoint > 0xFFFF) {
+ codePoint -= 0x10000;
+ output += stringFromCharCode(codePoint >>> 10 & 0x3FF | 0xD800);
+ codePoint = 0xDC00 | codePoint & 0x3FF;
+ }
+
+ output += stringFromCharCode(codePoint);
+ return output;
+ };
+
+ var hexEscape = function hexEscape(codePoint) {
+ return '' + codePoint.toString(16).toUpperCase() + ';';
+ };
+
+ var decEscape = function decEscape(codePoint) {
+ return '' + codePoint + ';';
+ };
+
+ var parseError = function parseError(message) {
+ throw Error('Parse error: ' + message);
+ };
+ /*--------------------------------------------------------------------------*/
+
+
+ var encode = function encode(string, options) {
+ options = merge(options, encode.options);
+ var strict = options.strict;
+
+ if (strict && regexInvalidRawCodePoint.test(string)) {
+ parseError('forbidden code point');
+ }
+
+ var encodeEverything = options.encodeEverything;
+ var useNamedReferences = options.useNamedReferences;
+ var allowUnsafeSymbols = options.allowUnsafeSymbols;
+ var escapeCodePoint = options.decimal ? decEscape : hexEscape;
+
+ var escapeBmpSymbol = function escapeBmpSymbol(symbol) {
+ return escapeCodePoint(symbol.charCodeAt(0));
+ };
+
+ if (encodeEverything) {
+ // Encode ASCII symbols.
+ string = string.replace(regexAsciiWhitelist, function (symbol) {
+ // Use named references if requested & possible.
+ if (useNamedReferences && has(encodeMap, symbol)) {
+ return '&' + encodeMap[symbol] + ';';
+ }
+
+ return escapeBmpSymbol(symbol);
+ }); // Shorten a few escapes that represent two symbols, of which at least one
+ // is within the ASCII range.
+
+ if (useNamedReferences) {
+ string = string.replace(/>\u20D2/g, '>⃒').replace(/<\u20D2/g, '<⃒').replace(/fj/g, 'fj');
+ } // Encode non-ASCII symbols.
+
+
+ if (useNamedReferences) {
+ // Encode non-ASCII symbols that can be replaced with a named reference.
+ string = string.replace(regexEncodeNonAscii, function (string) {
+ // Note: there is no need to check `has(encodeMap, string)` here.
+ return '&' + encodeMap[string] + ';';
+ });
+ } // Note: any remaining non-ASCII symbols are handled outside of the `if`.
+
+ } else if (useNamedReferences) {
+ // Apply named character references.
+ // Encode `<>"'&` using named character references.
+ if (!allowUnsafeSymbols) {
+ string = string.replace(regexEscape, function (string) {
+ return '&' + encodeMap[string] + ';'; // no need to check `has()` here
+ });
+ } // Shorten escapes that represent two symbols, of which at least one is
+ // `<>"'&`.
+
+
+ string = string.replace(/>\u20D2/g, '>⃒').replace(/<\u20D2/g, '<⃒'); // Encode non-ASCII symbols that can be replaced with a named reference.
+
+ string = string.replace(regexEncodeNonAscii, function (string) {
+ // Note: there is no need to check `has(encodeMap, string)` here.
+ return '&' + encodeMap[string] + ';';
+ });
+ } else if (!allowUnsafeSymbols) {
+ // Encode `<>"'&` using hexadecimal escapes, now that they’re not handled
+ // using named character references.
+ string = string.replace(regexEscape, escapeBmpSymbol);
+ }
+
+ return string // Encode astral symbols.
+ .replace(regexAstralSymbols, function ($0) {
+ // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
+ var high = $0.charCodeAt(0);
+ var low = $0.charCodeAt(1);
+ var codePoint = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000;
+ return escapeCodePoint(codePoint);
+ }) // Encode any remaining BMP symbols that are not printable ASCII symbols
+ // using a hexadecimal escape.
+ .replace(regexBmpWhitelist, escapeBmpSymbol);
+ }; // Expose default options (so they can be overridden globally).
+
+
+ encode.options = {
+ 'allowUnsafeSymbols': false,
+ 'encodeEverything': false,
+ 'strict': false,
+ 'useNamedReferences': false,
+ 'decimal': false
+ };
+
+ var decode = function decode(html, options) {
+ options = merge(options, decode.options);
+ var strict = options.strict;
+
+ if (strict && regexInvalidEntity.test(html)) {
+ parseError('malformed character reference');
+ }
+
+ return html.replace(regexDecode, function ($0, $1, $2, $3, $4, $5, $6, $7, $8) {
+ var codePoint;
+ var semicolon;
+ var decDigits;
+ var hexDigits;
+ var reference;
+ var next;
+
+ if ($1) {
+ reference = $1; // Note: there is no need to check `has(decodeMap, reference)`.
+
+ return decodeMap[reference];
+ }
+
+ if ($2) {
+ // Decode named character references without trailing `;`, e.g. `&`.
+ // This is only a parse error if it gets converted to `&`, or if it is
+ // followed by `=` in an attribute context.
+ reference = $2;
+ next = $3;
+
+ if (next && options.isAttributeValue) {
+ if (strict && next == '=') {
+ parseError('`&` did not start a character reference');
+ }
+
+ return $0;
+ } else {
+ if (strict) {
+ parseError('named character reference was not terminated by a semicolon');
+ } // Note: there is no need to check `has(decodeMapLegacy, reference)`.
+
+
+ return decodeMapLegacy[reference] + (next || '');
+ }
+ }
+
+ if ($4) {
+ // Decode decimal escapes, e.g. `𝌆`.
+ decDigits = $4;
+ semicolon = $5;
+
+ if (strict && !semicolon) {
+ parseError('character reference was not terminated by a semicolon');
+ }
+
+ codePoint = parseInt(decDigits, 10);
+ return codePointToSymbol(codePoint, strict);
+ }
+
+ if ($6) {
+ // Decode hexadecimal escapes, e.g. `𝌆`.
+ hexDigits = $6;
+ semicolon = $7;
+
+ if (strict && !semicolon) {
+ parseError('character reference was not terminated by a semicolon');
+ }
+
+ codePoint = parseInt(hexDigits, 16);
+ return codePointToSymbol(codePoint, strict);
+ } // If we’re still here, `if ($7)` is implied; it’s an ambiguous
+ // ampersand for sure. https://mths.be/notes/ambiguous-ampersands
+
+
+ if (strict) {
+ parseError('named character reference was not terminated by a semicolon');
+ }
+
+ return $0;
+ });
+ }; // Expose default options (so they can be overridden globally).
+
+
+ decode.options = {
+ 'isAttributeValue': false,
+ 'strict': false
+ };
+
+ var escape = function escape(string) {
+ return string.replace(regexEscape, function ($0) {
+ // Note: there is no need to check `has(escapeMap, $0)` here.
+ return escapeMap[$0];
+ });
+ };
+ /*--------------------------------------------------------------------------*/
+
+
+ var he = {
+ 'version': '1.2.0',
+ 'encode': encode,
+ 'decode': decode,
+ 'escape': escape,
+ 'unescape': decode
+ }; // Some AMD build optimizers, like r.js, check for specific condition patterns
+ // like the following:
+
+ if (freeExports && !freeExports.nodeType) {
+ if (freeModule) {
+ // in Node.js, io.js, or RingoJS v0.8.0+
+ freeModule.exports = he;
+ } else {
+ // in Narwhal or RingoJS v0.7.0-
+ for (var key in he) {
+ has(he, key) && (freeExports[key] = he[key]);
+ }
+ }
+ } else {
+ // in Rhino or a web browser
+ root.he = he;
+ }
+ })(commonjsGlobal);
+ });
+
+ var utils = createCommonjsModule(function (module, exports) {
+ /**
+ * Various utility functions used throughout Mocha's codebase.
+ * @module utils
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var nanoid = nonSecure.nanoid;
+ var MOCHA_ID_PROP_NAME = '__mocha_id__';
+ /**
+ * Inherit the prototype methods from one constructor into another.
+ *
+ * @param {function} ctor - Constructor function which needs to inherit the
+ * prototype.
+ * @param {function} superCtor - Constructor function to inherit prototype from.
+ * @throws {TypeError} if either constructor is null, or if super constructor
+ * lacks a prototype.
+ */
+
+ exports.inherits = util.inherits;
+ /**
+ * Escape special characters in the given string of html.
+ *
+ * @private
+ * @param {string} html
+ * @return {string}
+ */
+
+ exports.escape = function (html) {
+ return he.encode(String(html), {
+ useNamedReferences: false
+ });
+ };
+ /**
+ * Test if the given obj is type of string.
+ *
+ * @private
+ * @param {Object} obj
+ * @return {boolean}
+ */
+
+
+ exports.isString = function (obj) {
+ return typeof obj === 'string';
+ };
+ /**
+ * Compute a slug from the given `str`.
+ *
+ * @private
+ * @param {string} str
+ * @return {string}
+ */
+
+
+ exports.slug = function (str) {
+ return str.toLowerCase().replace(/\s+/g, '-').replace(/[^-\w]/g, '').replace(/-{2,}/g, '-');
+ };
+ /**
+ * Strip the function definition from `str`, and re-indent for pre whitespace.
+ *
+ * @param {string} str
+ * @return {string}
+ */
+
+
+ exports.clean = function (str) {
+ str = str.replace(/\r\n?|[\n\u2028\u2029]/g, '\n').replace(/^\uFEFF/, '') // (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content
+ .replace(/^function(?:\s*|\s+[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\s*\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\s*\}|((?:.|\n)*))$/, '$1$2$3');
+ var spaces = str.match(/^\n?( *)/)[1].length;
+ var tabs = str.match(/^\n?(\t*)/)[1].length;
+ var re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs || spaces) + '}', 'gm');
+ str = str.replace(re, '');
+ return str.trim();
+ };
+ /**
+ * If a value could have properties, and has none, this function is called,
+ * which returns a string representation of the empty value.
+ *
+ * Functions w/ no properties return `'[Function]'`
+ * Arrays w/ length === 0 return `'[]'`
+ * Objects w/ no properties return `'{}'`
+ * All else: return result of `value.toString()`
+ *
+ * @private
+ * @param {*} value The value to inspect.
+ * @param {string} typeHint The type of the value
+ * @returns {string}
+ */
+
+
+ function emptyRepresentation(value, typeHint) {
+ switch (typeHint) {
+ case 'function':
+ return '[Function]';
+
+ case 'object':
+ return '{}';
+
+ case 'array':
+ return '[]';
+
+ default:
+ return value.toString();
+ }
+ }
+ /**
+ * Takes some variable and asks `Object.prototype.toString()` what it thinks it
+ * is.
+ *
+ * @private
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
+ * @param {*} value The value to test.
+ * @returns {string} Computed type
+ * @example
+ * canonicalType({}) // 'object'
+ * canonicalType([]) // 'array'
+ * canonicalType(1) // 'number'
+ * canonicalType(false) // 'boolean'
+ * canonicalType(Infinity) // 'number'
+ * canonicalType(null) // 'null'
+ * canonicalType(new Date()) // 'date'
+ * canonicalType(/foo/) // 'regexp'
+ * canonicalType('type') // 'string'
+ * canonicalType(global) // 'global'
+ * canonicalType(new String('foo') // 'object'
+ * canonicalType(async function() {}) // 'asyncfunction'
+ * canonicalType(await import(name)) // 'module'
+ */
+
+
+ var canonicalType = exports.canonicalType = function canonicalType(value) {
+ if (value === undefined) {
+ return 'undefined';
+ } else if (value === null) {
+ return 'null';
+ } else if (isBuffer$2(value)) {
+ return 'buffer';
+ }
+
+ return Object.prototype.toString.call(value).replace(/^\[.+\s(.+?)]$/, '$1').toLowerCase();
+ };
+ /**
+ *
+ * Returns a general type or data structure of a variable
+ * @private
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
+ * @param {*} value The value to test.
+ * @returns {string} One of undefined, boolean, number, string, bigint, symbol, object
+ * @example
+ * type({}) // 'object'
+ * type([]) // 'array'
+ * type(1) // 'number'
+ * type(false) // 'boolean'
+ * type(Infinity) // 'number'
+ * type(null) // 'null'
+ * type(new Date()) // 'object'
+ * type(/foo/) // 'object'
+ * type('type') // 'string'
+ * type(global) // 'object'
+ * type(new String('foo') // 'string'
+ */
+
+
+ exports.type = function type(value) {
+ // Null is special
+ if (value === null) return 'null';
+ var primitives = new Set(['undefined', 'boolean', 'number', 'string', 'bigint', 'symbol']);
+
+ var _type = _typeof(value);
+
+ if (_type === 'function') return _type;
+ if (primitives.has(_type)) return _type;
+ if (value instanceof String) return 'string';
+ if (value instanceof Error) return 'error';
+ if (Array.isArray(value)) return 'array';
+ return _type;
+ };
+ /**
+ * Stringify `value`. Different behavior depending on type of value:
+ *
+ * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively.
+ * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes.
+ * - If `value` is an *empty* object, function, or array, return result of function
+ * {@link emptyRepresentation}.
+ * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of
+ * JSON.stringify().
+ *
+ * @private
+ * @see exports.type
+ * @param {*} value
+ * @return {string}
+ */
+
+
+ exports.stringify = function (value) {
+ var typeHint = canonicalType(value);
+
+ if (!~['object', 'array', 'function'].indexOf(typeHint)) {
+ if (typeHint === 'buffer') {
+ var json = Buffer$1.prototype.toJSON.call(value); // Based on the toJSON result
+
+ return jsonStringify(json.data && json.type ? json.data : json, 2).replace(/,(\n|$)/g, '$1');
+ } // IE7/IE8 has a bizarre String constructor; needs to be coerced
+ // into an array and back to obj.
+
+
+ if (typeHint === 'string' && _typeof(value) === 'object') {
+ value = value.split('').reduce(function (acc, _char, idx) {
+ acc[idx] = _char;
+ return acc;
+ }, {});
+ typeHint = 'object';
+ } else {
+ return jsonStringify(value);
+ }
+ }
+
+ for (var prop in value) {
+ if (Object.prototype.hasOwnProperty.call(value, prop)) {
+ return jsonStringify(exports.canonicalize(value, null, typeHint), 2).replace(/,(\n|$)/g, '$1');
+ }
+ }
+
+ return emptyRepresentation(value, typeHint);
+ };
+ /**
+ * like JSON.stringify but more sense.
+ *
+ * @private
+ * @param {Object} object
+ * @param {number=} spaces
+ * @param {number=} depth
+ * @returns {*}
+ */
+
+
+ function jsonStringify(object, spaces, depth) {
+ if (typeof spaces === 'undefined') {
+ // primitive types
+ return _stringify(object);
+ }
+
+ depth = depth || 1;
+ var space = spaces * depth;
+ var str = Array.isArray(object) ? '[' : '{';
+ var end = Array.isArray(object) ? ']' : '}';
+ var length = typeof object.length === 'number' ? object.length : Object.keys(object).length; // `.repeat()` polyfill
+
+ function repeat(s, n) {
+ return new Array(n).join(s);
+ }
+
+ function _stringify(val) {
+ switch (canonicalType(val)) {
+ case 'null':
+ case 'undefined':
+ val = '[' + val + ']';
+ break;
+
+ case 'array':
+ case 'object':
+ val = jsonStringify(val, spaces, depth + 1);
+ break;
+
+ case 'boolean':
+ case 'regexp':
+ case 'symbol':
+ case 'number':
+ val = val === 0 && 1 / val === -Infinity // `-0`
+ ? '-0' : val.toString();
+ break;
+
+ case 'bigint':
+ val = val.toString() + 'n';
+ break;
+
+ case 'date':
+ var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString();
+ val = '[Date: ' + sDate + ']';
+ break;
+
+ case 'buffer':
+ var json = val.toJSON(); // Based on the toJSON result
+
+ json = json.data && json.type ? json.data : json;
+ val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']';
+ break;
+
+ default:
+ val = val === '[Function]' || val === '[Circular]' ? val : JSON.stringify(val);
+ // string
+ }
+
+ return val;
+ }
+
+ for (var i in object) {
+ if (!Object.prototype.hasOwnProperty.call(object, i)) {
+ continue; // not my business
+ }
+
+ --length;
+ str += '\n ' + repeat(' ', space) + (Array.isArray(object) ? '' : '"' + i + '": ') + // key
+ _stringify(object[i]) + (length ? ',' : ''); // comma
+ }
+
+ return str + (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end);
+ }
+ /**
+ * Return a new Thing that has the keys in sorted order. Recursive.
+ *
+ * If the Thing...
+ * - has already been seen, return string `'[Circular]'`
+ * - is `undefined`, return string `'[undefined]'`
+ * - is `null`, return value `null`
+ * - is some other primitive, return the value
+ * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method
+ * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again.
+ * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()`
+ *
+ * @private
+ * @see {@link exports.stringify}
+ * @param {*} value Thing to inspect. May or may not have properties.
+ * @param {Array} [stack=[]] Stack of seen values
+ * @param {string} [typeHint] Type hint
+ * @return {(Object|Array|Function|string|undefined)}
+ */
+
+
+ exports.canonicalize = function canonicalize(value, stack, typeHint) {
+ var canonicalizedObj;
+ /* eslint-disable no-unused-vars */
+
+ var prop;
+ /* eslint-enable no-unused-vars */
+
+ typeHint = typeHint || canonicalType(value);
+
+ function withStack(value, fn) {
+ stack.push(value);
+ fn();
+ stack.pop();
+ }
+
+ stack = stack || [];
+
+ if (stack.indexOf(value) !== -1) {
+ return '[Circular]';
+ }
+
+ switch (typeHint) {
+ case 'undefined':
+ case 'buffer':
+ case 'null':
+ canonicalizedObj = value;
+ break;
+
+ case 'array':
+ withStack(value, function () {
+ canonicalizedObj = value.map(function (item) {
+ return exports.canonicalize(item, stack);
+ });
+ });
+ break;
+
+ case 'function':
+ /* eslint-disable-next-line no-unused-vars, no-unreachable-loop */
+ for (prop in value) {
+ canonicalizedObj = {};
+ break;
+ }
+ /* eslint-enable guard-for-in */
+
+
+ if (!canonicalizedObj) {
+ canonicalizedObj = emptyRepresentation(value, typeHint);
+ break;
+ }
+
+ /* falls through */
+
+ case 'object':
+ canonicalizedObj = canonicalizedObj || {};
+ withStack(value, function () {
+ Object.keys(value).sort().forEach(function (key) {
+ canonicalizedObj[key] = exports.canonicalize(value[key], stack);
+ });
+ });
+ break;
+
+ case 'date':
+ case 'number':
+ case 'regexp':
+ case 'boolean':
+ case 'symbol':
+ canonicalizedObj = value;
+ break;
+
+ default:
+ canonicalizedObj = value + '';
+ }
+
+ return canonicalizedObj;
+ };
+ /**
+ * @summary
+ * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`)
+ * @description
+ * When invoking this function you get a filter function that get the Error.stack as an input,
+ * and return a prettify output.
+ * (i.e: strip Mocha and internal node functions from stack trace).
+ * @returns {Function}
+ */
+
+
+ exports.stackTraceFilter = function () {
+ // TODO: Replace with `process.browser`
+ var is = typeof document === 'undefined' ? {
+ node: true
+ } : {
+ browser: true
+ };
+ var slash = path.sep;
+ var cwd;
+
+ if (is.node) {
+ cwd = exports.cwd() + slash;
+ } else {
+ cwd = (typeof location === 'undefined' ? window.location : location).href.replace(/\/[^/]*$/, '/');
+ slash = '/';
+ }
+
+ function isMochaInternal(line) {
+ return ~line.indexOf('node_modules' + slash + 'mocha' + slash) || ~line.indexOf(slash + 'mocha.js') || ~line.indexOf(slash + 'mocha.min.js');
+ }
+
+ function isNodeInternal(line) {
+ return ~line.indexOf('(timers.js:') || ~line.indexOf('(events.js:') || ~line.indexOf('(node.js:') || ~line.indexOf('(module.js:') || ~line.indexOf('GeneratorFunctionPrototype.next (native)') || false;
+ }
+
+ return function (stack) {
+ stack = stack.split('\n');
+ stack = stack.reduce(function (list, line) {
+ if (isMochaInternal(line)) {
+ return list;
+ }
+
+ if (is.node && isNodeInternal(line)) {
+ return list;
+ } // Clean up cwd(absolute)
+
+
+ if (/:\d+:\d+\)?$/.test(line)) {
+ line = line.replace('(' + cwd, '(');
+ }
+
+ list.push(line);
+ return list;
+ }, []);
+ return stack.join('\n');
+ };
+ };
+ /**
+ * Crude, but effective.
+ * @public
+ * @param {*} value
+ * @returns {boolean} Whether or not `value` is a Promise
+ */
+
+
+ exports.isPromise = function isPromise(value) {
+ return _typeof(value) === 'object' && value !== null && typeof value.then === 'function';
+ };
+ /**
+ * Clamps a numeric value to an inclusive range.
+ *
+ * @param {number} value - Value to be clamped.
+ * @param {number[]} range - Two element array specifying [min, max] range.
+ * @returns {number} clamped value
+ */
+
+
+ exports.clamp = function clamp(value, range) {
+ return Math.min(Math.max(value, range[0]), range[1]);
+ };
+ /**
+ * It's a noop.
+ * @public
+ */
+
+
+ exports.noop = function () {};
+ /**
+ * Creates a map-like object.
+ *
+ * @description
+ * A "map" is an object with no prototype, for our purposes. In some cases
+ * this would be more appropriate than a `Map`, especially if your environment
+ * doesn't support it. Recommended for use in Mocha's public APIs.
+ *
+ * @public
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Custom_and_Null_objects|MDN:Map}
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Custom_and_Null_objects|MDN:Object.create - Custom objects}
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Custom_and_Null_objects|MDN:Object.assign}
+ * @param {...*} [obj] - Arguments to `Object.assign()`.
+ * @returns {Object} An object with no prototype, having `...obj` properties
+ */
+
+
+ exports.createMap = function (obj) {
+ return Object.assign.apply(null, [Object.create(null)].concat(Array.prototype.slice.call(arguments)));
+ };
+ /**
+ * Creates a read-only map-like object.
+ *
+ * @description
+ * This differs from {@link module:utils.createMap createMap} only in that
+ * the argument must be non-empty, because the result is frozen.
+ *
+ * @see {@link module:utils.createMap createMap}
+ * @param {...*} [obj] - Arguments to `Object.assign()`.
+ * @returns {Object} A frozen object with no prototype, having `...obj` properties
+ * @throws {TypeError} if argument is not a non-empty object.
+ */
+
+
+ exports.defineConstants = function (obj) {
+ if (canonicalType(obj) !== 'object' || !Object.keys(obj).length) {
+ throw new TypeError('Invalid argument; expected a non-empty object');
+ }
+
+ return Object.freeze(exports.createMap(obj));
+ };
+ /**
+ * Returns current working directory
+ *
+ * Wrapper around `process.cwd()` for isolation
+ * @private
+ */
+
+
+ exports.cwd = function cwd() {
+ return process$4.cwd();
+ };
+ /**
+ * Returns `true` if Mocha is running in a browser.
+ * Checks for `process.browser`.
+ * @returns {boolean}
+ * @private
+ */
+
+
+ exports.isBrowser = function isBrowser() {
+ return Boolean(browser$2);
+ };
+ /*
+ * Casts `value` to an array; useful for optionally accepting array parameters
+ *
+ * It follows these rules, depending on `value`. If `value` is...
+ * 1. `undefined`: return an empty Array
+ * 2. `null`: return an array with a single `null` element
+ * 3. Any other object: return the value of `Array.from()` _if_ the object is iterable
+ * 4. otherwise: return an array with a single element, `value`
+ * @param {*} value - Something to cast to an Array
+ * @returns {Array<*>}
+ */
+
+
+ exports.castArray = function castArray(value) {
+ if (value === undefined) {
+ return [];
+ }
+
+ if (value === null) {
+ return [null];
+ }
+
+ if (_typeof(value) === 'object' && (typeof value[Symbol.iterator] === 'function' || value.length !== undefined)) {
+ return Array.from(value);
+ }
+
+ return [value];
+ };
+
+ exports.constants = exports.defineConstants({
+ MOCHA_ID_PROP_NAME: MOCHA_ID_PROP_NAME
+ });
+ /**
+ * Creates a new unique identifier
+ * @returns {string} Unique identifier
+ */
+
+ exports.uniqueID = function () {
+ return nanoid();
+ };
+
+ exports.assignNewMochaID = function (obj) {
+ var id = exports.uniqueID();
+ Object.defineProperty(obj, MOCHA_ID_PROP_NAME, {
+ get: function get() {
+ return id;
+ }
+ });
+ return obj;
+ };
+ /**
+ * Retrieves a Mocha ID from an object, if present.
+ * @param {*} [obj] - Object
+ * @returns {string|void}
+ */
+
+
+ exports.getMochaID = function (obj) {
+ return obj && _typeof(obj) === 'object' ? obj[MOCHA_ID_PROP_NAME] : undefined;
+ };
+ });
+
+ var _nodeResolve_empty = {};
+
+ var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ 'default': _nodeResolve_empty
+ });
+
+ var browser$1 = {
+ info: 'ℹ️',
+ success: '✅',
+ warning: '⚠️',
+ error: '❌️'
+ };
+
+ // `Map` constructor
+ // https://tc39.es/ecma262/#sec-map-objects
+ collection('Map', function (init) {
+ return function Map() { return init(this, arguments.length ? arguments[0] : undefined); };
+ }, collectionStrong);
+
+ /**
+ @module Pending
+ */
+
+ var pending = Pending;
+ /**
+ * Initialize a new `Pending` error with the given message.
+ *
+ * @param {string} message
+ */
+
+ function Pending(message) {
+ this.message = message;
+ }
+
+ /**
+ * Helpers.
+ */
+ var s = 1000;
+ var m = s * 60;
+ var h = m * 60;
+ var d = h * 24;
+ var w = d * 7;
+ var y = d * 365.25;
+ /**
+ * Parse or format the given `val`.
+ *
+ * Options:
+ *
+ * - `long` verbose formatting [false]
+ *
+ * @param {String|Number} val
+ * @param {Object} [options]
+ * @throws {Error} throw an error if val is not a non-empty string or a number
+ * @return {String|Number}
+ * @api public
+ */
+
+ var ms = function ms(val, options) {
+ options = options || {};
+
+ var type = _typeof(val);
+
+ if (type === 'string' && val.length > 0) {
+ return parse(val);
+ } else if (type === 'number' && isFinite(val)) {
+ return options["long"] ? fmtLong(val) : fmtShort(val);
+ }
+
+ throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val));
+ };
+ /**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
+
+
+ function parse(str) {
+ str = String(str);
+
+ if (str.length > 100) {
+ return;
+ }
+
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
+
+ if (!match) {
+ return;
+ }
+
+ var n = parseFloat(match[1]);
+ var type = (match[2] || 'ms').toLowerCase();
+
+ switch (type) {
+ case 'years':
+ case 'year':
+ case 'yrs':
+ case 'yr':
+ case 'y':
+ return n * y;
+
+ case 'weeks':
+ case 'week':
+ case 'w':
+ return n * w;
+
+ case 'days':
+ case 'day':
+ case 'd':
+ return n * d;
+
+ case 'hours':
+ case 'hour':
+ case 'hrs':
+ case 'hr':
+ case 'h':
+ return n * h;
+
+ case 'minutes':
+ case 'minute':
+ case 'mins':
+ case 'min':
+ case 'm':
+ return n * m;
+
+ case 'seconds':
+ case 'second':
+ case 'secs':
+ case 'sec':
+ case 's':
+ return n * s;
+
+ case 'milliseconds':
+ case 'millisecond':
+ case 'msecs':
+ case 'msec':
+ case 'ms':
+ return n;
+
+ default:
+ return undefined;
+ }
+ }
+ /**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+
+ function fmtShort(ms) {
+ var msAbs = Math.abs(ms);
+
+ if (msAbs >= d) {
+ return Math.round(ms / d) + 'd';
+ }
+
+ if (msAbs >= h) {
+ return Math.round(ms / h) + 'h';
+ }
+
+ if (msAbs >= m) {
+ return Math.round(ms / m) + 'm';
+ }
+
+ if (msAbs >= s) {
+ return Math.round(ms / s) + 's';
+ }
+
+ return ms + 'ms';
+ }
+ /**
+ * Long format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+
+ function fmtLong(ms) {
+ var msAbs = Math.abs(ms);
+
+ if (msAbs >= d) {
+ return plural(ms, msAbs, d, 'day');
+ }
+
+ if (msAbs >= h) {
+ return plural(ms, msAbs, h, 'hour');
+ }
+
+ if (msAbs >= m) {
+ return plural(ms, msAbs, m, 'minute');
+ }
+
+ if (msAbs >= s) {
+ return plural(ms, msAbs, s, 'second');
+ }
+
+ return ms + ' ms';
+ }
+ /**
+ * Pluralization helper.
+ */
+
+
+ function plural(ms, msAbs, n, name) {
+ var isPlural = msAbs >= n * 1.5;
+ return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
+ }
+
+ /**
+ * This is the common logic for both the Node.js and web browser
+ * implementations of `debug()`.
+ */
+
+ function setup(env) {
+ createDebug.debug = createDebug;
+ createDebug["default"] = createDebug;
+ createDebug.coerce = coerce;
+ createDebug.disable = disable;
+ createDebug.enable = enable;
+ createDebug.enabled = enabled;
+ createDebug.humanize = ms;
+ createDebug.destroy = destroy;
+ Object.keys(env).forEach(function (key) {
+ createDebug[key] = env[key];
+ });
+ /**
+ * The currently active debug mode names, and names to skip.
+ */
+
+ createDebug.names = [];
+ createDebug.skips = [];
+ /**
+ * Map of special "%n" handling functions, for the debug "format" argument.
+ *
+ * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
+ */
+
+ createDebug.formatters = {};
+ /**
+ * Selects a color for a debug namespace
+ * @param {String} namespace The namespace string for the for the debug instance to be colored
+ * @return {Number|String} An ANSI color code for the given namespace
+ * @api private
+ */
+
+ function selectColor(namespace) {
+ var hash = 0;
+
+ for (var i = 0; i < namespace.length; i++) {
+ hash = (hash << 5) - hash + namespace.charCodeAt(i);
+ hash |= 0; // Convert to 32bit integer
+ }
+
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
+ }
+
+ createDebug.selectColor = selectColor;
+ /**
+ * Create a debugger with the given `namespace`.
+ *
+ * @param {String} namespace
+ * @return {Function}
+ * @api public
+ */
+
+ function createDebug(namespace) {
+ var prevTime;
+ var enableOverride = null;
+ var namespacesCache;
+ var enabledCache;
+
+ function debug() {
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ // Disabled?
+ if (!debug.enabled) {
+ return;
+ }
+
+ var self = debug; // Set `diff` timestamp
+
+ var curr = Number(new Date());
+ var ms = curr - (prevTime || curr);
+ self.diff = ms;
+ self.prev = prevTime;
+ self.curr = curr;
+ prevTime = curr;
+ args[0] = createDebug.coerce(args[0]);
+
+ if (typeof args[0] !== 'string') {
+ // Anything else let's inspect with %O
+ args.unshift('%O');
+ } // Apply any `formatters` transformations
+
+
+ var index = 0;
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
+ // If we encounter an escaped % then don't increase the array index
+ if (match === '%%') {
+ return '%';
+ }
+
+ index++;
+ var formatter = createDebug.formatters[format];
+
+ if (typeof formatter === 'function') {
+ var val = args[index];
+ match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
+
+ args.splice(index, 1);
+ index--;
+ }
+
+ return match;
+ }); // Apply env-specific formatting (colors, etc.)
+
+ createDebug.formatArgs.call(self, args);
+ var logFn = self.log || createDebug.log;
+ logFn.apply(self, args);
+ }
+
+ debug.namespace = namespace;
+ debug.useColors = createDebug.useColors();
+ debug.color = createDebug.selectColor(namespace);
+ debug.extend = extend;
+ debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
+
+ Object.defineProperty(debug, 'enabled', {
+ enumerable: true,
+ configurable: false,
+ get: function get() {
+ if (enableOverride !== null) {
+ return enableOverride;
+ }
+
+ if (namespacesCache !== createDebug.namespaces) {
+ namespacesCache = createDebug.namespaces;
+ enabledCache = createDebug.enabled(namespace);
+ }
+
+ return enabledCache;
+ },
+ set: function set(v) {
+ enableOverride = v;
+ }
+ }); // Env-specific initialization logic for debug instances
+
+ if (typeof createDebug.init === 'function') {
+ createDebug.init(debug);
+ }
+
+ return debug;
+ }
+
+ function extend(namespace, delimiter) {
+ var newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
+ newDebug.log = this.log;
+ return newDebug;
+ }
+ /**
+ * Enables a debug mode by namespaces. This can include modes
+ * separated by a colon and wildcards.
+ *
+ * @param {String} namespaces
+ * @api public
+ */
+
+
+ function enable(namespaces) {
+ createDebug.save(namespaces);
+ createDebug.namespaces = namespaces;
+ createDebug.names = [];
+ createDebug.skips = [];
+ var i;
+ var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
+ var len = split.length;
+
+ for (i = 0; i < len; i++) {
+ if (!split[i]) {
+ // ignore empty strings
+ continue;
+ }
+
+ namespaces = split[i].replace(/\*/g, '.*?');
+
+ if (namespaces[0] === '-') {
+ createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
+ } else {
+ createDebug.names.push(new RegExp('^' + namespaces + '$'));
+ }
+ }
+ }
+ /**
+ * Disable debug output.
+ *
+ * @return {String} namespaces
+ * @api public
+ */
+
+
+ function disable() {
+ var namespaces = [].concat(_toConsumableArray(createDebug.names.map(toNamespace)), _toConsumableArray(createDebug.skips.map(toNamespace).map(function (namespace) {
+ return '-' + namespace;
+ }))).join(',');
+ createDebug.enable('');
+ return namespaces;
+ }
+ /**
+ * Returns true if the given mode name is enabled, false otherwise.
+ *
+ * @param {String} name
+ * @return {Boolean}
+ * @api public
+ */
+
+
+ function enabled(name) {
+ if (name[name.length - 1] === '*') {
+ return true;
+ }
+
+ var i;
+ var len;
+
+ for (i = 0, len = createDebug.skips.length; i < len; i++) {
+ if (createDebug.skips[i].test(name)) {
+ return false;
+ }
+ }
+
+ for (i = 0, len = createDebug.names.length; i < len; i++) {
+ if (createDebug.names[i].test(name)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+ /**
+ * Convert regexp to namespace
+ *
+ * @param {RegExp} regxep
+ * @return {String} namespace
+ * @api private
+ */
+
+
+ function toNamespace(regexp) {
+ return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, '*');
+ }
+ /**
+ * Coerce `val`.
+ *
+ * @param {Mixed} val
+ * @return {Mixed}
+ * @api private
+ */
+
+
+ function coerce(val) {
+ if (val instanceof Error) {
+ return val.stack || val.message;
+ }
+
+ return val;
+ }
+ /**
+ * XXX DO NOT USE. This is a temporary stub function.
+ * XXX It WILL be removed in the next major release.
+ */
+
+
+ function destroy() {
+ console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
+ }
+
+ createDebug.enable(createDebug.load());
+ return createDebug;
+ }
+
+ var common$1 = setup;
+
+ var browser = createCommonjsModule(function (module, exports) {
+ /* eslint-env browser */
+
+ /**
+ * This is the web browser implementation of `debug()`.
+ */
+ exports.formatArgs = formatArgs;
+ exports.save = save;
+ exports.load = load;
+ exports.useColors = useColors;
+ exports.storage = localstorage();
+
+ exports.destroy = function () {
+ var warned = false;
+ return function () {
+ if (!warned) {
+ warned = true;
+ console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
+ }
+ };
+ }();
+ /**
+ * Colors.
+ */
+
+
+ exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
+ /**
+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,
+ * and the Firebug extension (any Firefox version) are known
+ * to support "%c" CSS customizations.
+ *
+ * TODO: add a `localStorage` variable to explicitly enable/disable colors
+ */
+ // eslint-disable-next-line complexity
+
+ function useColors() {
+ // NB: In an Electron preload script, document will be defined but not fully
+ // initialized. Since we know we're in Chrome, we'll just detect this case
+ // explicitly
+ if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
+ return true;
+ } // Internet Explorer and Edge do not support colors.
+
+
+ if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
+ return false;
+ } // Is webkit? http://stackoverflow.com/a/16459606/376773
+ // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
+
+
+ return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
+ }
+ /**
+ * Colorize log arguments if enabled.
+ *
+ * @api public
+ */
+
+
+ function formatArgs(args) {
+ args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
+
+ if (!this.useColors) {
+ return;
+ }
+
+ var c = 'color: ' + this.color;
+ args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
+ // arguments passed either before or after the %c, so we need to
+ // figure out the correct index to insert the CSS into
+
+ var index = 0;
+ var lastC = 0;
+ args[0].replace(/%[a-zA-Z%]/g, function (match) {
+ if (match === '%%') {
+ return;
+ }
+
+ index++;
+
+ if (match === '%c') {
+ // We only are interested in the *last* %c
+ // (the user may have provided their own)
+ lastC = index;
+ }
+ });
+ args.splice(lastC, 0, c);
+ }
+ /**
+ * Invokes `console.debug()` when available.
+ * No-op when `console.debug` is not a "function".
+ * If `console.debug` is not available, falls back
+ * to `console.log`.
+ *
+ * @api public
+ */
+
+
+ exports.log = console.debug || console.log || function () {};
+ /**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+
+
+ function save(namespaces) {
+ try {
+ if (namespaces) {
+ exports.storage.setItem('debug', namespaces);
+ } else {
+ exports.storage.removeItem('debug');
+ }
+ } catch (error) {// Swallow
+ // XXX (@Qix-) should we be logging these?
+ }
+ }
+ /**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
+
+
+ function load() {
+ var r;
+
+ try {
+ r = exports.storage.getItem('debug');
+ } catch (error) {// Swallow
+ // XXX (@Qix-) should we be logging these?
+ } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
+
+
+ if (!r && typeof process$4 !== 'undefined' && 'env' in process$4) {
+ r = process$4.env.DEBUG;
+ }
+
+ return r;
+ }
+ /**
+ * Localstorage attempts to return the localstorage.
+ *
+ * This is necessary because safari throws
+ * when a user disables cookies/localstorage
+ * and you attempt to access it.
+ *
+ * @return {LocalStorage}
+ * @api private
+ */
+
+
+ function localstorage() {
+ try {
+ // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
+ // The Browser also has localStorage in the global context.
+ return localStorage;
+ } catch (error) {// Swallow
+ // XXX (@Qix-) should we be logging these?
+ }
+ }
+
+ module.exports = common$1(exports);
+ var formatters = module.exports.formatters;
+ /**
+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
+ */
+
+ formatters.j = function (v) {
+ try {
+ return JSON.stringify(v);
+ } catch (error) {
+ return '[UnexpectedJSONParseError]: ' + error.message;
+ }
+ };
+ });
+
+ var propertyIsEnumerable = objectPropertyIsEnumerable.f;
+
+ // `Object.{ entries, values }` methods implementation
+ var createMethod = function (TO_ENTRIES) {
+ return function (it) {
+ var O = toIndexedObject(it);
+ var keys = objectKeys(O);
+ var length = keys.length;
+ var i = 0;
+ var result = [];
+ var key;
+ while (length > i) {
+ key = keys[i++];
+ if (!descriptors || propertyIsEnumerable.call(O, key)) {
+ result.push(TO_ENTRIES ? [key, O[key]] : O[key]);
+ }
+ }
+ return result;
+ };
+ };
+
+ var objectToArray = {
+ // `Object.entries` method
+ // https://tc39.es/ecma262/#sec-object.entries
+ entries: createMethod(true),
+ // `Object.values` method
+ // https://tc39.es/ecma262/#sec-object.values
+ values: createMethod(false)
+ };
+
+ var $values = objectToArray.values;
+
+ // `Object.values` method
+ // https://tc39.es/ecma262/#sec-object.values
+ _export({ target: 'Object', stat: true }, {
+ values: function values(O) {
+ return $values(O);
+ }
+ });
+
+ var format = util.format;
+ /**
+ * Contains error codes, factory functions to create throwable error objects,
+ * and warning/deprecation functions.
+ * @module
+ */
+
+ /**
+ * process.emitWarning or a polyfill
+ * @see https://nodejs.org/api/process.html#process_process_emitwarning_warning_options
+ * @ignore
+ */
+
+ var emitWarning = function emitWarning(msg, type) {
+ if (process$4.emitWarning) {
+ process$4.emitWarning(msg, type);
+ } else {
+ /* istanbul ignore next */
+ nextTick$1(function () {
+ console.warn(type + ': ' + msg);
+ });
+ }
+ };
+ /**
+ * Show a deprecation warning. Each distinct message is only displayed once.
+ * Ignores empty messages.
+ *
+ * @param {string} [msg] - Warning to print
+ * @private
+ */
+
+
+ var deprecate = function deprecate(msg) {
+ msg = String(msg);
+
+ if (msg && !deprecate.cache[msg]) {
+ deprecate.cache[msg] = true;
+ emitWarning(msg, 'DeprecationWarning');
+ }
+ };
+
+ deprecate.cache = {};
+ /**
+ * Show a generic warning.
+ * Ignores empty messages.
+ *
+ * @param {string} [msg] - Warning to print
+ * @private
+ */
+
+ var warn = function warn(msg) {
+ if (msg) {
+ emitWarning(msg);
+ }
+ };
+ /**
+ * When Mocha throws exceptions (or rejects `Promise`s), it attempts to assign a `code` property to the `Error` object, for easier handling. These are the potential values of `code`.
+ * @public
+ * @namespace
+ * @memberof module:lib/errors
+ */
+
+
+ var constants$4 = {
+ /**
+ * An unrecoverable error.
+ * @constant
+ * @default
+ */
+ FATAL: 'ERR_MOCHA_FATAL',
+
+ /**
+ * The type of an argument to a function call is invalid
+ * @constant
+ * @default
+ */
+ INVALID_ARG_TYPE: 'ERR_MOCHA_INVALID_ARG_TYPE',
+
+ /**
+ * The value of an argument to a function call is invalid
+ * @constant
+ * @default
+ */
+ INVALID_ARG_VALUE: 'ERR_MOCHA_INVALID_ARG_VALUE',
+
+ /**
+ * Something was thrown, but it wasn't an `Error`
+ * @constant
+ * @default
+ */
+ INVALID_EXCEPTION: 'ERR_MOCHA_INVALID_EXCEPTION',
+
+ /**
+ * An interface (e.g., `Mocha.interfaces`) is unknown or invalid
+ * @constant
+ * @default
+ */
+ INVALID_INTERFACE: 'ERR_MOCHA_INVALID_INTERFACE',
+
+ /**
+ * A reporter (.e.g, `Mocha.reporters`) is unknown or invalid
+ * @constant
+ * @default
+ */
+ INVALID_REPORTER: 'ERR_MOCHA_INVALID_REPORTER',
+
+ /**
+ * `done()` was called twice in a `Test` or `Hook` callback
+ * @constant
+ * @default
+ */
+ MULTIPLE_DONE: 'ERR_MOCHA_MULTIPLE_DONE',
+
+ /**
+ * No files matched the pattern provided by the user
+ * @constant
+ * @default
+ */
+ NO_FILES_MATCH_PATTERN: 'ERR_MOCHA_NO_FILES_MATCH_PATTERN',
+
+ /**
+ * Known, but unsupported behavior of some kind
+ * @constant
+ * @default
+ */
+ UNSUPPORTED: 'ERR_MOCHA_UNSUPPORTED',
+
+ /**
+ * Invalid state transition occurring in `Mocha` instance
+ * @constant
+ * @default
+ */
+ INSTANCE_ALREADY_RUNNING: 'ERR_MOCHA_INSTANCE_ALREADY_RUNNING',
+
+ /**
+ * Invalid state transition occurring in `Mocha` instance
+ * @constant
+ * @default
+ */
+ INSTANCE_ALREADY_DISPOSED: 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED',
+
+ /**
+ * Use of `only()` w/ `--forbid-only` results in this error.
+ * @constant
+ * @default
+ */
+ FORBIDDEN_EXCLUSIVITY: 'ERR_MOCHA_FORBIDDEN_EXCLUSIVITY',
+
+ /**
+ * To be thrown when a user-defined plugin implementation (e.g., `mochaHooks`) is invalid
+ * @constant
+ * @default
+ */
+ INVALID_PLUGIN_IMPLEMENTATION: 'ERR_MOCHA_INVALID_PLUGIN_IMPLEMENTATION',
+
+ /**
+ * To be thrown when a builtin or third-party plugin definition (the _definition_ of `mochaHooks`) is invalid
+ * @constant
+ * @default
+ */
+ INVALID_PLUGIN_DEFINITION: 'ERR_MOCHA_INVALID_PLUGIN_DEFINITION',
+
+ /**
+ * When a runnable exceeds its allowed run time.
+ * @constant
+ * @default
+ */
+ TIMEOUT: 'ERR_MOCHA_TIMEOUT',
+
+ /**
+ * Input file is not able to be parsed
+ * @constant
+ * @default
+ */
+ UNPARSABLE_FILE: 'ERR_MOCHA_UNPARSABLE_FILE'
+ };
+ /**
+ * A set containing all string values of all Mocha error constants, for use by {@link isMochaError}.
+ * @private
+ */
+
+ var MOCHA_ERRORS = new Set(Object.values(constants$4));
+ /**
+ * Creates an error object to be thrown when no files to be tested could be found using specified pattern.
+ *
+ * @public
+ * @static
+ * @param {string} message - Error message to be displayed.
+ * @param {string} pattern - User-specified argument value.
+ * @returns {Error} instance detailing the error condition
+ */
+
+ function createNoFilesMatchPatternError(message, pattern) {
+ var err = new Error(message);
+ err.code = constants$4.NO_FILES_MATCH_PATTERN;
+ err.pattern = pattern;
+ return err;
+ }
+ /**
+ * Creates an error object to be thrown when the reporter specified in the options was not found.
+ *
+ * @public
+ * @param {string} message - Error message to be displayed.
+ * @param {string} reporter - User-specified reporter value.
+ * @returns {Error} instance detailing the error condition
+ */
+
+
+ function createInvalidReporterError(message, reporter) {
+ var err = new TypeError(message);
+ err.code = constants$4.INVALID_REPORTER;
+ err.reporter = reporter;
+ return err;
+ }
+ /**
+ * Creates an error object to be thrown when the interface specified in the options was not found.
+ *
+ * @public
+ * @static
+ * @param {string} message - Error message to be displayed.
+ * @param {string} ui - User-specified interface value.
+ * @returns {Error} instance detailing the error condition
+ */
+
+
+ function createInvalidInterfaceError(message, ui) {
+ var err = new Error(message);
+ err.code = constants$4.INVALID_INTERFACE;
+ err["interface"] = ui;
+ return err;
+ }
+ /**
+ * Creates an error object to be thrown when a behavior, option, or parameter is unsupported.
+ *
+ * @public
+ * @static
+ * @param {string} message - Error message to be displayed.
+ * @returns {Error} instance detailing the error condition
+ */
+
+
+ function createUnsupportedError$2(message) {
+ var err = new Error(message);
+ err.code = constants$4.UNSUPPORTED;
+ return err;
+ }
+ /**
+ * Creates an error object to be thrown when an argument is missing.
+ *
+ * @public
+ * @static
+ * @param {string} message - Error message to be displayed.
+ * @param {string} argument - Argument name.
+ * @param {string} expected - Expected argument datatype.
+ * @returns {Error} instance detailing the error condition
+ */
+
+
+ function createMissingArgumentError$1(message, argument, expected) {
+ return createInvalidArgumentTypeError$1(message, argument, expected);
+ }
+ /**
+ * Creates an error object to be thrown when an argument did not use the supported type
+ *
+ * @public
+ * @static
+ * @param {string} message - Error message to be displayed.
+ * @param {string} argument - Argument name.
+ * @param {string} expected - Expected argument datatype.
+ * @returns {Error} instance detailing the error condition
+ */
+
+
+ function createInvalidArgumentTypeError$1(message, argument, expected) {
+ var err = new TypeError(message);
+ err.code = constants$4.INVALID_ARG_TYPE;
+ err.argument = argument;
+ err.expected = expected;
+ err.actual = _typeof(argument);
+ return err;
+ }
+ /**
+ * Creates an error object to be thrown when an argument did not use the supported value
+ *
+ * @public
+ * @static
+ * @param {string} message - Error message to be displayed.
+ * @param {string} argument - Argument name.
+ * @param {string} value - Argument value.
+ * @param {string} [reason] - Why value is invalid.
+ * @returns {Error} instance detailing the error condition
+ */
+
+
+ function createInvalidArgumentValueError(message, argument, value, reason) {
+ var err = new TypeError(message);
+ err.code = constants$4.INVALID_ARG_VALUE;
+ err.argument = argument;
+ err.value = value;
+ err.reason = typeof reason !== 'undefined' ? reason : 'is invalid';
+ return err;
+ }
+ /**
+ * Creates an error object to be thrown when an exception was caught, but the `Error` is falsy or undefined.
+ *
+ * @public
+ * @static
+ * @param {string} message - Error message to be displayed.
+ * @returns {Error} instance detailing the error condition
+ */
+
+
+ function createInvalidExceptionError$2(message, value) {
+ var err = new Error(message);
+ err.code = constants$4.INVALID_EXCEPTION;
+ err.valueType = _typeof(value);
+ err.value = value;
+ return err;
+ }
+ /**
+ * Creates an error object to be thrown when an unrecoverable error occurs.
+ *
+ * @public
+ * @static
+ * @param {string} message - Error message to be displayed.
+ * @returns {Error} instance detailing the error condition
+ */
+
+
+ function createFatalError$1(message, value) {
+ var err = new Error(message);
+ err.code = constants$4.FATAL;
+ err.valueType = _typeof(value);
+ err.value = value;
+ return err;
+ }
+ /**
+ * Dynamically creates a plugin-type-specific error based on plugin type
+ * @param {string} message - Error message
+ * @param {"reporter"|"ui"} pluginType - Plugin type. Future: expand as needed
+ * @param {string} [pluginId] - Name/path of plugin, if any
+ * @throws When `pluginType` is not known
+ * @public
+ * @static
+ * @returns {Error}
+ */
+
+
+ function createInvalidLegacyPluginError(message, pluginType, pluginId) {
+ switch (pluginType) {
+ case 'reporter':
+ return createInvalidReporterError(message, pluginId);
+
+ case 'ui':
+ return createInvalidInterfaceError(message, pluginId);
+
+ default:
+ throw new Error('unknown pluginType "' + pluginType + '"');
+ }
+ }
+ /**
+ * **DEPRECATED**. Use {@link createInvalidLegacyPluginError} instead Dynamically creates a plugin-type-specific error based on plugin type
+ * @deprecated
+ * @param {string} message - Error message
+ * @param {"reporter"|"interface"} pluginType - Plugin type. Future: expand as needed
+ * @param {string} [pluginId] - Name/path of plugin, if any
+ * @throws When `pluginType` is not known
+ * @public
+ * @static
+ * @returns {Error}
+ */
+
+
+ function createInvalidPluginError() {
+ deprecate('Use createInvalidLegacyPluginError() instead');
+ return createInvalidLegacyPluginError.apply(void 0, arguments);
+ }
+ /**
+ * Creates an error object to be thrown when a mocha object's `run` method is executed while it is already disposed.
+ * @param {string} message The error message to be displayed.
+ * @param {boolean} cleanReferencesAfterRun the value of `cleanReferencesAfterRun`
+ * @param {Mocha} instance the mocha instance that throw this error
+ * @static
+ */
+
+
+ function createMochaInstanceAlreadyDisposedError(message, cleanReferencesAfterRun, instance) {
+ var err = new Error(message);
+ err.code = constants$4.INSTANCE_ALREADY_DISPOSED;
+ err.cleanReferencesAfterRun = cleanReferencesAfterRun;
+ err.instance = instance;
+ return err;
+ }
+ /**
+ * Creates an error object to be thrown when a mocha object's `run` method is called while a test run is in progress.
+ * @param {string} message The error message to be displayed.
+ * @static
+ * @public
+ */
+
+
+ function createMochaInstanceAlreadyRunningError(message, instance) {
+ var err = new Error(message);
+ err.code = constants$4.INSTANCE_ALREADY_RUNNING;
+ err.instance = instance;
+ return err;
+ }
+ /**
+ * Creates an error object to be thrown when done() is called multiple times in a test
+ *
+ * @public
+ * @param {Runnable} runnable - Original runnable
+ * @param {Error} [originalErr] - Original error, if any
+ * @returns {Error} instance detailing the error condition
+ * @static
+ */
+
+
+ function createMultipleDoneError$1(runnable, originalErr) {
+ var title;
+
+ try {
+ title = format('<%s>', runnable.fullTitle());
+
+ if (runnable.parent.root) {
+ title += ' (of root suite)';
+ }
+ } catch (ignored) {
+ title = format('<%s> (of unknown suite)', runnable.title);
+ }
+
+ var message = format('done() called multiple times in %s %s', runnable.type ? runnable.type : 'unknown runnable', title);
+
+ if (runnable.file) {
+ message += format(' of file %s', runnable.file);
+ }
+
+ if (originalErr) {
+ message += format('; in addition, done() received error: %s', originalErr);
+ }
+
+ var err = new Error(message);
+ err.code = constants$4.MULTIPLE_DONE;
+ err.valueType = _typeof(originalErr);
+ err.value = originalErr;
+ return err;
+ }
+ /**
+ * Creates an error object to be thrown when `.only()` is used with
+ * `--forbid-only`.
+ * @static
+ * @public
+ * @param {Mocha} mocha - Mocha instance
+ * @returns {Error} Error with code {@link constants.FORBIDDEN_EXCLUSIVITY}
+ */
+
+
+ function createForbiddenExclusivityError$1(mocha) {
+ var err = new Error(mocha.isWorker ? '`.only` is not supported in parallel mode' : '`.only` forbidden by --forbid-only');
+ err.code = constants$4.FORBIDDEN_EXCLUSIVITY;
+ return err;
+ }
+ /**
+ * Creates an error object to be thrown when a plugin definition is invalid
+ * @static
+ * @param {string} msg - Error message
+ * @param {PluginDefinition} [pluginDef] - Problematic plugin definition
+ * @public
+ * @returns {Error} Error with code {@link constants.INVALID_PLUGIN_DEFINITION}
+ */
+
+
+ function createInvalidPluginDefinitionError(msg, pluginDef) {
+ var err = new Error(msg);
+ err.code = constants$4.INVALID_PLUGIN_DEFINITION;
+ err.pluginDef = pluginDef;
+ return err;
+ }
+ /**
+ * Creates an error object to be thrown when a plugin implementation (user code) is invalid
+ * @static
+ * @param {string} msg - Error message
+ * @param {Object} [opts] - Plugin definition and user-supplied implementation
+ * @param {PluginDefinition} [opts.pluginDef] - Plugin Definition
+ * @param {*} [opts.pluginImpl] - Plugin Implementation (user-supplied)
+ * @public
+ * @returns {Error} Error with code {@link constants.INVALID_PLUGIN_DEFINITION}
+ */
+
+
+ function createInvalidPluginImplementationError(msg) {
+ var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
+ pluginDef = _ref.pluginDef,
+ pluginImpl = _ref.pluginImpl;
+
+ var err = new Error(msg);
+ err.code = constants$4.INVALID_PLUGIN_IMPLEMENTATION;
+ err.pluginDef = pluginDef;
+ err.pluginImpl = pluginImpl;
+ return err;
+ }
+ /**
+ * Creates an error object to be thrown when a runnable exceeds its allowed run time.
+ * @static
+ * @param {string} msg - Error message
+ * @param {number} [timeout] - Timeout in ms
+ * @param {string} [file] - File, if given
+ * @returns {MochaTimeoutError}
+ */
+
+
+ function createTimeoutError$1(msg, timeout, file) {
+ var err = new Error(msg);
+ err.code = constants$4.TIMEOUT;
+ err.timeout = timeout;
+ err.file = file;
+ return err;
+ }
+ /**
+ * Creates an error object to be thrown when file is unparsable
+ * @public
+ * @static
+ * @param {string} message - Error message to be displayed.
+ * @param {string} filename - File name
+ * @returns {Error} Error with code {@link constants.UNPARSABLE_FILE}
+ */
+
+
+ function createUnparsableFileError(message, filename) {
+ var err = new Error(message);
+ err.code = constants$4.UNPARSABLE_FILE;
+ return err;
+ }
+ /**
+ * Returns `true` if an error came out of Mocha.
+ * _Can suffer from false negatives, but not false positives._
+ * @static
+ * @public
+ * @param {*} err - Error, or anything
+ * @returns {boolean}
+ */
+
+
+ var isMochaError$1 = function isMochaError(err) {
+ return Boolean(err && _typeof(err) === 'object' && MOCHA_ERRORS.has(err.code));
+ };
+
+ var errors = {
+ constants: constants$4,
+ createFatalError: createFatalError$1,
+ createForbiddenExclusivityError: createForbiddenExclusivityError$1,
+ createInvalidArgumentTypeError: createInvalidArgumentTypeError$1,
+ createInvalidArgumentValueError: createInvalidArgumentValueError,
+ createInvalidExceptionError: createInvalidExceptionError$2,
+ createInvalidInterfaceError: createInvalidInterfaceError,
+ createInvalidLegacyPluginError: createInvalidLegacyPluginError,
+ createInvalidPluginDefinitionError: createInvalidPluginDefinitionError,
+ createInvalidPluginError: createInvalidPluginError,
+ createInvalidPluginImplementationError: createInvalidPluginImplementationError,
+ createInvalidReporterError: createInvalidReporterError,
+ createMissingArgumentError: createMissingArgumentError$1,
+ createMochaInstanceAlreadyDisposedError: createMochaInstanceAlreadyDisposedError,
+ createMochaInstanceAlreadyRunningError: createMochaInstanceAlreadyRunningError,
+ createMultipleDoneError: createMultipleDoneError$1,
+ createNoFilesMatchPatternError: createNoFilesMatchPatternError,
+ createTimeoutError: createTimeoutError$1,
+ createUnparsableFileError: createUnparsableFileError,
+ createUnsupportedError: createUnsupportedError$2,
+ deprecate: deprecate,
+ isMochaError: isMochaError$1,
+ warn: warn
+ };
+
+ var EventEmitter$1 = EventEmitter$2.EventEmitter;
+ var debug$1 = browser('mocha:runnable');
+ var createInvalidExceptionError$1 = errors.createInvalidExceptionError,
+ createMultipleDoneError = errors.createMultipleDoneError,
+ createTimeoutError = errors.createTimeoutError;
+ /**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ * @private
+ */
+
+ var Date$4 = commonjsGlobal.Date;
+ var setTimeout$3 = commonjsGlobal.setTimeout;
+ var clearTimeout$1 = commonjsGlobal.clearTimeout;
+ var toString = Object.prototype.toString;
+ var runnable = Runnable;
+ /**
+ * Initialize a new `Runnable` with the given `title` and callback `fn`.
+ *
+ * @class
+ * @extends external:EventEmitter
+ * @public
+ * @param {String} title
+ * @param {Function} fn
+ */
+
+ function Runnable(title, fn) {
+ this.title = title;
+ this.fn = fn;
+ this.body = (fn || '').toString();
+ this.async = fn && fn.length;
+ this.sync = !this.async;
+ this._timeout = 2000;
+ this._slow = 75;
+ this._retries = -1;
+ utils.assignNewMochaID(this);
+ Object.defineProperty(this, 'id', {
+ get: function get() {
+ return utils.getMochaID(this);
+ }
+ });
+ this.reset();
+ }
+ /**
+ * Inherit from `EventEmitter.prototype`.
+ */
+
+
+ utils.inherits(Runnable, EventEmitter$1);
+ /**
+ * Resets the state initially or for a next run.
+ */
+
+ Runnable.prototype.reset = function () {
+ this.timedOut = false;
+ this._currentRetry = 0;
+ this.pending = false;
+ delete this.state;
+ delete this.err;
+ };
+ /**
+ * Get current timeout value in msecs.
+ *
+ * @private
+ * @returns {number} current timeout threshold value
+ */
+
+ /**
+ * @summary
+ * Set timeout threshold value (msecs).
+ *
+ * @description
+ * A string argument can use shorthand (e.g., "2s") and will be converted.
+ * The value will be clamped to range [0
, 2^31 -1
].
+ * If clamped value matches either range endpoint, timeouts will be disabled.
+ *
+ * @private
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Maximum_delay_value}
+ * @param {number|string} ms - Timeout threshold value.
+ * @returns {Runnable} this
+ * @chainable
+ */
+
+
+ Runnable.prototype.timeout = function (ms) {
+ if (!arguments.length) {
+ return this._timeout;
+ }
+
+ if (typeof ms === 'string') {
+ ms = ms$1(ms);
+ } // Clamp to range
+
+
+ var INT_MAX = Math.pow(2, 31) - 1;
+ var range = [0, INT_MAX];
+ ms = utils.clamp(ms, range); // see #1652 for reasoning
+
+ if (ms === range[0] || ms === range[1]) {
+ this._timeout = 0;
+ } else {
+ this._timeout = ms;
+ }
+
+ debug$1('timeout %d', this._timeout);
+
+ if (this.timer) {
+ this.resetTimeout();
+ }
+
+ return this;
+ };
+ /**
+ * Set or get slow `ms`.
+ *
+ * @private
+ * @param {number|string} ms
+ * @return {Runnable|number} ms or Runnable instance.
+ */
+
+
+ Runnable.prototype.slow = function (ms) {
+ if (!arguments.length || typeof ms === 'undefined') {
+ return this._slow;
+ }
+
+ if (typeof ms === 'string') {
+ ms = ms$1(ms);
+ }
+
+ debug$1('slow %d', ms);
+ this._slow = ms;
+ return this;
+ };
+ /**
+ * Halt and mark as pending.
+ *
+ * @memberof Mocha.Runnable
+ * @public
+ */
+
+
+ Runnable.prototype.skip = function () {
+ this.pending = true;
+ throw new pending('sync skip; aborting execution');
+ };
+ /**
+ * Check if this runnable or its parent suite is marked as pending.
+ *
+ * @private
+ */
+
+
+ Runnable.prototype.isPending = function () {
+ return this.pending || this.parent && this.parent.isPending();
+ };
+ /**
+ * Return `true` if this Runnable has failed.
+ * @return {boolean}
+ * @private
+ */
+
+
+ Runnable.prototype.isFailed = function () {
+ return !this.isPending() && this.state === constants$3.STATE_FAILED;
+ };
+ /**
+ * Return `true` if this Runnable has passed.
+ * @return {boolean}
+ * @private
+ */
+
+
+ Runnable.prototype.isPassed = function () {
+ return !this.isPending() && this.state === constants$3.STATE_PASSED;
+ };
+ /**
+ * Set or get number of retries.
+ *
+ * @private
+ */
+
+
+ Runnable.prototype.retries = function (n) {
+ if (!arguments.length) {
+ return this._retries;
+ }
+
+ this._retries = n;
+ };
+ /**
+ * Set or get current retry
+ *
+ * @private
+ */
+
+
+ Runnable.prototype.currentRetry = function (n) {
+ if (!arguments.length) {
+ return this._currentRetry;
+ }
+
+ this._currentRetry = n;
+ };
+ /**
+ * Return the full title generated by recursively concatenating the parent's
+ * full title.
+ *
+ * @memberof Mocha.Runnable
+ * @public
+ * @return {string}
+ */
+
+
+ Runnable.prototype.fullTitle = function () {
+ return this.titlePath().join(' ');
+ };
+ /**
+ * Return the title path generated by concatenating the parent's title path with the title.
+ *
+ * @memberof Mocha.Runnable
+ * @public
+ * @return {string}
+ */
+
+
+ Runnable.prototype.titlePath = function () {
+ return this.parent.titlePath().concat([this.title]);
+ };
+ /**
+ * Clear the timeout.
+ *
+ * @private
+ */
+
+
+ Runnable.prototype.clearTimeout = function () {
+ clearTimeout$1(this.timer);
+ };
+ /**
+ * Reset the timeout.
+ *
+ * @private
+ */
+
+
+ Runnable.prototype.resetTimeout = function () {
+ var self = this;
+ var ms = this.timeout();
+
+ if (ms === 0) {
+ return;
+ }
+
+ this.clearTimeout();
+ this.timer = setTimeout$3(function () {
+ if (self.timeout() === 0) {
+ return;
+ }
+
+ self.callback(self._timeoutError(ms));
+ self.timedOut = true;
+ }, ms);
+ };
+ /**
+ * Set or get a list of whitelisted globals for this test run.
+ *
+ * @private
+ * @param {string[]} globals
+ */
+
+
+ Runnable.prototype.globals = function (globals) {
+ if (!arguments.length) {
+ return this._allowedGlobals;
+ }
+
+ this._allowedGlobals = globals;
+ };
+ /**
+ * Run the test and invoke `fn(err)`.
+ *
+ * @param {Function} fn
+ * @private
+ */
+
+
+ Runnable.prototype.run = function (fn) {
+ var self = this;
+ var start = new Date$4();
+ var ctx = this.ctx;
+ var finished;
+ var errorWasHandled = false;
+ if (this.isPending()) return fn(); // Sometimes the ctx exists, but it is not runnable
+
+ if (ctx && ctx.runnable) {
+ ctx.runnable(this);
+ } // called multiple times
+
+
+ function multiple(err) {
+ if (errorWasHandled) {
+ return;
+ }
+
+ errorWasHandled = true;
+ self.emit('error', createMultipleDoneError(self, err));
+ } // finished
+
+
+ function done(err) {
+ var ms = self.timeout();
+
+ if (self.timedOut) {
+ return;
+ }
+
+ if (finished) {
+ return multiple(err);
+ }
+
+ self.clearTimeout();
+ self.duration = new Date$4() - start;
+ finished = true;
+
+ if (!err && self.duration > ms && ms > 0) {
+ err = self._timeoutError(ms);
+ }
+
+ fn(err);
+ } // for .resetTimeout() and Runner#uncaught()
+
+
+ this.callback = done;
+
+ if (this.fn && typeof this.fn.call !== 'function') {
+ done(new TypeError('A runnable must be passed a function as its second argument.'));
+ return;
+ } // explicit async with `done` argument
+
+
+ if (this.async) {
+ this.resetTimeout(); // allows skip() to be used in an explicit async context
+
+ this.skip = function asyncSkip() {
+ this.pending = true;
+ done(); // halt execution, the uncaught handler will ignore the failure.
+
+ throw new pending('async skip; aborting execution');
+ };
+
+ try {
+ callFnAsync(this.fn);
+ } catch (err) {
+ // handles async runnables which actually run synchronously
+ errorWasHandled = true;
+
+ if (err instanceof pending) {
+ return; // done() is already called in this.skip()
+ } else if (this.allowUncaught) {
+ throw err;
+ }
+
+ done(Runnable.toValueOrError(err));
+ }
+
+ return;
+ } // sync or promise-returning
+
+
+ try {
+ callFn(this.fn);
+ } catch (err) {
+ errorWasHandled = true;
+
+ if (err instanceof pending) {
+ return done();
+ } else if (this.allowUncaught) {
+ throw err;
+ }
+
+ done(Runnable.toValueOrError(err));
+ }
+
+ function callFn(fn) {
+ var result = fn.call(ctx);
+
+ if (result && typeof result.then === 'function') {
+ self.resetTimeout();
+ result.then(function () {
+ done(); // Return null so libraries like bluebird do not warn about
+ // subsequently constructed Promises.
+
+ return null;
+ }, function (reason) {
+ done(reason || new Error('Promise rejected with no or falsy reason'));
+ });
+ } else {
+ if (self.asyncOnly) {
+ return done(new Error('--async-only option in use without declaring `done()` or returning a promise'));
+ }
+
+ done();
+ }
+ }
+
+ function callFnAsync(fn) {
+ var result = fn.call(ctx, function (err) {
+ if (err instanceof Error || toString.call(err) === '[object Error]') {
+ return done(err);
+ }
+
+ if (err) {
+ if (Object.prototype.toString.call(err) === '[object Object]') {
+ return done(new Error('done() invoked with non-Error: ' + JSON.stringify(err)));
+ }
+
+ return done(new Error('done() invoked with non-Error: ' + err));
+ }
+
+ if (result && utils.isPromise(result)) {
+ return done(new Error('Resolution method is overspecified. Specify a callback *or* return a Promise; not both.'));
+ }
+
+ done();
+ });
+ }
+ };
+ /**
+ * Instantiates a "timeout" error
+ *
+ * @param {number} ms - Timeout (in milliseconds)
+ * @returns {Error} a "timeout" error
+ * @private
+ */
+
+
+ Runnable.prototype._timeoutError = function (ms) {
+ var msg = "Timeout of ".concat(ms, "ms exceeded. For async tests and hooks, ensure \"done()\" is called; if returning a Promise, ensure it resolves.");
+
+ if (this.file) {
+ msg += ' (' + this.file + ')';
+ }
+
+ return createTimeoutError(msg, ms, this.file);
+ };
+
+ var constants$3 = utils.defineConstants(
+ /**
+ * {@link Runnable}-related constants.
+ * @public
+ * @memberof Runnable
+ * @readonly
+ * @static
+ * @alias constants
+ * @enum {string}
+ */
+ {
+ /**
+ * Value of `state` prop when a `Runnable` has failed
+ */
+ STATE_FAILED: 'failed',
+
+ /**
+ * Value of `state` prop when a `Runnable` has passed
+ */
+ STATE_PASSED: 'passed',
+
+ /**
+ * Value of `state` prop when a `Runnable` has been skipped by user
+ */
+ STATE_PENDING: 'pending'
+ });
+ /**
+ * Given `value`, return identity if truthy, otherwise create an "invalid exception" error and return that.
+ * @param {*} [value] - Value to return, if present
+ * @returns {*|Error} `value`, otherwise an `Error`
+ * @private
+ */
+
+ Runnable.toValueOrError = function (value) {
+ return value || createInvalidExceptionError$1('Runnable failed with falsy or undefined exception. Please throw an Error instead.', value);
+ };
+
+ Runnable.constants = constants$3;
+
+ var inherits = utils.inherits,
+ constants$2 = utils.constants;
+ var MOCHA_ID_PROP_NAME$1 = constants$2.MOCHA_ID_PROP_NAME;
+ /**
+ * Expose `Hook`.
+ */
+
+ var hook = Hook;
+ /**
+ * Initialize a new `Hook` with the given `title` and callback `fn`
+ *
+ * @class
+ * @extends Runnable
+ * @param {String} title
+ * @param {Function} fn
+ */
+
+ function Hook(title, fn) {
+ runnable.call(this, title, fn);
+ this.type = 'hook';
+ }
+ /**
+ * Inherit from `Runnable.prototype`.
+ */
+
+
+ inherits(Hook, runnable);
+ /**
+ * Resets the state for a next run.
+ */
+
+ Hook.prototype.reset = function () {
+ runnable.prototype.reset.call(this);
+ delete this._error;
+ };
+ /**
+ * Get or set the test `err`.
+ *
+ * @memberof Hook
+ * @public
+ * @param {Error} err
+ * @return {Error}
+ */
+
+
+ Hook.prototype.error = function (err) {
+ if (!arguments.length) {
+ err = this._error;
+ this._error = null;
+ return err;
+ }
+
+ this._error = err;
+ };
+ /**
+ * Returns an object suitable for IPC.
+ * Functions are represented by keys beginning with `$$`.
+ * @private
+ * @returns {Object}
+ */
+
+
+ Hook.prototype.serialize = function serialize() {
+ return _defineProperty({
+ $$currentRetry: this.currentRetry(),
+ $$fullTitle: this.fullTitle(),
+ $$isPending: Boolean(this.isPending()),
+ $$titlePath: this.titlePath(),
+ ctx: this.ctx && this.ctx.currentTest ? {
+ currentTest: _defineProperty({
+ title: this.ctx.currentTest.title
+ }, MOCHA_ID_PROP_NAME$1, this.ctx.currentTest.id)
+ } : {},
+ duration: this.duration,
+ file: this.file,
+ parent: _defineProperty({
+ $$fullTitle: this.parent.fullTitle()
+ }, MOCHA_ID_PROP_NAME$1, this.parent.id),
+ state: this.state,
+ title: this.title,
+ type: this.type
+ }, MOCHA_ID_PROP_NAME$1, this.id);
+ };
+
+ var suite = createCommonjsModule(function (module, exports) {
+ /**
+ * Module dependencies.
+ * @private
+ */
+
+ var EventEmitter = EventEmitter$2.EventEmitter;
+ var assignNewMochaID = utils.assignNewMochaID,
+ clamp = utils.clamp,
+ utilsConstants = utils.constants,
+ createMap = utils.createMap,
+ defineConstants = utils.defineConstants,
+ getMochaID = utils.getMochaID,
+ inherits = utils.inherits,
+ isString = utils.isString;
+ var debug = browser('mocha:suite');
+ var MOCHA_ID_PROP_NAME = utilsConstants.MOCHA_ID_PROP_NAME;
+ /**
+ * Expose `Suite`.
+ */
+
+ module.exports = Suite;
+ /**
+ * Create a new `Suite` with the given `title` and parent `Suite`.
+ *
+ * @public
+ * @param {Suite} parent - Parent suite (required!)
+ * @param {string} title - Title
+ * @return {Suite}
+ */
+
+ Suite.create = function (parent, title) {
+ var suite = new Suite(title, parent.ctx);
+ suite.parent = parent;
+ title = suite.fullTitle();
+ parent.addSuite(suite);
+ return suite;
+ };
+ /**
+ * Constructs a new `Suite` instance with the given `title`, `ctx`, and `isRoot`.
+ *
+ * @public
+ * @class
+ * @extends EventEmitter
+ * @see {@link https://nodejs.org/api/events.html#events_class_eventemitter|EventEmitter}
+ * @param {string} title - Suite title.
+ * @param {Context} parentContext - Parent context instance.
+ * @param {boolean} [isRoot=false] - Whether this is the root suite.
+ */
+
+
+ function Suite(title, parentContext, isRoot) {
+ if (!isString(title)) {
+ throw errors.createInvalidArgumentTypeError('Suite argument "title" must be a string. Received type "' + _typeof(title) + '"', 'title', 'string');
+ }
+
+ this.title = title;
+
+ function Context() {}
+
+ Context.prototype = parentContext;
+ this.ctx = new Context();
+ this.suites = [];
+ this.tests = [];
+ this.root = isRoot === true;
+ this.pending = false;
+ this._retries = -1;
+ this._beforeEach = [];
+ this._beforeAll = [];
+ this._afterEach = [];
+ this._afterAll = [];
+ this._timeout = 2000;
+ this._slow = 75;
+ this._bail = false;
+ this._onlyTests = [];
+ this._onlySuites = [];
+ assignNewMochaID(this);
+ Object.defineProperty(this, 'id', {
+ get: function get() {
+ return getMochaID(this);
+ }
+ });
+ this.reset();
+ this.on('newListener', function (event) {
+ if (deprecatedEvents[event]) {
+ errors.deprecate('Event "' + event + '" is deprecated. Please let the Mocha team know about your use case: https://git.io/v6Lwm');
+ }
+ });
+ }
+ /**
+ * Inherit from `EventEmitter.prototype`.
+ */
+
+
+ inherits(Suite, EventEmitter);
+ /**
+ * Resets the state initially or for a next run.
+ */
+
+ Suite.prototype.reset = function () {
+ this.delayed = false;
+
+ function doReset(thingToReset) {
+ thingToReset.reset();
+ }
+
+ this.suites.forEach(doReset);
+ this.tests.forEach(doReset);
+
+ this._beforeEach.forEach(doReset);
+
+ this._afterEach.forEach(doReset);
+
+ this._beforeAll.forEach(doReset);
+
+ this._afterAll.forEach(doReset);
+ };
+ /**
+ * Return a clone of this `Suite`.
+ *
+ * @private
+ * @return {Suite}
+ */
+
+
+ Suite.prototype.clone = function () {
+ var suite = new Suite(this.title);
+ debug('clone');
+ suite.ctx = this.ctx;
+ suite.root = this.root;
+ suite.timeout(this.timeout());
+ suite.retries(this.retries());
+ suite.slow(this.slow());
+ suite.bail(this.bail());
+ return suite;
+ };
+ /**
+ * Set or get timeout `ms` or short-hand such as "2s".
+ *
+ * @private
+ * @todo Do not attempt to set value if `ms` is undefined
+ * @param {number|string} ms
+ * @return {Suite|number} for chaining
+ */
+
+
+ Suite.prototype.timeout = function (ms) {
+ if (!arguments.length) {
+ return this._timeout;
+ }
+
+ if (typeof ms === 'string') {
+ ms = ms$1(ms);
+ } // Clamp to range
+
+
+ var INT_MAX = Math.pow(2, 31) - 1;
+ var range = [0, INT_MAX];
+ ms = clamp(ms, range);
+ debug('timeout %d', ms);
+ this._timeout = parseInt(ms, 10);
+ return this;
+ };
+ /**
+ * Set or get number of times to retry a failed test.
+ *
+ * @private
+ * @param {number|string} n
+ * @return {Suite|number} for chaining
+ */
+
+
+ Suite.prototype.retries = function (n) {
+ if (!arguments.length) {
+ return this._retries;
+ }
+
+ debug('retries %d', n);
+ this._retries = parseInt(n, 10) || 0;
+ return this;
+ };
+ /**
+ * Set or get slow `ms` or short-hand such as "2s".
+ *
+ * @private
+ * @param {number|string} ms
+ * @return {Suite|number} for chaining
+ */
+
+
+ Suite.prototype.slow = function (ms) {
+ if (!arguments.length) {
+ return this._slow;
+ }
+
+ if (typeof ms === 'string') {
+ ms = ms$1(ms);
+ }
+
+ debug('slow %d', ms);
+ this._slow = ms;
+ return this;
+ };
+ /**
+ * Set or get whether to bail after first error.
+ *
+ * @private
+ * @param {boolean} bail
+ * @return {Suite|number} for chaining
+ */
+
+
+ Suite.prototype.bail = function (bail) {
+ if (!arguments.length) {
+ return this._bail;
+ }
+
+ debug('bail %s', bail);
+ this._bail = bail;
+ return this;
+ };
+ /**
+ * Check if this suite or its parent suite is marked as pending.
+ *
+ * @private
+ */
+
+
+ Suite.prototype.isPending = function () {
+ return this.pending || this.parent && this.parent.isPending();
+ };
+ /**
+ * Generic hook-creator.
+ * @private
+ * @param {string} title - Title of hook
+ * @param {Function} fn - Hook callback
+ * @returns {Hook} A new hook
+ */
+
+
+ Suite.prototype._createHook = function (title, fn) {
+ var hook$1 = new hook(title, fn);
+ hook$1.parent = this;
+ hook$1.timeout(this.timeout());
+ hook$1.retries(this.retries());
+ hook$1.slow(this.slow());
+ hook$1.ctx = this.ctx;
+ hook$1.file = this.file;
+ return hook$1;
+ };
+ /**
+ * Run `fn(test[, done])` before running tests.
+ *
+ * @private
+ * @param {string} title
+ * @param {Function} fn
+ * @return {Suite} for chaining
+ */
+
+
+ Suite.prototype.beforeAll = function (title, fn) {
+ if (this.isPending()) {
+ return this;
+ }
+
+ if (typeof title === 'function') {
+ fn = title;
+ title = fn.name;
+ }
+
+ title = '"before all" hook' + (title ? ': ' + title : '');
+
+ var hook = this._createHook(title, fn);
+
+ this._beforeAll.push(hook);
+
+ this.emit(constants.EVENT_SUITE_ADD_HOOK_BEFORE_ALL, hook);
+ return this;
+ };
+ /**
+ * Run `fn(test[, done])` after running tests.
+ *
+ * @private
+ * @param {string} title
+ * @param {Function} fn
+ * @return {Suite} for chaining
+ */
+
+
+ Suite.prototype.afterAll = function (title, fn) {
+ if (this.isPending()) {
+ return this;
+ }
+
+ if (typeof title === 'function') {
+ fn = title;
+ title = fn.name;
+ }
+
+ title = '"after all" hook' + (title ? ': ' + title : '');
+
+ var hook = this._createHook(title, fn);
+
+ this._afterAll.push(hook);
+
+ this.emit(constants.EVENT_SUITE_ADD_HOOK_AFTER_ALL, hook);
+ return this;
+ };
+ /**
+ * Run `fn(test[, done])` before each test case.
+ *
+ * @private
+ * @param {string} title
+ * @param {Function} fn
+ * @return {Suite} for chaining
+ */
+
+
+ Suite.prototype.beforeEach = function (title, fn) {
+ if (this.isPending()) {
+ return this;
+ }
+
+ if (typeof title === 'function') {
+ fn = title;
+ title = fn.name;
+ }
+
+ title = '"before each" hook' + (title ? ': ' + title : '');
+
+ var hook = this._createHook(title, fn);
+
+ this._beforeEach.push(hook);
+
+ this.emit(constants.EVENT_SUITE_ADD_HOOK_BEFORE_EACH, hook);
+ return this;
+ };
+ /**
+ * Run `fn(test[, done])` after each test case.
+ *
+ * @private
+ * @param {string} title
+ * @param {Function} fn
+ * @return {Suite} for chaining
+ */
+
+
+ Suite.prototype.afterEach = function (title, fn) {
+ if (this.isPending()) {
+ return this;
+ }
+
+ if (typeof title === 'function') {
+ fn = title;
+ title = fn.name;
+ }
+
+ title = '"after each" hook' + (title ? ': ' + title : '');
+
+ var hook = this._createHook(title, fn);
+
+ this._afterEach.push(hook);
+
+ this.emit(constants.EVENT_SUITE_ADD_HOOK_AFTER_EACH, hook);
+ return this;
+ };
+ /**
+ * Add a test `suite`.
+ *
+ * @private
+ * @param {Suite} suite
+ * @return {Suite} for chaining
+ */
+
+
+ Suite.prototype.addSuite = function (suite) {
+ suite.parent = this;
+ suite.root = false;
+ suite.timeout(this.timeout());
+ suite.retries(this.retries());
+ suite.slow(this.slow());
+ suite.bail(this.bail());
+ this.suites.push(suite);
+ this.emit(constants.EVENT_SUITE_ADD_SUITE, suite);
+ return this;
+ };
+ /**
+ * Add a `test` to this suite.
+ *
+ * @private
+ * @param {Test} test
+ * @return {Suite} for chaining
+ */
+
+
+ Suite.prototype.addTest = function (test) {
+ test.parent = this;
+ test.timeout(this.timeout());
+ test.retries(this.retries());
+ test.slow(this.slow());
+ test.ctx = this.ctx;
+ this.tests.push(test);
+ this.emit(constants.EVENT_SUITE_ADD_TEST, test);
+ return this;
+ };
+ /**
+ * Return the full title generated by recursively concatenating the parent's
+ * full title.
+ *
+ * @memberof Suite
+ * @public
+ * @return {string}
+ */
+
+
+ Suite.prototype.fullTitle = function () {
+ return this.titlePath().join(' ');
+ };
+ /**
+ * Return the title path generated by recursively concatenating the parent's
+ * title path.
+ *
+ * @memberof Suite
+ * @public
+ * @return {string}
+ */
+
+
+ Suite.prototype.titlePath = function () {
+ var result = [];
+
+ if (this.parent) {
+ result = result.concat(this.parent.titlePath());
+ }
+
+ if (!this.root) {
+ result.push(this.title);
+ }
+
+ return result;
+ };
+ /**
+ * Return the total number of tests.
+ *
+ * @memberof Suite
+ * @public
+ * @return {number}
+ */
+
+
+ Suite.prototype.total = function () {
+ return this.suites.reduce(function (sum, suite) {
+ return sum + suite.total();
+ }, 0) + this.tests.length;
+ };
+ /**
+ * Iterates through each suite recursively to find all tests. Applies a
+ * function in the format `fn(test)`.
+ *
+ * @private
+ * @param {Function} fn
+ * @return {Suite}
+ */
+
+
+ Suite.prototype.eachTest = function (fn) {
+ this.tests.forEach(fn);
+ this.suites.forEach(function (suite) {
+ suite.eachTest(fn);
+ });
+ return this;
+ };
+ /**
+ * This will run the root suite if we happen to be running in delayed mode.
+ * @private
+ */
+
+
+ Suite.prototype.run = function run() {
+ if (this.root) {
+ this.emit(constants.EVENT_ROOT_SUITE_RUN);
+ }
+ };
+ /**
+ * Determines whether a suite has an `only` test or suite as a descendant.
+ *
+ * @private
+ * @returns {Boolean}
+ */
+
+
+ Suite.prototype.hasOnly = function hasOnly() {
+ return this._onlyTests.length > 0 || this._onlySuites.length > 0 || this.suites.some(function (suite) {
+ return suite.hasOnly();
+ });
+ };
+ /**
+ * Filter suites based on `isOnly` logic.
+ *
+ * @private
+ * @returns {Boolean}
+ */
+
+
+ Suite.prototype.filterOnly = function filterOnly() {
+ if (this._onlyTests.length) {
+ // If the suite contains `only` tests, run those and ignore any nested suites.
+ this.tests = this._onlyTests;
+ this.suites = [];
+ } else {
+ // Otherwise, do not run any of the tests in this suite.
+ this.tests = [];
+
+ this._onlySuites.forEach(function (onlySuite) {
+ // If there are other `only` tests/suites nested in the current `only` suite, then filter that `only` suite.
+ // Otherwise, all of the tests on this `only` suite should be run, so don't filter it.
+ if (onlySuite.hasOnly()) {
+ onlySuite.filterOnly();
+ }
+ }); // Run the `only` suites, as well as any other suites that have `only` tests/suites as descendants.
+
+
+ var onlySuites = this._onlySuites;
+ this.suites = this.suites.filter(function (childSuite) {
+ return onlySuites.indexOf(childSuite) !== -1 || childSuite.filterOnly();
+ });
+ } // Keep the suite only if there is something to run
+
+
+ return this.tests.length > 0 || this.suites.length > 0;
+ };
+ /**
+ * Adds a suite to the list of subsuites marked `only`.
+ *
+ * @private
+ * @param {Suite} suite
+ */
+
+
+ Suite.prototype.appendOnlySuite = function (suite) {
+ this._onlySuites.push(suite);
+ };
+ /**
+ * Marks a suite to be `only`.
+ *
+ * @private
+ */
+
+
+ Suite.prototype.markOnly = function () {
+ this.parent && this.parent.appendOnlySuite(this);
+ };
+ /**
+ * Adds a test to the list of tests marked `only`.
+ *
+ * @private
+ * @param {Test} test
+ */
+
+
+ Suite.prototype.appendOnlyTest = function (test) {
+ this._onlyTests.push(test);
+ };
+ /**
+ * Returns the array of hooks by hook name; see `HOOK_TYPE_*` constants.
+ * @private
+ */
+
+
+ Suite.prototype.getHooks = function getHooks(name) {
+ return this['_' + name];
+ };
+ /**
+ * cleans all references from this suite and all child suites.
+ */
+
+
+ Suite.prototype.dispose = function () {
+ this.suites.forEach(function (suite) {
+ suite.dispose();
+ });
+ this.cleanReferences();
+ };
+ /**
+ * Cleans up the references to all the deferred functions
+ * (before/after/beforeEach/afterEach) and tests of a Suite.
+ * These must be deleted otherwise a memory leak can happen,
+ * as those functions may reference variables from closures,
+ * thus those variables can never be garbage collected as long
+ * as the deferred functions exist.
+ *
+ * @private
+ */
+
+
+ Suite.prototype.cleanReferences = function cleanReferences() {
+ function cleanArrReferences(arr) {
+ for (var i = 0; i < arr.length; i++) {
+ delete arr[i].fn;
+ }
+ }
+
+ if (Array.isArray(this._beforeAll)) {
+ cleanArrReferences(this._beforeAll);
+ }
+
+ if (Array.isArray(this._beforeEach)) {
+ cleanArrReferences(this._beforeEach);
+ }
+
+ if (Array.isArray(this._afterAll)) {
+ cleanArrReferences(this._afterAll);
+ }
+
+ if (Array.isArray(this._afterEach)) {
+ cleanArrReferences(this._afterEach);
+ }
+
+ for (var i = 0; i < this.tests.length; i++) {
+ delete this.tests[i].fn;
+ }
+ };
+ /**
+ * Returns an object suitable for IPC.
+ * Functions are represented by keys beginning with `$$`.
+ * @private
+ * @returns {Object}
+ */
+
+
+ Suite.prototype.serialize = function serialize() {
+ var _ref2;
+
+ return _ref2 = {
+ _bail: this._bail,
+ $$fullTitle: this.fullTitle(),
+ $$isPending: Boolean(this.isPending()),
+ root: this.root,
+ title: this.title
+ }, _defineProperty(_ref2, MOCHA_ID_PROP_NAME, this.id), _defineProperty(_ref2, "parent", this.parent ? _defineProperty({}, MOCHA_ID_PROP_NAME, this.parent.id) : null), _ref2;
+ };
+
+ var constants = defineConstants(
+ /**
+ * {@link Suite}-related constants.
+ * @public
+ * @memberof Suite
+ * @alias constants
+ * @readonly
+ * @static
+ * @enum {string}
+ */
+ {
+ /**
+ * Event emitted after a test file has been loaded Not emitted in browser.
+ */
+ EVENT_FILE_POST_REQUIRE: 'post-require',
+
+ /**
+ * Event emitted before a test file has been loaded. In browser, this is emitted once an interface has been selected.
+ */
+ EVENT_FILE_PRE_REQUIRE: 'pre-require',
+
+ /**
+ * Event emitted immediately after a test file has been loaded. Not emitted in browser.
+ */
+ EVENT_FILE_REQUIRE: 'require',
+
+ /**
+ * Event emitted when `global.run()` is called (use with `delay` option)
+ */
+ EVENT_ROOT_SUITE_RUN: 'run',
+
+ /**
+ * Namespace for collection of a `Suite`'s "after all" hooks
+ */
+ HOOK_TYPE_AFTER_ALL: 'afterAll',
+
+ /**
+ * Namespace for collection of a `Suite`'s "after each" hooks
+ */
+ HOOK_TYPE_AFTER_EACH: 'afterEach',
+
+ /**
+ * Namespace for collection of a `Suite`'s "before all" hooks
+ */
+ HOOK_TYPE_BEFORE_ALL: 'beforeAll',
+
+ /**
+ * Namespace for collection of a `Suite`'s "before all" hooks
+ */
+ HOOK_TYPE_BEFORE_EACH: 'beforeEach',
+ // the following events are all deprecated
+
+ /**
+ * Emitted after an "after all" `Hook` has been added to a `Suite`. Deprecated
+ */
+ EVENT_SUITE_ADD_HOOK_AFTER_ALL: 'afterAll',
+
+ /**
+ * Emitted after an "after each" `Hook` has been added to a `Suite` Deprecated
+ */
+ EVENT_SUITE_ADD_HOOK_AFTER_EACH: 'afterEach',
+
+ /**
+ * Emitted after an "before all" `Hook` has been added to a `Suite` Deprecated
+ */
+ EVENT_SUITE_ADD_HOOK_BEFORE_ALL: 'beforeAll',
+
+ /**
+ * Emitted after an "before each" `Hook` has been added to a `Suite` Deprecated
+ */
+ EVENT_SUITE_ADD_HOOK_BEFORE_EACH: 'beforeEach',
+
+ /**
+ * Emitted after a child `Suite` has been added to a `Suite`. Deprecated
+ */
+ EVENT_SUITE_ADD_SUITE: 'suite',
+
+ /**
+ * Emitted after a `Test` has been added to a `Suite`. Deprecated
+ */
+ EVENT_SUITE_ADD_TEST: 'test'
+ });
+ /**
+ * @summary There are no known use cases for these events.
+ * @desc This is a `Set`-like object having all keys being the constant's string value and the value being `true`.
+ * @todo Remove eventually
+ * @type {Object}
+ * @ignore
+ */
+
+ var deprecatedEvents = Object.keys(constants).filter(function (constant) {
+ return constant.substring(0, 15) === 'EVENT_SUITE_ADD';
+ }).reduce(function (acc, constant) {
+ acc[constants[constant]] = true;
+ return acc;
+ }, createMap());
+ Suite.constants = constants;
+ });
+
+ /**
+ * Module dependencies.
+ * @private
+ */
+
+
+ var EventEmitter = EventEmitter$2.EventEmitter;
+ var debug = browser('mocha:runner');
+ var HOOK_TYPE_BEFORE_EACH = suite.constants.HOOK_TYPE_BEFORE_EACH;
+ var HOOK_TYPE_AFTER_EACH = suite.constants.HOOK_TYPE_AFTER_EACH;
+ var HOOK_TYPE_AFTER_ALL = suite.constants.HOOK_TYPE_AFTER_ALL;
+ var HOOK_TYPE_BEFORE_ALL = suite.constants.HOOK_TYPE_BEFORE_ALL;
+ var EVENT_ROOT_SUITE_RUN = suite.constants.EVENT_ROOT_SUITE_RUN;
+ var STATE_FAILED = runnable.constants.STATE_FAILED;
+ var STATE_PASSED = runnable.constants.STATE_PASSED;
+ var STATE_PENDING = runnable.constants.STATE_PENDING;
+ var stackFilter = utils.stackTraceFilter();
+ var stringify = utils.stringify;
+ var createInvalidExceptionError = errors.createInvalidExceptionError,
+ createUnsupportedError$1 = errors.createUnsupportedError,
+ createFatalError = errors.createFatalError,
+ isMochaError = errors.isMochaError,
+ errorConstants = errors.constants;
+ /**
+ * Non-enumerable globals.
+ * @private
+ * @readonly
+ */
+
+ var globals = ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'XMLHttpRequest', 'Date', 'setImmediate', 'clearImmediate'];
+ var constants$1 = utils.defineConstants(
+ /**
+ * {@link Runner}-related constants.
+ * @public
+ * @memberof Runner
+ * @readonly
+ * @alias constants
+ * @static
+ * @enum {string}
+ */
+ {
+ /**
+ * Emitted when {@link Hook} execution begins
+ */
+ EVENT_HOOK_BEGIN: 'hook',
+
+ /**
+ * Emitted when {@link Hook} execution ends
+ */
+ EVENT_HOOK_END: 'hook end',
+
+ /**
+ * Emitted when Root {@link Suite} execution begins (all files have been parsed and hooks/tests are ready for execution)
+ */
+ EVENT_RUN_BEGIN: 'start',
+
+ /**
+ * Emitted when Root {@link Suite} execution has been delayed via `delay` option
+ */
+ EVENT_DELAY_BEGIN: 'waiting',
+
+ /**
+ * Emitted when delayed Root {@link Suite} execution is triggered by user via `global.run()`
+ */
+ EVENT_DELAY_END: 'ready',
+
+ /**
+ * Emitted when Root {@link Suite} execution ends
+ */
+ EVENT_RUN_END: 'end',
+
+ /**
+ * Emitted when {@link Suite} execution begins
+ */
+ EVENT_SUITE_BEGIN: 'suite',
+
+ /**
+ * Emitted when {@link Suite} execution ends
+ */
+ EVENT_SUITE_END: 'suite end',
+
+ /**
+ * Emitted when {@link Test} execution begins
+ */
+ EVENT_TEST_BEGIN: 'test',
+
+ /**
+ * Emitted when {@link Test} execution ends
+ */
+ EVENT_TEST_END: 'test end',
+
+ /**
+ * Emitted when {@link Test} execution fails
+ */
+ EVENT_TEST_FAIL: 'fail',
+
+ /**
+ * Emitted when {@link Test} execution succeeds
+ */
+ EVENT_TEST_PASS: 'pass',
+
+ /**
+ * Emitted when {@link Test} becomes pending
+ */
+ EVENT_TEST_PENDING: 'pending',
+
+ /**
+ * Emitted when {@link Test} execution has failed, but will retry
+ */
+ EVENT_TEST_RETRY: 'retry',
+
+ /**
+ * Initial state of Runner
+ */
+ STATE_IDLE: 'idle',
+
+ /**
+ * State set to this value when the Runner has started running
+ */
+ STATE_RUNNING: 'running',
+
+ /**
+ * State set to this value when the Runner has stopped
+ */
+ STATE_STOPPED: 'stopped'
+ });
+
+ var Runner = /*#__PURE__*/function (_EventEmitter) {
+ _inherits(Runner, _EventEmitter);
+
+ var _super = _createSuper(Runner);
+
+ /**
+ * Initialize a `Runner` at the Root {@link Suite}, which represents a hierarchy of {@link Suite|Suites} and {@link Test|Tests}.
+ *
+ * @extends external:EventEmitter
+ * @public
+ * @class
+ * @param {Suite} suite - Root suite
+ * @param {Object|boolean} [opts] - Options. If `boolean` (deprecated), whether to delay execution of root suite until ready.
+ * @param {boolean} [opts.cleanReferencesAfterRun] - Whether to clean references to test fns and hooks when a suite is done.
+ * @param {boolean} [opts.delay] - Whether to delay execution of root suite until ready.
+ * @param {boolean} [opts.dryRun] - Whether to report tests without running them.
+ * @param {boolean} [options.failZero] - Whether to fail test run if zero tests encountered.
+ */
+ function Runner(suite, opts) {
+ var _this;
+
+ _classCallCheck(this, Runner);
+
+ _this = _super.call(this);
+
+ if (opts === undefined) {
+ opts = {};
+ }
+
+ if (typeof opts === 'boolean') {
+ // TODO: remove this
+ errors.deprecate('"Runner(suite: Suite, delay: boolean)" is deprecated. Use "Runner(suite: Suite, {delay: boolean})" instead.');
+ _this._delay = opts;
+ opts = {};
+ } else {
+ _this._delay = opts.delay;
+ }
+
+ var self = _assertThisInitialized(_this);
+
+ _this._globals = [];
+ _this._abort = false;
+ _this.suite = suite;
+ _this._opts = opts;
+ _this.state = constants$1.STATE_IDLE;
+ _this.total = suite.total();
+ _this.failures = 0;
+ /**
+ * @type {Map>>}
+ */
+
+ _this._eventListeners = new Map();
+
+ _this.on(constants$1.EVENT_TEST_END, function (test) {
+ if (test.type === 'test' && test.retriedTest() && test.parent) {
+ var idx = test.parent.tests && test.parent.tests.indexOf(test.retriedTest());
+ if (idx > -1) test.parent.tests[idx] = test;
+ }
+
+ self.checkGlobals(test);
+ });
+
+ _this.on(constants$1.EVENT_HOOK_END, function (hook) {
+ self.checkGlobals(hook);
+ });
+
+ _this._defaultGrep = /.*/;
+
+ _this.grep(_this._defaultGrep);
+
+ _this.globals(_this.globalProps());
+
+ _this.uncaught = _this._uncaught.bind(_assertThisInitialized(_this));
+
+ _this.unhandled = function (reason, promise) {
+ if (isMochaError(reason)) {
+ debug('trapped unhandled rejection coming out of Mocha; forwarding to uncaught handler:', reason);
+
+ _this.uncaught(reason);
+ } else {
+ debug('trapped unhandled rejection from (probably) user code; re-emitting on process');
+
+ _this._removeEventListener(process$4, 'unhandledRejection', _this.unhandled);
+
+ try {
+ process$4.emit('unhandledRejection', reason, promise);
+ } finally {
+ _this._addEventListener(process$4, 'unhandledRejection', _this.unhandled);
+ }
+ }
+ };
+
+ return _this;
+ }
+
+ return Runner;
+ }(EventEmitter);
+ /**
+ * Wrapper for setImmediate, process.nextTick, or browser polyfill.
+ *
+ * @param {Function} fn
+ * @private
+ */
+
+
+ Runner.immediately = commonjsGlobal.setImmediate || nextTick$1;
+ /**
+ * Replacement for `target.on(eventName, listener)` that does bookkeeping to remove them when this runner instance is disposed.
+ * @param {EventEmitter} target - The `EventEmitter`
+ * @param {string} eventName - The event name
+ * @param {string} fn - Listener function
+ * @private
+ */
+
+ Runner.prototype._addEventListener = function (target, eventName, listener) {
+ debug('_addEventListener(): adding for event %s; %d current listeners', eventName, target.listenerCount(eventName));
+ /* istanbul ignore next */
+
+ if (this._eventListeners.has(target) && this._eventListeners.get(target).has(eventName) && this._eventListeners.get(target).get(eventName).has(listener)) {
+ debug('warning: tried to attach duplicate event listener for %s', eventName);
+ return;
+ }
+
+ target.on(eventName, listener);
+ var targetListeners = this._eventListeners.has(target) ? this._eventListeners.get(target) : new Map();
+ var targetEventListeners = targetListeners.has(eventName) ? targetListeners.get(eventName) : new Set();
+ targetEventListeners.add(listener);
+ targetListeners.set(eventName, targetEventListeners);
+
+ this._eventListeners.set(target, targetListeners);
+ };
+ /**
+ * Replacement for `target.removeListener(eventName, listener)` that also updates the bookkeeping.
+ * @param {EventEmitter} target - The `EventEmitter`
+ * @param {string} eventName - The event name
+ * @param {function} listener - Listener function
+ * @private
+ */
+
+
+ Runner.prototype._removeEventListener = function (target, eventName, listener) {
+ target.removeListener(eventName, listener);
+
+ if (this._eventListeners.has(target)) {
+ var targetListeners = this._eventListeners.get(target);
+
+ if (targetListeners.has(eventName)) {
+ var targetEventListeners = targetListeners.get(eventName);
+ targetEventListeners["delete"](listener);
+
+ if (!targetEventListeners.size) {
+ targetListeners["delete"](eventName);
+ }
+ }
+
+ if (!targetListeners.size) {
+ this._eventListeners["delete"](target);
+ }
+ } else {
+ debug('trying to remove listener for untracked object %s', target);
+ }
+ };
+ /**
+ * Removes all event handlers set during a run on this instance.
+ * Remark: this does _not_ clean/dispose the tests or suites themselves.
+ */
+
+
+ Runner.prototype.dispose = function () {
+ this.removeAllListeners();
+
+ this._eventListeners.forEach(function (targetListeners, target) {
+ targetListeners.forEach(function (targetEventListeners, eventName) {
+ targetEventListeners.forEach(function (listener) {
+ target.removeListener(eventName, listener);
+ });
+ });
+ });
+
+ this._eventListeners.clear();
+ };
+ /**
+ * Run tests with full titles matching `re`. Updates runner.total
+ * with number of tests matched.
+ *
+ * @public
+ * @memberof Runner
+ * @param {RegExp} re
+ * @param {boolean} invert
+ * @return {Runner} Runner instance.
+ */
+
+
+ Runner.prototype.grep = function (re, invert) {
+ debug('grep(): setting to %s', re);
+ this._grep = re;
+ this._invert = invert;
+ this.total = this.grepTotal(this.suite);
+ return this;
+ };
+ /**
+ * Returns the number of tests matching the grep search for the
+ * given suite.
+ *
+ * @memberof Runner
+ * @public
+ * @param {Suite} suite
+ * @return {number}
+ */
+
+
+ Runner.prototype.grepTotal = function (suite) {
+ var self = this;
+ var total = 0;
+ suite.eachTest(function (test) {
+ var match = self._grep.test(test.fullTitle());
+
+ if (self._invert) {
+ match = !match;
+ }
+
+ if (match) {
+ total++;
+ }
+ });
+ return total;
+ };
+ /**
+ * Return a list of global properties.
+ *
+ * @return {Array}
+ * @private
+ */
+
+
+ Runner.prototype.globalProps = function () {
+ var props = Object.keys(commonjsGlobal); // non-enumerables
+
+ for (var i = 0; i < globals.length; ++i) {
+ if (~props.indexOf(globals[i])) {
+ continue;
+ }
+
+ props.push(globals[i]);
+ }
+
+ return props;
+ };
+ /**
+ * Allow the given `arr` of globals.
+ *
+ * @public
+ * @memberof Runner
+ * @param {Array} arr
+ * @return {Runner} Runner instance.
+ */
+
+
+ Runner.prototype.globals = function (arr) {
+ if (!arguments.length) {
+ return this._globals;
+ }
+
+ debug('globals(): setting to %O', arr);
+ this._globals = this._globals.concat(arr);
+ return this;
+ };
+ /**
+ * Check for global variable leaks.
+ *
+ * @private
+ */
+
+
+ Runner.prototype.checkGlobals = function (test) {
+ if (!this.checkLeaks) {
+ return;
+ }
+
+ var ok = this._globals;
+ var globals = this.globalProps();
+ var leaks;
+
+ if (test) {
+ ok = ok.concat(test._allowedGlobals || []);
+ }
+
+ if (this.prevGlobalsLength === globals.length) {
+ return;
+ }
+
+ this.prevGlobalsLength = globals.length;
+ leaks = filterLeaks(ok, globals);
+ this._globals = this._globals.concat(leaks);
+
+ if (leaks.length) {
+ var msg = "global leak(s) detected: ".concat(leaks.map(function (e) {
+ return "'".concat(e, "'");
+ }).join(', '));
+ this.fail(test, new Error(msg));
+ }
+ };
+ /**
+ * Fail the given `test`.
+ *
+ * If `test` is a hook, failures work in the following pattern:
+ * - If bail, run corresponding `after each` and `after` hooks,
+ * then exit
+ * - Failed `before` hook skips all tests in a suite and subsuites,
+ * but jumps to corresponding `after` hook
+ * - Failed `before each` hook skips remaining tests in a
+ * suite and jumps to corresponding `after each` hook,
+ * which is run only once
+ * - Failed `after` hook does not alter execution order
+ * - Failed `after each` hook skips remaining tests in a
+ * suite and subsuites, but executes other `after each`
+ * hooks
+ *
+ * @private
+ * @param {Runnable} test
+ * @param {Error} err
+ * @param {boolean} [force=false] - Whether to fail a pending test.
+ */
+
+
+ Runner.prototype.fail = function (test, err, force) {
+ force = force === true;
+
+ if (test.isPending() && !force) {
+ return;
+ }
+
+ if (this.state === constants$1.STATE_STOPPED) {
+ if (err.code === errorConstants.MULTIPLE_DONE) {
+ throw err;
+ }
+
+ throw createFatalError('Test failed after root suite execution completed!', err);
+ }
+
+ ++this.failures;
+ debug('total number of failures: %d', this.failures);
+ test.state = STATE_FAILED;
+
+ if (!isError(err)) {
+ err = thrown2Error(err);
+ }
+
+ try {
+ err.stack = this.fullStackTrace || !err.stack ? err.stack : stackFilter(err.stack);
+ } catch (ignore) {// some environments do not take kindly to monkeying with the stack
+ }
+
+ this.emit(constants$1.EVENT_TEST_FAIL, test, err);
+ };
+ /**
+ * Run hook `name` callbacks and then invoke `fn()`.
+ *
+ * @private
+ * @param {string} name
+ * @param {Function} fn
+ */
+
+
+ Runner.prototype.hook = function (name, fn) {
+ if (this._opts.dryRun) return fn();
+ var suite = this.suite;
+ var hooks = suite.getHooks(name);
+ var self = this;
+
+ function next(i) {
+ var hook = hooks[i];
+
+ if (!hook) {
+ return fn();
+ }
+
+ self.currentRunnable = hook;
+
+ if (name === HOOK_TYPE_BEFORE_ALL) {
+ hook.ctx.currentTest = hook.parent.tests[0];
+ } else if (name === HOOK_TYPE_AFTER_ALL) {
+ hook.ctx.currentTest = hook.parent.tests[hook.parent.tests.length - 1];
+ } else {
+ hook.ctx.currentTest = self.test;
+ }
+
+ setHookTitle(hook);
+ hook.allowUncaught = self.allowUncaught;
+ self.emit(constants$1.EVENT_HOOK_BEGIN, hook);
+
+ if (!hook.listeners('error').length) {
+ self._addEventListener(hook, 'error', function (err) {
+ self.fail(hook, err);
+ });
+ }
+
+ hook.run(function cbHookRun(err) {
+ var testError = hook.error();
+
+ if (testError) {
+ self.fail(self.test, testError);
+ } // conditional skip
+
+
+ if (hook.pending) {
+ if (name === HOOK_TYPE_AFTER_EACH) {
+ // TODO define and implement use case
+ if (self.test) {
+ self.test.pending = true;
+ }
+ } else if (name === HOOK_TYPE_BEFORE_EACH) {
+ if (self.test) {
+ self.test.pending = true;
+ }
+
+ self.emit(constants$1.EVENT_HOOK_END, hook);
+ hook.pending = false; // activates hook for next test
+
+ return fn(new Error('abort hookDown'));
+ } else if (name === HOOK_TYPE_BEFORE_ALL) {
+ suite.tests.forEach(function (test) {
+ test.pending = true;
+ });
+ suite.suites.forEach(function (suite) {
+ suite.pending = true;
+ });
+ hooks = [];
+ } else {
+ hook.pending = false;
+ var errForbid = createUnsupportedError$1('`this.skip` forbidden');
+ self.fail(hook, errForbid);
+ return fn(errForbid);
+ }
+ } else if (err) {
+ self.fail(hook, err); // stop executing hooks, notify callee of hook err
+
+ return fn(err);
+ }
+
+ self.emit(constants$1.EVENT_HOOK_END, hook);
+ delete hook.ctx.currentTest;
+ setHookTitle(hook);
+ next(++i);
+ });
+
+ function setHookTitle(hook) {
+ hook.originalTitle = hook.originalTitle || hook.title;
+
+ if (hook.ctx && hook.ctx.currentTest) {
+ hook.title = "".concat(hook.originalTitle, " for \"").concat(hook.ctx.currentTest.title, "\"");
+ } else {
+ var parentTitle;
+
+ if (hook.parent.title) {
+ parentTitle = hook.parent.title;
+ } else {
+ parentTitle = hook.parent.root ? '{root}' : '';
+ }
+
+ hook.title = "".concat(hook.originalTitle, " in \"").concat(parentTitle, "\"");
+ }
+ }
+ }
+
+ Runner.immediately(function () {
+ next(0);
+ });
+ };
+ /**
+ * Run hook `name` for the given array of `suites`
+ * in order, and callback `fn(err, errSuite)`.
+ *
+ * @private
+ * @param {string} name
+ * @param {Array} suites
+ * @param {Function} fn
+ */
+
+
+ Runner.prototype.hooks = function (name, suites, fn) {
+ var self = this;
+ var orig = this.suite;
+
+ function next(suite) {
+ self.suite = suite;
+
+ if (!suite) {
+ self.suite = orig;
+ return fn();
+ }
+
+ self.hook(name, function (err) {
+ if (err) {
+ var errSuite = self.suite;
+ self.suite = orig;
+ return fn(err, errSuite);
+ }
+
+ next(suites.pop());
+ });
+ }
+
+ next(suites.pop());
+ };
+ /**
+ * Run 'afterEach' hooks from bottom up.
+ *
+ * @param {String} name
+ * @param {Function} fn
+ * @private
+ */
+
+
+ Runner.prototype.hookUp = function (name, fn) {
+ var suites = [this.suite].concat(this.parents()).reverse();
+ this.hooks(name, suites, fn);
+ };
+ /**
+ * Run 'beforeEach' hooks from top level down.
+ *
+ * @param {String} name
+ * @param {Function} fn
+ * @private
+ */
+
+
+ Runner.prototype.hookDown = function (name, fn) {
+ var suites = [this.suite].concat(this.parents());
+ this.hooks(name, suites, fn);
+ };
+ /**
+ * Return an array of parent Suites from
+ * closest to furthest.
+ *
+ * @return {Array}
+ * @private
+ */
+
+
+ Runner.prototype.parents = function () {
+ var suite = this.suite;
+ var suites = [];
+
+ while (suite.parent) {
+ suite = suite.parent;
+ suites.push(suite);
+ }
+
+ return suites;
+ };
+ /**
+ * Run the current test and callback `fn(err)`.
+ *
+ * @param {Function} fn
+ * @private
+ */
+
+
+ Runner.prototype.runTest = function (fn) {
+ if (this._opts.dryRun) return fn();
+ var self = this;
+ var test = this.test;
+
+ if (!test) {
+ return;
+ }
+
+ if (this.asyncOnly) {
+ test.asyncOnly = true;
+ }
+
+ this._addEventListener(test, 'error', function (err) {
+ self.fail(test, err);
+ });
+
+ if (this.allowUncaught) {
+ test.allowUncaught = true;
+ return test.run(fn);
+ }
+
+ try {
+ test.run(fn);
+ } catch (err) {
+ fn(err);
+ }
+ };
+ /**
+ * Run tests in the given `suite` and invoke the callback `fn()` when complete.
+ *
+ * @private
+ * @param {Suite} suite
+ * @param {Function} fn
+ */
+
+
+ Runner.prototype.runTests = function (suite, fn) {
+ var self = this;
+ var tests = suite.tests.slice();
+ var test;
+
+ function hookErr(_, errSuite, after) {
+ // before/after Each hook for errSuite failed:
+ var orig = self.suite; // for failed 'after each' hook start from errSuite parent,
+ // otherwise start from errSuite itself
+
+ self.suite = after ? errSuite.parent : errSuite;
+
+ if (self.suite) {
+ self.hookUp(HOOK_TYPE_AFTER_EACH, function (err2, errSuite2) {
+ self.suite = orig; // some hooks may fail even now
+
+ if (err2) {
+ return hookErr(err2, errSuite2, true);
+ } // report error suite
+
+
+ fn(errSuite);
+ });
+ } else {
+ // there is no need calling other 'after each' hooks
+ self.suite = orig;
+ fn(errSuite);
+ }
+ }
+
+ function next(err, errSuite) {
+ // if we bail after first err
+ if (self.failures && suite._bail) {
+ tests = [];
+ }
+
+ if (self._abort) {
+ return fn();
+ }
+
+ if (err) {
+ return hookErr(err, errSuite, true);
+ } // next test
+
+
+ test = tests.shift(); // all done
+
+ if (!test) {
+ return fn();
+ } // grep
+
+
+ var match = self._grep.test(test.fullTitle());
+
+ if (self._invert) {
+ match = !match;
+ }
+
+ if (!match) {
+ // Run immediately only if we have defined a grep. When we
+ // define a grep — It can cause maximum callstack error if
+ // the grep is doing a large recursive loop by neglecting
+ // all tests. The run immediately function also comes with
+ // a performance cost. So we don't want to run immediately
+ // if we run the whole test suite, because running the whole
+ // test suite don't do any immediate recursive loops. Thus,
+ // allowing a JS runtime to breathe.
+ if (self._grep !== self._defaultGrep) {
+ Runner.immediately(next);
+ } else {
+ next();
+ }
+
+ return;
+ } // static skip, no hooks are executed
+
+
+ if (test.isPending()) {
+ if (self.forbidPending) {
+ self.fail(test, new Error('Pending test forbidden'), true);
+ } else {
+ test.state = STATE_PENDING;
+ self.emit(constants$1.EVENT_TEST_PENDING, test);
+ }
+
+ self.emit(constants$1.EVENT_TEST_END, test);
+ return next();
+ } // execute test and hook(s)
+
+
+ self.emit(constants$1.EVENT_TEST_BEGIN, self.test = test);
+ self.hookDown(HOOK_TYPE_BEFORE_EACH, function (err, errSuite) {
+ // conditional skip within beforeEach
+ if (test.isPending()) {
+ if (self.forbidPending) {
+ self.fail(test, new Error('Pending test forbidden'), true);
+ } else {
+ test.state = STATE_PENDING;
+ self.emit(constants$1.EVENT_TEST_PENDING, test);
+ }
+
+ self.emit(constants$1.EVENT_TEST_END, test); // skip inner afterEach hooks below errSuite level
+
+ var origSuite = self.suite;
+ self.suite = errSuite || self.suite;
+ return self.hookUp(HOOK_TYPE_AFTER_EACH, function (e, eSuite) {
+ self.suite = origSuite;
+ next(e, eSuite);
+ });
+ }
+
+ if (err) {
+ return hookErr(err, errSuite, false);
+ }
+
+ self.currentRunnable = self.test;
+ self.runTest(function (err) {
+ test = self.test; // conditional skip within it
+
+ if (test.pending) {
+ if (self.forbidPending) {
+ self.fail(test, new Error('Pending test forbidden'), true);
+ } else {
+ test.state = STATE_PENDING;
+ self.emit(constants$1.EVENT_TEST_PENDING, test);
+ }
+
+ self.emit(constants$1.EVENT_TEST_END, test);
+ return self.hookUp(HOOK_TYPE_AFTER_EACH, next);
+ } else if (err) {
+ var retry = test.currentRetry();
+
+ if (retry < test.retries()) {
+ var clonedTest = test.clone();
+ clonedTest.currentRetry(retry + 1);
+ tests.unshift(clonedTest);
+ self.emit(constants$1.EVENT_TEST_RETRY, test, err); // Early return + hook trigger so that it doesn't
+ // increment the count wrong
+
+ return self.hookUp(HOOK_TYPE_AFTER_EACH, next);
+ } else {
+ self.fail(test, err);
+ }
+
+ self.emit(constants$1.EVENT_TEST_END, test);
+ return self.hookUp(HOOK_TYPE_AFTER_EACH, next);
+ }
+
+ test.state = STATE_PASSED;
+ self.emit(constants$1.EVENT_TEST_PASS, test);
+ self.emit(constants$1.EVENT_TEST_END, test);
+ self.hookUp(HOOK_TYPE_AFTER_EACH, next);
+ });
+ });
+ }
+
+ this.next = next;
+ this.hookErr = hookErr;
+ next();
+ };
+ /**
+ * Run the given `suite` and invoke the callback `fn()` when complete.
+ *
+ * @private
+ * @param {Suite} suite
+ * @param {Function} fn
+ */
+
+
+ Runner.prototype.runSuite = function (suite, fn) {
+ var i = 0;
+ var self = this;
+ var total = this.grepTotal(suite);
+ debug('runSuite(): running %s', suite.fullTitle());
+
+ if (!total || self.failures && suite._bail) {
+ debug('runSuite(): bailing');
+ return fn();
+ }
+
+ this.emit(constants$1.EVENT_SUITE_BEGIN, this.suite = suite);
+
+ function next(errSuite) {
+ if (errSuite) {
+ // current suite failed on a hook from errSuite
+ if (errSuite === suite) {
+ // if errSuite is current suite
+ // continue to the next sibling suite
+ return done();
+ } // errSuite is among the parents of current suite
+ // stop execution of errSuite and all sub-suites
+
+
+ return done(errSuite);
+ }
+
+ if (self._abort) {
+ return done();
+ }
+
+ var curr = suite.suites[i++];
+
+ if (!curr) {
+ return done();
+ } // Avoid grep neglecting large number of tests causing a
+ // huge recursive loop and thus a maximum call stack error.
+ // See comment in `this.runTests()` for more information.
+
+
+ if (self._grep !== self._defaultGrep) {
+ Runner.immediately(function () {
+ self.runSuite(curr, next);
+ });
+ } else {
+ self.runSuite(curr, next);
+ }
+ }
+
+ function done(errSuite) {
+ self.suite = suite;
+ self.nextSuite = next; // remove reference to test
+
+ delete self.test;
+ self.hook(HOOK_TYPE_AFTER_ALL, function () {
+ self.emit(constants$1.EVENT_SUITE_END, suite);
+ fn(errSuite);
+ });
+ }
+
+ this.nextSuite = next;
+ this.hook(HOOK_TYPE_BEFORE_ALL, function (err) {
+ if (err) {
+ return done();
+ }
+
+ self.runTests(suite, next);
+ });
+ };
+ /**
+ * Handle uncaught exceptions within runner.
+ *
+ * This function is bound to the instance as `Runner#uncaught` at instantiation
+ * time. It's intended to be listening on the `Process.uncaughtException` event.
+ * In order to not leak EE listeners, we need to ensure no more than a single
+ * `uncaughtException` listener exists per `Runner`. The only way to do
+ * this--because this function needs the context (and we don't have lambdas)--is
+ * to use `Function.prototype.bind`. We need strict equality to unregister and
+ * _only_ unregister the _one_ listener we set from the
+ * `Process.uncaughtException` event; would be poor form to just remove
+ * everything. See {@link Runner#run} for where the event listener is registered
+ * and unregistered.
+ * @param {Error} err - Some uncaught error
+ * @private
+ */
+
+
+ Runner.prototype._uncaught = function (err) {
+ // this is defensive to prevent future developers from mis-calling this function.
+ // it's more likely that it'd be called with the incorrect context--say, the global
+ // `process` object--than it would to be called with a context that is not a "subclass"
+ // of `Runner`.
+ if (!(this instanceof Runner)) {
+ throw createFatalError('Runner#uncaught() called with invalid context', this);
+ }
+
+ if (err instanceof pending) {
+ debug('uncaught(): caught a Pending');
+ return;
+ } // browser does not exit script when throwing in global.onerror()
+
+
+ if (this.allowUncaught && !utils.isBrowser()) {
+ debug('uncaught(): bubbling exception due to --allow-uncaught');
+ throw err;
+ }
+
+ if (this.state === constants$1.STATE_STOPPED) {
+ debug('uncaught(): throwing after run has completed!');
+ throw err;
+ }
+
+ if (err) {
+ debug('uncaught(): got truthy exception %O', err);
+ } else {
+ debug('uncaught(): undefined/falsy exception');
+ err = createInvalidExceptionError('Caught falsy/undefined exception which would otherwise be uncaught. No stack trace found; try a debugger', err);
+ }
+
+ if (!isError(err)) {
+ err = thrown2Error(err);
+ debug('uncaught(): converted "error" %o to Error', err);
+ }
+
+ err.uncaught = true;
+ var runnable$1 = this.currentRunnable;
+
+ if (!runnable$1) {
+ runnable$1 = new runnable('Uncaught error outside test suite');
+ debug('uncaught(): no current Runnable; created a phony one');
+ runnable$1.parent = this.suite;
+
+ if (this.state === constants$1.STATE_RUNNING) {
+ debug('uncaught(): failing gracefully');
+ this.fail(runnable$1, err);
+ } else {
+ // Can't recover from this failure
+ debug('uncaught(): test run has not yet started; unrecoverable');
+ this.emit(constants$1.EVENT_RUN_BEGIN);
+ this.fail(runnable$1, err);
+ this.emit(constants$1.EVENT_RUN_END);
+ }
+
+ return;
+ }
+
+ runnable$1.clearTimeout();
+
+ if (runnable$1.isFailed()) {
+ debug('uncaught(): Runnable has already failed'); // Ignore error if already failed
+
+ return;
+ } else if (runnable$1.isPending()) {
+ debug('uncaught(): pending Runnable wound up failing!'); // report 'pending test' retrospectively as failed
+
+ this.fail(runnable$1, err, true);
+ return;
+ } // we cannot recover gracefully if a Runnable has already passed
+ // then fails asynchronously
+
+
+ if (runnable$1.isPassed()) {
+ debug('uncaught(): Runnable has already passed; bailing gracefully');
+ this.fail(runnable$1, err);
+ this.abort();
+ } else {
+ debug('uncaught(): forcing Runnable to complete with Error');
+ return runnable$1.callback(err);
+ }
+ };
+ /**
+ * Run the root suite and invoke `fn(failures)`
+ * on completion.
+ *
+ * @public
+ * @memberof Runner
+ * @param {Function} fn - Callback when finished
+ * @param {{files: string[], options: Options}} [opts] - For subclasses
+ * @returns {Runner} Runner instance.
+ */
+
+
+ Runner.prototype.run = function (fn) {
+ var _this2 = this;
+
+ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ var rootSuite = this.suite;
+ var options = opts.options || {};
+ debug('run(): got options: %O', options);
+
+ fn = fn || function () {};
+
+ var end = function end() {
+ if (!_this2.total && _this2._opts.failZero) _this2.failures = 1;
+ debug('run(): root suite completed; emitting %s', constants$1.EVENT_RUN_END);
+
+ _this2.emit(constants$1.EVENT_RUN_END);
+ };
+
+ var begin = function begin() {
+ debug('run(): emitting %s', constants$1.EVENT_RUN_BEGIN);
+
+ _this2.emit(constants$1.EVENT_RUN_BEGIN);
+
+ debug('run(): emitted %s', constants$1.EVENT_RUN_BEGIN);
+
+ _this2.runSuite(rootSuite, end);
+ };
+
+ var prepare = function prepare() {
+ debug('run(): starting'); // If there is an `only` filter
+
+ if (rootSuite.hasOnly()) {
+ rootSuite.filterOnly();
+ debug('run(): filtered exclusive Runnables');
+ }
+
+ _this2.state = constants$1.STATE_RUNNING;
+
+ if (_this2._delay) {
+ _this2.emit(constants$1.EVENT_DELAY_END);
+
+ debug('run(): "delay" ended');
+ }
+
+ return begin();
+ }; // references cleanup to avoid memory leaks
+
+
+ if (this._opts.cleanReferencesAfterRun) {
+ this.on(constants$1.EVENT_SUITE_END, function (suite) {
+ suite.cleanReferences();
+ });
+ } // callback
+
+
+ this.on(constants$1.EVENT_RUN_END, function () {
+ this.state = constants$1.STATE_STOPPED;
+ debug('run(): emitted %s', constants$1.EVENT_RUN_END);
+ fn(this.failures);
+ });
+
+ this._removeEventListener(process$4, 'uncaughtException', this.uncaught);
+
+ this._removeEventListener(process$4, 'unhandledRejection', this.unhandled);
+
+ this._addEventListener(process$4, 'uncaughtException', this.uncaught);
+
+ this._addEventListener(process$4, 'unhandledRejection', this.unhandled);
+
+ if (this._delay) {
+ // for reporters, I guess.
+ // might be nice to debounce some dots while we wait.
+ this.emit(constants$1.EVENT_DELAY_BEGIN, rootSuite);
+ rootSuite.once(EVENT_ROOT_SUITE_RUN, prepare);
+ debug('run(): waiting for green light due to --delay');
+ } else {
+ Runner.immediately(prepare);
+ }
+
+ return this;
+ };
+ /**
+ * Toggle partial object linking behavior; used for building object references from
+ * unique ID's. Does nothing in serial mode, because the object references already exist.
+ * Subclasses can implement this (e.g., `ParallelBufferedRunner`)
+ * @abstract
+ * @param {boolean} [value] - If `true`, enable partial object linking, otherwise disable
+ * @returns {Runner}
+ * @chainable
+ * @public
+ * @example
+ * // this reporter needs proper object references when run in parallel mode
+ * class MyReporter() {
+ * constructor(runner) {
+ * this.runner.linkPartialObjects(true)
+ * .on(EVENT_SUITE_BEGIN, suite => {
+ // this Suite may be the same object...
+ * })
+ * .on(EVENT_TEST_BEGIN, test => {
+ * // ...as the `test.parent` property
+ * });
+ * }
+ * }
+ */
+
+
+ Runner.prototype.linkPartialObjects = function (value) {
+ return this;
+ };
+ /*
+ * Like {@link Runner#run}, but does not accept a callback and returns a `Promise` instead of a `Runner`.
+ * This function cannot reject; an `unhandledRejection` event will bubble up to the `process` object instead.
+ * @public
+ * @memberof Runner
+ * @param {Object} [opts] - Options for {@link Runner#run}
+ * @returns {Promise} Failure count
+ */
+
+
+ Runner.prototype.runAsync = /*#__PURE__*/function () {
+ var _runAsync = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
+ var _this3 = this;
+
+ var opts,
+ _args = arguments;
+ return regeneratorRuntime.wrap(function _callee$(_context) {
+ while (1) {
+ switch (_context.prev = _context.next) {
+ case 0:
+ opts = _args.length > 0 && _args[0] !== undefined ? _args[0] : {};
+ return _context.abrupt("return", new Promise(function (resolve) {
+ _this3.run(resolve, opts);
+ }));
+
+ case 2:
+ case "end":
+ return _context.stop();
+ }
+ }
+ }, _callee);
+ }));
+
+ function runAsync() {
+ return _runAsync.apply(this, arguments);
+ }
+
+ return runAsync;
+ }();
+ /**
+ * Cleanly abort execution.
+ *
+ * @memberof Runner
+ * @public
+ * @return {Runner} Runner instance.
+ */
+
+
+ Runner.prototype.abort = function () {
+ debug('abort(): aborting');
+ this._abort = true;
+ return this;
+ };
+ /**
+ * Returns `true` if Mocha is running in parallel mode. For reporters.
+ *
+ * Subclasses should return an appropriate value.
+ * @public
+ * @returns {false}
+ */
+
+
+ Runner.prototype.isParallelMode = function isParallelMode() {
+ return false;
+ };
+ /**
+ * Configures an alternate reporter for worker processes to use. Subclasses
+ * using worker processes should implement this.
+ * @public
+ * @param {string} path - Absolute path to alternate reporter for worker processes to use
+ * @returns {Runner}
+ * @throws When in serial mode
+ * @chainable
+ * @abstract
+ */
+
+
+ Runner.prototype.workerReporter = function () {
+ throw createUnsupportedError$1('workerReporter() not supported in serial mode');
+ };
+ /**
+ * Filter leaks with the given globals flagged as `ok`.
+ *
+ * @private
+ * @param {Array} ok
+ * @param {Array} globals
+ * @return {Array}
+ */
+
+
+ function filterLeaks(ok, globals) {
+ return globals.filter(function (key) {
+ // Firefox and Chrome exposes iframes as index inside the window object
+ if (/^\d+/.test(key)) {
+ return false;
+ } // in firefox
+ // if runner runs in an iframe, this iframe's window.getInterface method
+ // not init at first it is assigned in some seconds
+
+
+ if (commonjsGlobal.navigator && /^getInterface/.test(key)) {
+ return false;
+ } // an iframe could be approached by window[iframeIndex]
+ // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak
+
+
+ if (commonjsGlobal.navigator && /^\d+/.test(key)) {
+ return false;
+ } // Opera and IE expose global variables for HTML element IDs (issue #243)
+
+
+ if (/^mocha-/.test(key)) {
+ return false;
+ }
+
+ var matched = ok.filter(function (ok) {
+ if (~ok.indexOf('*')) {
+ return key.indexOf(ok.split('*')[0]) === 0;
+ }
+
+ return key === ok;
+ });
+ return !matched.length && (!commonjsGlobal.navigator || key !== 'onerror');
+ });
+ }
+ /**
+ * Check if argument is an instance of Error object or a duck-typed equivalent.
+ *
+ * @private
+ * @param {Object} err - object to check
+ * @param {string} err.message - error message
+ * @returns {boolean}
+ */
+
+
+ function isError(err) {
+ return err instanceof Error || err && typeof err.message === 'string';
+ }
+ /**
+ *
+ * Converts thrown non-extensible type into proper Error.
+ *
+ * @private
+ * @param {*} thrown - Non-extensible type thrown by code
+ * @return {Error}
+ */
+
+
+ function thrown2Error(err) {
+ return new Error("the ".concat(utils.canonicalType(err), " ").concat(stringify(err), " was thrown, throw an Error :)"));
+ }
+
+ Runner.constants = constants$1;
+ /**
+ * Node.js' `EventEmitter`
+ * @external EventEmitter
+ * @see {@link https://nodejs.org/api/events.html#events_class_eventemitter}
+ */
+
+ var runner = Runner;
+
+ var require$$10 = getCjsExportFromNamespace(_nodeResolve_empty$1);
+
+ var base = createCommonjsModule(function (module, exports) {
+ /**
+ * @module Base
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var constants = runner.constants;
+ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
+ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
+ var isBrowser = utils.isBrowser();
+
+ function getBrowserWindowSize() {
+ if ('innerHeight' in commonjsGlobal) {
+ return [commonjsGlobal.innerHeight, commonjsGlobal.innerWidth];
+ } // In a Web Worker, the DOM Window is not available.
+
+
+ return [640, 480];
+ }
+ /**
+ * Expose `Base`.
+ */
+
+
+ exports = module.exports = Base;
+ /**
+ * Check if both stdio streams are associated with a tty.
+ */
+
+ var isatty = isBrowser || process$4.stdout.isTTY && process$4.stderr.isTTY;
+ /**
+ * Save log references to avoid tests interfering (see GH-3604).
+ */
+
+ var consoleLog = console.log;
+ /**
+ * Enable coloring by default, except in the browser interface.
+ */
+
+ exports.useColors = !isBrowser && (require$$10.stdout || process$4.env.MOCHA_COLORS !== undefined);
+ /**
+ * Inline diffs instead of +/-
+ */
+
+ exports.inlineDiffs = false;
+ /**
+ * Default color map.
+ */
+
+ exports.colors = {
+ pass: 90,
+ fail: 31,
+ 'bright pass': 92,
+ 'bright fail': 91,
+ 'bright yellow': 93,
+ pending: 36,
+ suite: 0,
+ 'error title': 0,
+ 'error message': 31,
+ 'error stack': 90,
+ checkmark: 32,
+ fast: 90,
+ medium: 33,
+ slow: 31,
+ green: 32,
+ light: 90,
+ 'diff gutter': 90,
+ 'diff added': 32,
+ 'diff removed': 31,
+ 'diff added inline': '30;42',
+ 'diff removed inline': '30;41'
+ };
+ /**
+ * Default symbol map.
+ */
+
+ exports.symbols = {
+ ok: browser$1.success,
+ err: browser$1.error,
+ dot: '.',
+ comma: ',',
+ bang: '!'
+ };
+ /**
+ * Color `str` with the given `type`,
+ * allowing colors to be disabled,
+ * as well as user-defined color
+ * schemes.
+ *
+ * @private
+ * @param {string} type
+ * @param {string} str
+ * @return {string}
+ */
+
+ var color = exports.color = function (type, str) {
+ if (!exports.useColors) {
+ return String(str);
+ }
+
+ return "\x1B[" + exports.colors[type] + 'm' + str + "\x1B[0m";
+ };
+ /**
+ * Expose term window size, with some defaults for when stderr is not a tty.
+ */
+
+
+ exports.window = {
+ width: 75
+ };
+
+ if (isatty) {
+ if (isBrowser) {
+ exports.window.width = getBrowserWindowSize()[1];
+ } else {
+ exports.window.width = process$4.stdout.getWindowSize(1)[0];
+ }
+ }
+ /**
+ * Expose some basic cursor interactions that are common among reporters.
+ */
+
+
+ exports.cursor = {
+ hide: function hide() {
+ isatty && process$4.stdout.write("\x1B[?25l");
+ },
+ show: function show() {
+ isatty && process$4.stdout.write("\x1B[?25h");
+ },
+ deleteLine: function deleteLine() {
+ isatty && process$4.stdout.write("\x1B[2K");
+ },
+ beginningOfLine: function beginningOfLine() {
+ isatty && process$4.stdout.write("\x1B[0G");
+ },
+ CR: function CR() {
+ if (isatty) {
+ exports.cursor.deleteLine();
+ exports.cursor.beginningOfLine();
+ } else {
+ process$4.stdout.write('\r');
+ }
+ }
+ };
+
+ var showDiff = exports.showDiff = function (err) {
+ return err && err.showDiff !== false && sameType(err.actual, err.expected) && err.expected !== undefined;
+ };
+
+ function stringifyDiffObjs(err) {
+ if (!utils.isString(err.actual) || !utils.isString(err.expected)) {
+ err.actual = utils.stringify(err.actual);
+ err.expected = utils.stringify(err.expected);
+ }
+ }
+ /**
+ * Returns a diff between 2 strings with coloured ANSI output.
+ *
+ * @description
+ * The diff will be either inline or unified dependent on the value
+ * of `Base.inlineDiff`.
+ *
+ * @param {string} actual
+ * @param {string} expected
+ * @return {string} Diff
+ */
+
+
+ var generateDiff = exports.generateDiff = function (actual, expected) {
+ try {
+ var diffSize = 2048;
+
+ if (actual.length > diffSize) {
+ actual = actual.substring(0, diffSize) + ' ... Lines skipped';
+ }
+
+ if (expected.length > diffSize) {
+ expected = expected.substring(0, diffSize) + ' ... Lines skipped';
+ }
+
+ return exports.inlineDiffs ? inlineDiff(actual, expected) : unifiedDiff(actual, expected);
+ } catch (err) {
+ var msg = '\n ' + color('diff added', '+ expected') + ' ' + color('diff removed', '- actual: failed to generate Mocha diff') + '\n';
+ return msg;
+ }
+ };
+ /**
+ * Outputs the given `failures` as a list.
+ *
+ * @public
+ * @memberof Mocha.reporters.Base
+ * @variation 1
+ * @param {Object[]} failures - Each is Test instance with corresponding
+ * Error property
+ */
+
+
+ exports.list = function (failures) {
+ var multipleErr, multipleTest;
+ Base.consoleLog();
+ failures.forEach(function (test, i) {
+ // format
+ var fmt = color('error title', ' %s) %s:\n') + color('error message', ' %s') + color('error stack', '\n%s\n'); // msg
+
+ var msg;
+ var err;
+
+ if (test.err && test.err.multiple) {
+ if (multipleTest !== test) {
+ multipleTest = test;
+ multipleErr = [test.err].concat(test.err.multiple);
+ }
+
+ err = multipleErr.shift();
+ } else {
+ err = test.err;
+ }
+
+ var message;
+
+ if (typeof err.inspect === 'function') {
+ message = err.inspect() + '';
+ } else if (err.message && typeof err.message.toString === 'function') {
+ message = err.message + '';
+ } else {
+ message = '';
+ }
+
+ var stack = err.stack || message;
+ var index = message ? stack.indexOf(message) : -1;
+
+ if (index === -1) {
+ msg = message;
+ } else {
+ index += message.length;
+ msg = stack.slice(0, index); // remove msg from stack
+
+ stack = stack.slice(index + 1);
+ } // uncaught
+
+
+ if (err.uncaught) {
+ msg = 'Uncaught ' + msg;
+ } // explicitly show diff
+
+
+ if (!exports.hideDiff && showDiff(err)) {
+ stringifyDiffObjs(err);
+ fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n');
+ var match = message.match(/^([^:]+): expected/);
+ msg = '\n ' + color('error message', match ? match[1] : msg);
+ msg += generateDiff(err.actual, err.expected);
+ } // indent stack trace
+
+
+ stack = stack.replace(/^/gm, ' '); // indented test title
+
+ var testTitle = '';
+ test.titlePath().forEach(function (str, index) {
+ if (index !== 0) {
+ testTitle += '\n ';
+ }
+
+ for (var i = 0; i < index; i++) {
+ testTitle += ' ';
+ }
+
+ testTitle += str;
+ });
+ Base.consoleLog(fmt, i + 1, testTitle, msg, stack);
+ });
+ };
+ /**
+ * Constructs a new `Base` reporter instance.
+ *
+ * @description
+ * All other reporters generally inherit from this reporter.
+ *
+ * @public
+ * @class
+ * @memberof Mocha.reporters
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+
+ function Base(runner, options) {
+ var failures = this.failures = [];
+
+ if (!runner) {
+ throw new TypeError('Missing runner argument');
+ }
+
+ this.options = options || {};
+ this.runner = runner;
+ this.stats = runner.stats; // assigned so Reporters keep a closer reference
+
+ runner.on(EVENT_TEST_PASS, function (test) {
+ if (test.duration > test.slow()) {
+ test.speed = 'slow';
+ } else if (test.duration > test.slow() / 2) {
+ test.speed = 'medium';
+ } else {
+ test.speed = 'fast';
+ }
+ });
+ runner.on(EVENT_TEST_FAIL, function (test, err) {
+ if (showDiff(err)) {
+ stringifyDiffObjs(err);
+ } // more than one error per test
+
+
+ if (test.err && err instanceof Error) {
+ test.err.multiple = (test.err.multiple || []).concat(err);
+ } else {
+ test.err = err;
+ }
+
+ failures.push(test);
+ });
+ }
+ /**
+ * Outputs common epilogue used by many of the bundled reporters.
+ *
+ * @public
+ * @memberof Mocha.reporters
+ */
+
+
+ Base.prototype.epilogue = function () {
+ var stats = this.stats;
+ var fmt;
+ Base.consoleLog(); // passes
+
+ fmt = color('bright pass', ' ') + color('green', ' %d passing') + color('light', ' (%s)');
+ Base.consoleLog(fmt, stats.passes || 0, ms$1(stats.duration)); // pending
+
+ if (stats.pending) {
+ fmt = color('pending', ' ') + color('pending', ' %d pending');
+ Base.consoleLog(fmt, stats.pending);
+ } // failures
+
+
+ if (stats.failures) {
+ fmt = color('fail', ' %d failing');
+ Base.consoleLog(fmt, stats.failures);
+ Base.list(this.failures);
+ Base.consoleLog();
+ }
+
+ Base.consoleLog();
+ };
+ /**
+ * Pads the given `str` to `len`.
+ *
+ * @private
+ * @param {string} str
+ * @param {string} len
+ * @return {string}
+ */
+
+
+ function pad(str, len) {
+ str = String(str);
+ return Array(len - str.length + 1).join(' ') + str;
+ }
+ /**
+ * Returns inline diff between 2 strings with coloured ANSI output.
+ *
+ * @private
+ * @param {String} actual
+ * @param {String} expected
+ * @return {string} Diff
+ */
+
+
+ function inlineDiff(actual, expected) {
+ var msg = errorDiff(actual, expected); // linenos
+
+ var lines = msg.split('\n');
+
+ if (lines.length > 4) {
+ var width = String(lines.length).length;
+ msg = lines.map(function (str, i) {
+ return pad(++i, width) + ' |' + ' ' + str;
+ }).join('\n');
+ } // legend
+
+
+ msg = '\n' + color('diff removed inline', 'actual') + ' ' + color('diff added inline', 'expected') + '\n\n' + msg + '\n'; // indent
+
+ msg = msg.replace(/^/gm, ' ');
+ return msg;
+ }
+ /**
+ * Returns unified diff between two strings with coloured ANSI output.
+ *
+ * @private
+ * @param {String} actual
+ * @param {String} expected
+ * @return {string} The diff.
+ */
+
+
+ function unifiedDiff(actual, expected) {
+ var indent = ' ';
+
+ function cleanUp(line) {
+ if (line[0] === '+') {
+ return indent + colorLines('diff added', line);
+ }
+
+ if (line[0] === '-') {
+ return indent + colorLines('diff removed', line);
+ }
+
+ if (line.match(/@@/)) {
+ return '--';
+ }
+
+ if (line.match(/\\ No newline/)) {
+ return null;
+ }
+
+ return indent + line;
+ }
+
+ function notBlank(line) {
+ return typeof line !== 'undefined' && line !== null;
+ }
+
+ var msg = diff$1.createPatch('string', actual, expected);
+ var lines = msg.split('\n').splice(5);
+ return '\n ' + colorLines('diff added', '+ expected') + ' ' + colorLines('diff removed', '- actual') + '\n\n' + lines.map(cleanUp).filter(notBlank).join('\n');
+ }
+ /**
+ * Returns character diff for `err`.
+ *
+ * @private
+ * @param {String} actual
+ * @param {String} expected
+ * @return {string} the diff
+ */
+
+
+ function errorDiff(actual, expected) {
+ return diff$1.diffWordsWithSpace(actual, expected).map(function (str) {
+ if (str.added) {
+ return colorLines('diff added inline', str.value);
+ }
+
+ if (str.removed) {
+ return colorLines('diff removed inline', str.value);
+ }
+
+ return str.value;
+ }).join('');
+ }
+ /**
+ * Colors lines for `str`, using the color `name`.
+ *
+ * @private
+ * @param {string} name
+ * @param {string} str
+ * @return {string}
+ */
+
+
+ function colorLines(name, str) {
+ return str.split('\n').map(function (str) {
+ return color(name, str);
+ }).join('\n');
+ }
+ /**
+ * Object#toString reference.
+ */
+
+
+ var objToString = Object.prototype.toString;
+ /**
+ * Checks that a / b have the same type.
+ *
+ * @private
+ * @param {Object} a
+ * @param {Object} b
+ * @return {boolean}
+ */
+
+ function sameType(a, b) {
+ return objToString.call(a) === objToString.call(b);
+ }
+
+ Base.consoleLog = consoleLog;
+ Base["abstract"] = true;
+ });
+
+ var dot = createCommonjsModule(function (module, exports) {
+ /**
+ * @module Dot
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var inherits = utils.inherits;
+ var constants = runner.constants;
+ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
+ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
+ var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
+ var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
+ var EVENT_RUN_END = constants.EVENT_RUN_END;
+ /**
+ * Expose `Dot`.
+ */
+
+ module.exports = Dot;
+ /**
+ * Constructs a new `Dot` reporter instance.
+ *
+ * @public
+ * @class
+ * @memberof Mocha.reporters
+ * @extends Mocha.reporters.Base
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+ function Dot(runner, options) {
+ base.call(this, runner, options);
+ var self = this;
+ var width = base.window.width * 0.75 | 0;
+ var n = -1;
+ runner.on(EVENT_RUN_BEGIN, function () {
+ process$4.stdout.write('\n');
+ });
+ runner.on(EVENT_TEST_PENDING, function () {
+ if (++n % width === 0) {
+ process$4.stdout.write('\n ');
+ }
+
+ process$4.stdout.write(base.color('pending', base.symbols.comma));
+ });
+ runner.on(EVENT_TEST_PASS, function (test) {
+ if (++n % width === 0) {
+ process$4.stdout.write('\n ');
+ }
+
+ if (test.speed === 'slow') {
+ process$4.stdout.write(base.color('bright yellow', base.symbols.dot));
+ } else {
+ process$4.stdout.write(base.color(test.speed, base.symbols.dot));
+ }
+ });
+ runner.on(EVENT_TEST_FAIL, function () {
+ if (++n % width === 0) {
+ process$4.stdout.write('\n ');
+ }
+
+ process$4.stdout.write(base.color('fail', base.symbols.bang));
+ });
+ runner.once(EVENT_RUN_END, function () {
+ process$4.stdout.write('\n');
+ self.epilogue();
+ });
+ }
+ /**
+ * Inherit from `Base.prototype`.
+ */
+
+
+ inherits(Dot, base);
+ Dot.description = 'dot matrix representation';
+ });
+
+ var doc = createCommonjsModule(function (module, exports) {
+ /**
+ * @module Doc
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var constants = runner.constants;
+ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
+ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
+ var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
+ var EVENT_SUITE_END = constants.EVENT_SUITE_END;
+ /**
+ * Expose `Doc`.
+ */
+
+ module.exports = Doc;
+ /**
+ * Constructs a new `Doc` reporter instance.
+ *
+ * @public
+ * @class
+ * @memberof Mocha.reporters
+ * @extends Mocha.reporters.Base
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+ function Doc(runner, options) {
+ base.call(this, runner, options);
+ var indents = 2;
+
+ function indent() {
+ return Array(indents).join(' ');
+ }
+
+ runner.on(EVENT_SUITE_BEGIN, function (suite) {
+ if (suite.root) {
+ return;
+ }
+
+ ++indents;
+ base.consoleLog('%s', indent());
+ ++indents;
+ base.consoleLog('%s%s ', indent(), utils.escape(suite.title));
+ base.consoleLog('%s', indent());
+ });
+ runner.on(EVENT_SUITE_END, function (suite) {
+ if (suite.root) {
+ return;
+ }
+
+ base.consoleLog('%s ', indent());
+ --indents;
+ base.consoleLog('%s ', indent());
+ --indents;
+ });
+ runner.on(EVENT_TEST_PASS, function (test) {
+ base.consoleLog('%s %s ', indent(), utils.escape(test.title));
+ base.consoleLog('%s %s ', indent(), utils.escape(test.file));
+ var code = utils.escape(utils.clean(test.body));
+ base.consoleLog('%s %s
', indent(), code);
+ });
+ runner.on(EVENT_TEST_FAIL, function (test, err) {
+ base.consoleLog('%s %s ', indent(), utils.escape(test.title));
+ base.consoleLog('%s %s ', indent(), utils.escape(test.file));
+ var code = utils.escape(utils.clean(test.body));
+ base.consoleLog('%s %s
', indent(), code);
+ base.consoleLog('%s %s ', indent(), utils.escape(err));
+ });
+ }
+
+ Doc.description = 'HTML documentation';
+ });
+
+ var tap = createCommonjsModule(function (module, exports) {
+ /**
+ * @module TAP
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var constants = runner.constants;
+ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
+ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
+ var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
+ var EVENT_RUN_END = constants.EVENT_RUN_END;
+ var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
+ var EVENT_TEST_END = constants.EVENT_TEST_END;
+ var inherits = utils.inherits;
+ var sprintf = util.format;
+ /**
+ * Expose `TAP`.
+ */
+
+ module.exports = TAP;
+ /**
+ * Constructs a new `TAP` reporter instance.
+ *
+ * @public
+ * @class
+ * @memberof Mocha.reporters
+ * @extends Mocha.reporters.Base
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+ function TAP(runner, options) {
+ base.call(this, runner, options);
+ var self = this;
+ var n = 1;
+ var tapVersion = '12';
+
+ if (options && options.reporterOptions) {
+ if (options.reporterOptions.tapVersion) {
+ tapVersion = options.reporterOptions.tapVersion.toString();
+ }
+ }
+
+ this._producer = createProducer(tapVersion);
+ runner.once(EVENT_RUN_BEGIN, function () {
+ self._producer.writeVersion();
+ });
+ runner.on(EVENT_TEST_END, function () {
+ ++n;
+ });
+ runner.on(EVENT_TEST_PENDING, function (test) {
+ self._producer.writePending(n, test);
+ });
+ runner.on(EVENT_TEST_PASS, function (test) {
+ self._producer.writePass(n, test);
+ });
+ runner.on(EVENT_TEST_FAIL, function (test, err) {
+ self._producer.writeFail(n, test, err);
+ });
+ runner.once(EVENT_RUN_END, function () {
+ self._producer.writeEpilogue(runner.stats);
+ });
+ }
+ /**
+ * Inherit from `Base.prototype`.
+ */
+
+
+ inherits(TAP, base);
+ /**
+ * Returns a TAP-safe title of `test`.
+ *
+ * @private
+ * @param {Test} test - Test instance.
+ * @return {String} title with any hash character removed
+ */
+
+ function title(test) {
+ return test.fullTitle().replace(/#/g, '');
+ }
+ /**
+ * Writes newline-terminated formatted string to reporter output stream.
+ *
+ * @private
+ * @param {string} format - `printf`-like format string
+ * @param {...*} [varArgs] - Format string arguments
+ */
+
+
+ function println(format, varArgs) {
+ var vargs = Array.from(arguments);
+ vargs[0] += '\n';
+ process$4.stdout.write(sprintf.apply(null, vargs));
+ }
+ /**
+ * Returns a `tapVersion`-appropriate TAP producer instance, if possible.
+ *
+ * @private
+ * @param {string} tapVersion - Version of TAP specification to produce.
+ * @returns {TAPProducer} specification-appropriate instance
+ * @throws {Error} if specification version has no associated producer.
+ */
+
+
+ function createProducer(tapVersion) {
+ var producers = {
+ '12': new TAP12Producer(),
+ '13': new TAP13Producer()
+ };
+ var producer = producers[tapVersion];
+
+ if (!producer) {
+ throw new Error('invalid or unsupported TAP version: ' + JSON.stringify(tapVersion));
+ }
+
+ return producer;
+ }
+ /**
+ * @summary
+ * Constructs a new TAPProducer.
+ *
+ * @description
+ * Only to be used as an abstract base class.
+ *
+ * @private
+ * @constructor
+ */
+
+
+ function TAPProducer() {}
+ /**
+ * Writes the TAP version to reporter output stream.
+ *
+ * @abstract
+ */
+
+
+ TAPProducer.prototype.writeVersion = function () {};
+ /**
+ * Writes the plan to reporter output stream.
+ *
+ * @abstract
+ * @param {number} ntests - Number of tests that are planned to run.
+ */
+
+
+ TAPProducer.prototype.writePlan = function (ntests) {
+ println('%d..%d', 1, ntests);
+ };
+ /**
+ * Writes that test passed to reporter output stream.
+ *
+ * @abstract
+ * @param {number} n - Index of test that passed.
+ * @param {Test} test - Instance containing test information.
+ */
+
+
+ TAPProducer.prototype.writePass = function (n, test) {
+ println('ok %d %s', n, title(test));
+ };
+ /**
+ * Writes that test was skipped to reporter output stream.
+ *
+ * @abstract
+ * @param {number} n - Index of test that was skipped.
+ * @param {Test} test - Instance containing test information.
+ */
+
+
+ TAPProducer.prototype.writePending = function (n, test) {
+ println('ok %d %s # SKIP -', n, title(test));
+ };
+ /**
+ * Writes that test failed to reporter output stream.
+ *
+ * @abstract
+ * @param {number} n - Index of test that failed.
+ * @param {Test} test - Instance containing test information.
+ * @param {Error} err - Reason the test failed.
+ */
+
+
+ TAPProducer.prototype.writeFail = function (n, test, err) {
+ println('not ok %d %s', n, title(test));
+ };
+ /**
+ * Writes the summary epilogue to reporter output stream.
+ *
+ * @abstract
+ * @param {Object} stats - Object containing run statistics.
+ */
+
+
+ TAPProducer.prototype.writeEpilogue = function (stats) {
+ // :TBD: Why is this not counting pending tests?
+ println('# tests ' + (stats.passes + stats.failures));
+ println('# pass ' + stats.passes); // :TBD: Why are we not showing pending results?
+
+ println('# fail ' + stats.failures);
+ this.writePlan(stats.passes + stats.failures + stats.pending);
+ };
+ /**
+ * @summary
+ * Constructs a new TAP12Producer.
+ *
+ * @description
+ * Produces output conforming to the TAP12 specification.
+ *
+ * @private
+ * @constructor
+ * @extends TAPProducer
+ * @see {@link https://testanything.org/tap-specification.html|Specification}
+ */
+
+
+ function TAP12Producer() {
+ /**
+ * Writes that test failed to reporter output stream, with error formatting.
+ * @override
+ */
+ this.writeFail = function (n, test, err) {
+ TAPProducer.prototype.writeFail.call(this, n, test, err);
+
+ if (err.message) {
+ println(err.message.replace(/^/gm, ' '));
+ }
+
+ if (err.stack) {
+ println(err.stack.replace(/^/gm, ' '));
+ }
+ };
+ }
+ /**
+ * Inherit from `TAPProducer.prototype`.
+ */
+
+
+ inherits(TAP12Producer, TAPProducer);
+ /**
+ * @summary
+ * Constructs a new TAP13Producer.
+ *
+ * @description
+ * Produces output conforming to the TAP13 specification.
+ *
+ * @private
+ * @constructor
+ * @extends TAPProducer
+ * @see {@link https://testanything.org/tap-version-13-specification.html|Specification}
+ */
+
+ function TAP13Producer() {
+ /**
+ * Writes the TAP version to reporter output stream.
+ * @override
+ */
+ this.writeVersion = function () {
+ println('TAP version 13');
+ };
+ /**
+ * Writes that test failed to reporter output stream, with error formatting.
+ * @override
+ */
+
+
+ this.writeFail = function (n, test, err) {
+ TAPProducer.prototype.writeFail.call(this, n, test, err);
+ var emitYamlBlock = err.message != null || err.stack != null;
+
+ if (emitYamlBlock) {
+ println(indent(1) + '---');
+
+ if (err.message) {
+ println(indent(2) + 'message: |-');
+ println(err.message.replace(/^/gm, indent(3)));
+ }
+
+ if (err.stack) {
+ println(indent(2) + 'stack: |-');
+ println(err.stack.replace(/^/gm, indent(3)));
+ }
+
+ println(indent(1) + '...');
+ }
+ };
+
+ function indent(level) {
+ return Array(level + 1).join(' ');
+ }
+ }
+ /**
+ * Inherit from `TAPProducer.prototype`.
+ */
+
+
+ inherits(TAP13Producer, TAPProducer);
+ TAP.description = 'TAP-compatible output';
+ });
+
+ var fs = {};
+
+ var json = createCommonjsModule(function (module, exports) {
+ /**
+ * @module JSON
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var createUnsupportedError = errors.createUnsupportedError;
+ var constants = runner.constants;
+ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
+ var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
+ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
+ var EVENT_TEST_END = constants.EVENT_TEST_END;
+ var EVENT_RUN_END = constants.EVENT_RUN_END;
+ /**
+ * Expose `JSON`.
+ */
+
+ module.exports = JSONReporter;
+ /**
+ * Constructs a new `JSON` reporter instance.
+ *
+ * @public
+ * @class JSON
+ * @memberof Mocha.reporters
+ * @extends Mocha.reporters.Base
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+ function JSONReporter(runner) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ base.call(this, runner, options);
+ var self = this;
+ var tests = [];
+ var pending = [];
+ var failures = [];
+ var passes = [];
+ var output;
+
+ if (options.reporterOption && options.reporterOption.output) {
+ if (utils.isBrowser()) {
+ throw createUnsupportedError('file output not supported in browser');
+ }
+
+ output = options.reporterOption.output;
+ }
+
+ runner.on(EVENT_TEST_END, function (test) {
+ tests.push(test);
+ });
+ runner.on(EVENT_TEST_PASS, function (test) {
+ passes.push(test);
+ });
+ runner.on(EVENT_TEST_FAIL, function (test) {
+ failures.push(test);
+ });
+ runner.on(EVENT_TEST_PENDING, function (test) {
+ pending.push(test);
+ });
+ runner.once(EVENT_RUN_END, function () {
+ var obj = {
+ stats: self.stats,
+ tests: tests.map(clean),
+ pending: pending.map(clean),
+ failures: failures.map(clean),
+ passes: passes.map(clean)
+ };
+ runner.testResults = obj;
+ var json = JSON.stringify(obj, null, 2);
+
+ if (output) {
+ try {
+ fs.mkdirSync(path.dirname(output), {
+ recursive: true
+ });
+ fs.writeFileSync(output, json);
+ } catch (err) {
+ console.error("".concat(base.symbols.err, " [mocha] writing output to \"").concat(output, "\" failed: ").concat(err.message, "\n"));
+ process$4.stdout.write(json);
+ }
+ } else {
+ process$4.stdout.write(json);
+ }
+ });
+ }
+ /**
+ * Return a plain-object representation of `test`
+ * free of cyclic properties etc.
+ *
+ * @private
+ * @param {Object} test
+ * @return {Object}
+ */
+
+
+ function clean(test) {
+ var err = test.err || {};
+
+ if (err instanceof Error) {
+ err = errorJSON(err);
+ }
+
+ return {
+ title: test.title,
+ fullTitle: test.fullTitle(),
+ file: test.file,
+ duration: test.duration,
+ currentRetry: test.currentRetry(),
+ speed: test.speed,
+ err: cleanCycles(err)
+ };
+ }
+ /**
+ * Replaces any circular references inside `obj` with '[object Object]'
+ *
+ * @private
+ * @param {Object} obj
+ * @return {Object}
+ */
+
+
+ function cleanCycles(obj) {
+ var cache = [];
+ return JSON.parse(JSON.stringify(obj, function (key, value) {
+ if (_typeof(value) === 'object' && value !== null) {
+ if (cache.indexOf(value) !== -1) {
+ // Instead of going in a circle, we'll print [object Object]
+ return '' + value;
+ }
+
+ cache.push(value);
+ }
+
+ return value;
+ }));
+ }
+ /**
+ * Transform an Error object into a JSON object.
+ *
+ * @private
+ * @param {Error} err
+ * @return {Object}
+ */
+
+
+ function errorJSON(err) {
+ var res = {};
+ Object.getOwnPropertyNames(err).forEach(function (key) {
+ res[key] = err[key];
+ }, err);
+ return res;
+ }
+
+ JSONReporter.description = 'single JSON object';
+ });
+
+ var valueOf = 1.0.valueOf;
+
+ // `thisNumberValue` abstract operation
+ // https://tc39.es/ecma262/#sec-thisnumbervalue
+ var thisNumberValue = function (value) {
+ return valueOf.call(value);
+ };
+
+ // `String.prototype.repeat` method implementation
+ // https://tc39.es/ecma262/#sec-string.prototype.repeat
+ var stringRepeat = function repeat(count) {
+ var str = toString_1(requireObjectCoercible(this));
+ var result = '';
+ var n = toInteger(count);
+ if (n < 0 || n == Infinity) throw RangeError('Wrong number of repetitions');
+ for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) result += str;
+ return result;
+ };
+
+ var nativeToFixed = 1.0.toFixed;
+ var floor = Math.floor;
+
+ var pow = function (x, n, acc) {
+ return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);
+ };
+
+ var log = function (x) {
+ var n = 0;
+ var x2 = x;
+ while (x2 >= 4096) {
+ n += 12;
+ x2 /= 4096;
+ }
+ while (x2 >= 2) {
+ n += 1;
+ x2 /= 2;
+ } return n;
+ };
+
+ var multiply = function (data, n, c) {
+ var index = -1;
+ var c2 = c;
+ while (++index < 6) {
+ c2 += n * data[index];
+ data[index] = c2 % 1e7;
+ c2 = floor(c2 / 1e7);
+ }
+ };
+
+ var divide = function (data, n) {
+ var index = 6;
+ var c = 0;
+ while (--index >= 0) {
+ c += data[index];
+ data[index] = floor(c / n);
+ c = (c % n) * 1e7;
+ }
+ };
+
+ var dataToString = function (data) {
+ var index = 6;
+ var s = '';
+ while (--index >= 0) {
+ if (s !== '' || index === 0 || data[index] !== 0) {
+ var t = String(data[index]);
+ s = s === '' ? t : s + stringRepeat.call('0', 7 - t.length) + t;
+ }
+ } return s;
+ };
+
+ var FORCED = nativeToFixed && (
+ 0.00008.toFixed(3) !== '0.000' ||
+ 0.9.toFixed(0) !== '1' ||
+ 1.255.toFixed(2) !== '1.25' ||
+ 1000000000000000128.0.toFixed(0) !== '1000000000000000128'
+ ) || !fails(function () {
+ // V8 ~ Android 4.3-
+ nativeToFixed.call({});
+ });
+
+ // `Number.prototype.toFixed` method
+ // https://tc39.es/ecma262/#sec-number.prototype.tofixed
+ _export({ target: 'Number', proto: true, forced: FORCED }, {
+ toFixed: function toFixed(fractionDigits) {
+ var number = thisNumberValue(this);
+ var fractDigits = toInteger(fractionDigits);
+ var data = [0, 0, 0, 0, 0, 0];
+ var sign = '';
+ var result = '0';
+ var e, z, j, k;
+
+ if (fractDigits < 0 || fractDigits > 20) throw RangeError('Incorrect fraction digits');
+ // eslint-disable-next-line no-self-compare -- NaN check
+ if (number != number) return 'NaN';
+ if (number <= -1e21 || number >= 1e21) return String(number);
+ if (number < 0) {
+ sign = '-';
+ number = -number;
+ }
+ if (number > 1e-21) {
+ e = log(number * pow(2, 69, 1)) - 69;
+ z = e < 0 ? number * pow(2, -e, 1) : number / pow(2, e, 1);
+ z *= 0x10000000000000;
+ e = 52 - e;
+ if (e > 0) {
+ multiply(data, 0, z);
+ j = fractDigits;
+ while (j >= 7) {
+ multiply(data, 1e7, 0);
+ j -= 7;
+ }
+ multiply(data, pow(10, j, 1), 0);
+ j = e - 1;
+ while (j >= 23) {
+ divide(data, 1 << 23);
+ j -= 23;
+ }
+ divide(data, 1 << j);
+ multiply(data, 1, 1);
+ divide(data, 2);
+ result = dataToString(data);
+ } else {
+ multiply(data, 0, z);
+ multiply(data, 1 << -e, 0);
+ result = dataToString(data) + stringRepeat.call('0', fractDigits);
+ }
+ }
+ if (fractDigits > 0) {
+ k = result.length;
+ result = sign + (k <= fractDigits
+ ? '0.' + stringRepeat.call('0', fractDigits - k) + result
+ : result.slice(0, k - fractDigits) + '.' + result.slice(k - fractDigits));
+ } else {
+ result = sign + result;
+ } return result;
+ }
+ });
+
+ /**
+ @module browser/Progress
+ */
+
+ /**
+ * Expose `Progress`.
+ */
+
+ var progress$1 = Progress;
+ /**
+ * Initialize a new `Progress` indicator.
+ */
+
+ function Progress() {
+ this.percent = 0;
+ this.size(0);
+ this.fontSize(11);
+ this.font('helvetica, arial, sans-serif');
+ }
+ /**
+ * Set progress size to `size`.
+ *
+ * @public
+ * @param {number} size
+ * @return {Progress} Progress instance.
+ */
+
+
+ Progress.prototype.size = function (size) {
+ this._size = size;
+ return this;
+ };
+ /**
+ * Set text to `text`.
+ *
+ * @public
+ * @param {string} text
+ * @return {Progress} Progress instance.
+ */
+
+
+ Progress.prototype.text = function (text) {
+ this._text = text;
+ return this;
+ };
+ /**
+ * Set font size to `size`.
+ *
+ * @public
+ * @param {number} size
+ * @return {Progress} Progress instance.
+ */
+
+
+ Progress.prototype.fontSize = function (size) {
+ this._fontSize = size;
+ return this;
+ };
+ /**
+ * Set font to `family`.
+ *
+ * @param {string} family
+ * @return {Progress} Progress instance.
+ */
+
+
+ Progress.prototype.font = function (family) {
+ this._font = family;
+ return this;
+ };
+ /**
+ * Update percentage to `n`.
+ *
+ * @param {number} n
+ * @return {Progress} Progress instance.
+ */
+
+
+ Progress.prototype.update = function (n) {
+ this.percent = n;
+ return this;
+ };
+ /**
+ * Draw on `ctx`.
+ *
+ * @param {CanvasRenderingContext2d} ctx
+ * @return {Progress} Progress instance.
+ */
+
+
+ Progress.prototype.draw = function (ctx) {
+ try {
+ var percent = Math.min(this.percent, 100);
+ var size = this._size;
+ var half = size / 2;
+ var x = half;
+ var y = half;
+ var rad = half - 1;
+ var fontSize = this._fontSize;
+ ctx.font = fontSize + 'px ' + this._font;
+ var angle = Math.PI * 2 * (percent / 100);
+ ctx.clearRect(0, 0, size, size); // outer circle
+
+ ctx.strokeStyle = '#9f9f9f';
+ ctx.beginPath();
+ ctx.arc(x, y, rad, 0, angle, false);
+ ctx.stroke(); // inner circle
+
+ ctx.strokeStyle = '#eee';
+ ctx.beginPath();
+ ctx.arc(x, y, rad - 1, 0, angle, true);
+ ctx.stroke(); // text
+
+ var text = this._text || (percent | 0) + '%';
+ var w = ctx.measureText(text).width;
+ ctx.fillText(text, x - w / 2 + 1, y + fontSize / 2 - 1);
+ } catch (ignore) {// don't fail if we can't render progress
+ }
+
+ return this;
+ };
+
+ var html = createCommonjsModule(function (module, exports) {
+ /* eslint-env browser */
+
+ /**
+ * @module HTML
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var constants = runner.constants;
+ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
+ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
+ var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
+ var EVENT_SUITE_END = constants.EVENT_SUITE_END;
+ var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
+ var escape = utils.escape;
+ /**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+ var Date = commonjsGlobal.Date;
+ /**
+ * Expose `HTML`.
+ */
+
+ module.exports = HTML;
+ /**
+ * Stats template.
+ */
+
+ var statsTemplate = '';
+ var playIcon = '‣';
+ /**
+ * Constructs a new `HTML` reporter instance.
+ *
+ * @public
+ * @class
+ * @memberof Mocha.reporters
+ * @extends Mocha.reporters.Base
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+ function HTML(runner, options) {
+ base.call(this, runner, options);
+ var self = this;
+ var stats = this.stats;
+ var stat = fragment(statsTemplate);
+ var items = stat.getElementsByTagName('li');
+ var passes = items[1].getElementsByTagName('em')[0];
+ var passesLink = items[1].getElementsByTagName('a')[0];
+ var failures = items[2].getElementsByTagName('em')[0];
+ var failuresLink = items[2].getElementsByTagName('a')[0];
+ var duration = items[3].getElementsByTagName('em')[0];
+ var canvas = stat.getElementsByTagName('canvas')[0];
+ var report = fragment('');
+ var stack = [report];
+ var progress;
+ var ctx;
+ var root = document.getElementById('mocha');
+
+ if (canvas.getContext) {
+ var ratio = window.devicePixelRatio || 1;
+ canvas.style.width = canvas.width;
+ canvas.style.height = canvas.height;
+ canvas.width *= ratio;
+ canvas.height *= ratio;
+ ctx = canvas.getContext('2d');
+ ctx.scale(ratio, ratio);
+ progress = new progress$1();
+ }
+
+ if (!root) {
+ return error('#mocha div missing, add it to your document');
+ } // pass toggle
+
+
+ on(passesLink, 'click', function (evt) {
+ evt.preventDefault();
+ unhide();
+ var name = /pass/.test(report.className) ? '' : ' pass';
+ report.className = report.className.replace(/fail|pass/g, '') + name;
+
+ if (report.className.trim()) {
+ hideSuitesWithout('test pass');
+ }
+ }); // failure toggle
+
+ on(failuresLink, 'click', function (evt) {
+ evt.preventDefault();
+ unhide();
+ var name = /fail/.test(report.className) ? '' : ' fail';
+ report.className = report.className.replace(/fail|pass/g, '') + name;
+
+ if (report.className.trim()) {
+ hideSuitesWithout('test fail');
+ }
+ });
+ root.appendChild(stat);
+ root.appendChild(report);
+
+ if (progress) {
+ progress.size(40);
+ }
+
+ runner.on(EVENT_SUITE_BEGIN, function (suite) {
+ if (suite.root) {
+ return;
+ } // suite
+
+
+ var url = self.suiteURL(suite);
+ var el = fragment(' ', url, escape(suite.title)); // container
+
+ stack[0].appendChild(el);
+ stack.unshift(document.createElement('ul'));
+ el.appendChild(stack[0]);
+ });
+ runner.on(EVENT_SUITE_END, function (suite) {
+ if (suite.root) {
+ updateStats();
+ return;
+ }
+
+ stack.shift();
+ });
+ runner.on(EVENT_TEST_PASS, function (test) {
+ var url = self.testURL(test);
+ var markup = ' ';
+ var el = fragment(markup, test.speed, test.title, test.duration, url);
+ self.addCodeToggle(el, test.body);
+ appendToStack(el);
+ updateStats();
+ });
+ runner.on(EVENT_TEST_FAIL, function (test) {
+ var el = fragment(' ', test.title, self.testURL(test));
+ var stackString; // Note: Includes leading newline
+
+ var message = test.err.toString(); // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
+ // check for the result of the stringifying.
+
+ if (message === '[object Error]') {
+ message = test.err.message;
+ }
+
+ if (test.err.stack) {
+ var indexOfMessage = test.err.stack.indexOf(test.err.message);
+
+ if (indexOfMessage === -1) {
+ stackString = test.err.stack;
+ } else {
+ stackString = test.err.stack.substr(test.err.message.length + indexOfMessage);
+ }
+ } else if (test.err.sourceURL && test.err.line !== undefined) {
+ // Safari doesn't give you a stack. Let's at least provide a source line.
+ stackString = '\n(' + test.err.sourceURL + ':' + test.err.line + ')';
+ }
+
+ stackString = stackString || '';
+
+ if (test.err.htmlMessage && stackString) {
+ el.appendChild(fragment('', test.err.htmlMessage, stackString));
+ } else if (test.err.htmlMessage) {
+ el.appendChild(fragment('%s
', test.err.htmlMessage));
+ } else {
+ el.appendChild(fragment('%e%e ', message, stackString));
+ }
+
+ self.addCodeToggle(el, test.body);
+ appendToStack(el);
+ updateStats();
+ });
+ runner.on(EVENT_TEST_PENDING, function (test) {
+ var el = fragment('%e ', test.title);
+ appendToStack(el);
+ updateStats();
+ });
+
+ function appendToStack(el) {
+ // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
+ if (stack[0]) {
+ stack[0].appendChild(el);
+ }
+ }
+
+ function updateStats() {
+ // TODO: add to stats
+ var percent = stats.tests / runner.total * 100 | 0;
+
+ if (progress) {
+ progress.update(percent).draw(ctx);
+ } // update stats
+
+
+ var ms = new Date() - stats.start;
+ text(passes, stats.passes);
+ text(failures, stats.failures);
+ text(duration, (ms / 1000).toFixed(2));
+ }
+ }
+ /**
+ * Makes a URL, preserving querystring ("search") parameters.
+ *
+ * @param {string} s
+ * @return {string} A new URL.
+ */
+
+
+ function makeUrl(s) {
+ var search = window.location.search; // Remove previous grep query parameter if present
+
+ if (search) {
+ search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?');
+ }
+
+ return window.location.pathname + (search ? search + '&' : '?') + 'grep=' + encodeURIComponent(escapeStringRegexp(s));
+ }
+ /**
+ * Provide suite URL.
+ *
+ * @param {Object} [suite]
+ */
+
+
+ HTML.prototype.suiteURL = function (suite) {
+ return makeUrl(suite.fullTitle());
+ };
+ /**
+ * Provide test URL.
+ *
+ * @param {Object} [test]
+ */
+
+
+ HTML.prototype.testURL = function (test) {
+ return makeUrl(test.fullTitle());
+ };
+ /**
+ * Adds code toggle functionality for the provided test's list element.
+ *
+ * @param {HTMLLIElement} el
+ * @param {string} contents
+ */
+
+
+ HTML.prototype.addCodeToggle = function (el, contents) {
+ var h2 = el.getElementsByTagName('h2')[0];
+ on(h2, 'click', function () {
+ pre.style.display = pre.style.display === 'none' ? 'block' : 'none';
+ });
+ var pre = fragment('%e
', utils.clean(contents));
+ el.appendChild(pre);
+ pre.style.display = 'none';
+ };
+ /**
+ * Display error `msg`.
+ *
+ * @param {string} msg
+ */
+
+
+ function error(msg) {
+ document.body.appendChild(fragment('%s
', msg));
+ }
+ /**
+ * Return a DOM fragment from `html`.
+ *
+ * @param {string} html
+ */
+
+
+ function fragment(html) {
+ var args = arguments;
+ var div = document.createElement('div');
+ var i = 1;
+ div.innerHTML = html.replace(/%([se])/g, function (_, type) {
+ switch (type) {
+ case 's':
+ return String(args[i++]);
+
+ case 'e':
+ return escape(args[i++]);
+ // no default
+ }
+ });
+ return div.firstChild;
+ }
+ /**
+ * Check for suites that do not have elements
+ * with `classname`, and hide them.
+ *
+ * @param {text} classname
+ */
+
+
+ function hideSuitesWithout(classname) {
+ var suites = document.getElementsByClassName('suite');
+
+ for (var i = 0; i < suites.length; i++) {
+ var els = suites[i].getElementsByClassName(classname);
+
+ if (!els.length) {
+ suites[i].className += ' hidden';
+ }
+ }
+ }
+ /**
+ * Unhide .hidden suites.
+ */
+
+
+ function unhide() {
+ var els = document.getElementsByClassName('suite hidden');
+
+ while (els.length > 0) {
+ els[0].className = els[0].className.replace('suite hidden', 'suite');
+ }
+ }
+ /**
+ * Set an element's text contents.
+ *
+ * @param {HTMLElement} el
+ * @param {string} contents
+ */
+
+
+ function text(el, contents) {
+ if (el.textContent) {
+ el.textContent = contents;
+ } else {
+ el.innerText = contents;
+ }
+ }
+ /**
+ * Listen on `event` with callback `fn`.
+ */
+
+
+ function on(el, event, fn) {
+ if (el.addEventListener) {
+ el.addEventListener(event, fn, false);
+ } else {
+ el.attachEvent('on' + event, fn);
+ }
+ }
+
+ HTML.browserOnly = true;
+ });
+
+ var list = createCommonjsModule(function (module, exports) {
+ /**
+ * @module List
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var inherits = utils.inherits;
+ var constants = runner.constants;
+ var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
+ var EVENT_RUN_END = constants.EVENT_RUN_END;
+ var EVENT_TEST_BEGIN = constants.EVENT_TEST_BEGIN;
+ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
+ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
+ var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
+ var color = base.color;
+ var cursor = base.cursor;
+ /**
+ * Expose `List`.
+ */
+
+ module.exports = List;
+ /**
+ * Constructs a new `List` reporter instance.
+ *
+ * @public
+ * @class
+ * @memberof Mocha.reporters
+ * @extends Mocha.reporters.Base
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+ function List(runner, options) {
+ base.call(this, runner, options);
+ var self = this;
+ var n = 0;
+ runner.on(EVENT_RUN_BEGIN, function () {
+ base.consoleLog();
+ });
+ runner.on(EVENT_TEST_BEGIN, function (test) {
+ process$4.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));
+ });
+ runner.on(EVENT_TEST_PENDING, function (test) {
+ var fmt = color('checkmark', ' -') + color('pending', ' %s');
+ base.consoleLog(fmt, test.fullTitle());
+ });
+ runner.on(EVENT_TEST_PASS, function (test) {
+ var fmt = color('checkmark', ' ' + base.symbols.ok) + color('pass', ' %s: ') + color(test.speed, '%dms');
+ cursor.CR();
+ base.consoleLog(fmt, test.fullTitle(), test.duration);
+ });
+ runner.on(EVENT_TEST_FAIL, function (test) {
+ cursor.CR();
+ base.consoleLog(color('fail', ' %d) %s'), ++n, test.fullTitle());
+ });
+ runner.once(EVENT_RUN_END, self.epilogue.bind(self));
+ }
+ /**
+ * Inherit from `Base.prototype`.
+ */
+
+
+ inherits(List, base);
+ List.description = 'like "spec" reporter but flat';
+ });
+
+ var min = createCommonjsModule(function (module, exports) {
+ /**
+ * @module Min
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var inherits = utils.inherits;
+ var constants = runner.constants;
+ var EVENT_RUN_END = constants.EVENT_RUN_END;
+ var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
+ /**
+ * Expose `Min`.
+ */
+
+ module.exports = Min;
+ /**
+ * Constructs a new `Min` reporter instance.
+ *
+ * @description
+ * This minimal test reporter is best used with '--watch'.
+ *
+ * @public
+ * @class
+ * @memberof Mocha.reporters
+ * @extends Mocha.reporters.Base
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+ function Min(runner, options) {
+ base.call(this, runner, options);
+ runner.on(EVENT_RUN_BEGIN, function () {
+ // clear screen
+ process$4.stdout.write("\x1B[2J"); // set cursor position
+
+ process$4.stdout.write("\x1B[1;3H");
+ });
+ runner.once(EVENT_RUN_END, this.epilogue.bind(this));
+ }
+ /**
+ * Inherit from `Base.prototype`.
+ */
+
+
+ inherits(Min, base);
+ Min.description = 'essentially just a summary';
+ });
+
+ var spec = createCommonjsModule(function (module, exports) {
+ /**
+ * @module Spec
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var constants = runner.constants;
+ var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
+ var EVENT_RUN_END = constants.EVENT_RUN_END;
+ var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
+ var EVENT_SUITE_END = constants.EVENT_SUITE_END;
+ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
+ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
+ var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
+ var inherits = utils.inherits;
+ var color = base.color;
+ /**
+ * Expose `Spec`.
+ */
+
+ module.exports = Spec;
+ /**
+ * Constructs a new `Spec` reporter instance.
+ *
+ * @public
+ * @class
+ * @memberof Mocha.reporters
+ * @extends Mocha.reporters.Base
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+ function Spec(runner, options) {
+ base.call(this, runner, options);
+ var self = this;
+ var indents = 0;
+ var n = 0;
+
+ function indent() {
+ return Array(indents).join(' ');
+ }
+
+ runner.on(EVENT_RUN_BEGIN, function () {
+ base.consoleLog();
+ });
+ runner.on(EVENT_SUITE_BEGIN, function (suite) {
+ ++indents;
+ base.consoleLog(color('suite', '%s%s'), indent(), suite.title);
+ });
+ runner.on(EVENT_SUITE_END, function () {
+ --indents;
+
+ if (indents === 1) {
+ base.consoleLog();
+ }
+ });
+ runner.on(EVENT_TEST_PENDING, function (test) {
+ var fmt = indent() + color('pending', ' - %s');
+ base.consoleLog(fmt, test.title);
+ });
+ runner.on(EVENT_TEST_PASS, function (test) {
+ var fmt;
+
+ if (test.speed === 'fast') {
+ fmt = indent() + color('checkmark', ' ' + base.symbols.ok) + color('pass', ' %s');
+ base.consoleLog(fmt, test.title);
+ } else {
+ fmt = indent() + color('checkmark', ' ' + base.symbols.ok) + color('pass', ' %s') + color(test.speed, ' (%dms)');
+ base.consoleLog(fmt, test.title, test.duration);
+ }
+ });
+ runner.on(EVENT_TEST_FAIL, function (test) {
+ base.consoleLog(indent() + color('fail', ' %d) %s'), ++n, test.title);
+ });
+ runner.once(EVENT_RUN_END, self.epilogue.bind(self));
+ }
+ /**
+ * Inherit from `Base.prototype`.
+ */
+
+
+ inherits(Spec, base);
+ Spec.description = 'hierarchical & verbose [default]';
+ });
+
+ var nyan = createCommonjsModule(function (module, exports) {
+ /**
+ * @module Nyan
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var constants = runner.constants;
+ var inherits = utils.inherits;
+ var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
+ var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
+ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
+ var EVENT_RUN_END = constants.EVENT_RUN_END;
+ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
+ /**
+ * Expose `Dot`.
+ */
+
+ module.exports = NyanCat;
+ /**
+ * Constructs a new `Nyan` reporter instance.
+ *
+ * @public
+ * @class Nyan
+ * @memberof Mocha.reporters
+ * @extends Mocha.reporters.Base
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+ function NyanCat(runner, options) {
+ base.call(this, runner, options);
+ var self = this;
+ var width = base.window.width * 0.75 | 0;
+ var nyanCatWidth = this.nyanCatWidth = 11;
+ this.colorIndex = 0;
+ this.numberOfLines = 4;
+ this.rainbowColors = self.generateColors();
+ this.scoreboardWidth = 5;
+ this.tick = 0;
+ this.trajectories = [[], [], [], []];
+ this.trajectoryWidthMax = width - nyanCatWidth;
+ runner.on(EVENT_RUN_BEGIN, function () {
+ base.cursor.hide();
+ self.draw();
+ });
+ runner.on(EVENT_TEST_PENDING, function () {
+ self.draw();
+ });
+ runner.on(EVENT_TEST_PASS, function () {
+ self.draw();
+ });
+ runner.on(EVENT_TEST_FAIL, function () {
+ self.draw();
+ });
+ runner.once(EVENT_RUN_END, function () {
+ base.cursor.show();
+
+ for (var i = 0; i < self.numberOfLines; i++) {
+ write('\n');
+ }
+
+ self.epilogue();
+ });
+ }
+ /**
+ * Inherit from `Base.prototype`.
+ */
+
+
+ inherits(NyanCat, base);
+ /**
+ * Draw the nyan cat
+ *
+ * @private
+ */
+
+ NyanCat.prototype.draw = function () {
+ this.appendRainbow();
+ this.drawScoreboard();
+ this.drawRainbow();
+ this.drawNyanCat();
+ this.tick = !this.tick;
+ };
+ /**
+ * Draw the "scoreboard" showing the number
+ * of passes, failures and pending tests.
+ *
+ * @private
+ */
+
+
+ NyanCat.prototype.drawScoreboard = function () {
+ var stats = this.stats;
+
+ function draw(type, n) {
+ write(' ');
+ write(base.color(type, n));
+ write('\n');
+ }
+
+ draw('green', stats.passes);
+ draw('fail', stats.failures);
+ draw('pending', stats.pending);
+ write('\n');
+ this.cursorUp(this.numberOfLines);
+ };
+ /**
+ * Append the rainbow.
+ *
+ * @private
+ */
+
+
+ NyanCat.prototype.appendRainbow = function () {
+ var segment = this.tick ? '_' : '-';
+ var rainbowified = this.rainbowify(segment);
+
+ for (var index = 0; index < this.numberOfLines; index++) {
+ var trajectory = this.trajectories[index];
+
+ if (trajectory.length >= this.trajectoryWidthMax) {
+ trajectory.shift();
+ }
+
+ trajectory.push(rainbowified);
+ }
+ };
+ /**
+ * Draw the rainbow.
+ *
+ * @private
+ */
+
+
+ NyanCat.prototype.drawRainbow = function () {
+ var self = this;
+ this.trajectories.forEach(function (line) {
+ write("\x1B[" + self.scoreboardWidth + 'C');
+ write(line.join(''));
+ write('\n');
+ });
+ this.cursorUp(this.numberOfLines);
+ };
+ /**
+ * Draw the nyan cat
+ *
+ * @private
+ */
+
+
+ NyanCat.prototype.drawNyanCat = function () {
+ var self = this;
+ var startWidth = this.scoreboardWidth + this.trajectories[0].length;
+ var dist = "\x1B[" + startWidth + 'C';
+ var padding = '';
+ write(dist);
+ write('_,------,');
+ write('\n');
+ write(dist);
+ padding = self.tick ? ' ' : ' ';
+ write('_|' + padding + '/\\_/\\ ');
+ write('\n');
+ write(dist);
+ padding = self.tick ? '_' : '__';
+ var tail = self.tick ? '~' : '^';
+ write(tail + '|' + padding + this.face() + ' ');
+ write('\n');
+ write(dist);
+ padding = self.tick ? ' ' : ' ';
+ write(padding + '"" "" ');
+ write('\n');
+ this.cursorUp(this.numberOfLines);
+ };
+ /**
+ * Draw nyan cat face.
+ *
+ * @private
+ * @return {string}
+ */
+
+
+ NyanCat.prototype.face = function () {
+ var stats = this.stats;
+
+ if (stats.failures) {
+ return '( x .x)';
+ } else if (stats.pending) {
+ return '( o .o)';
+ } else if (stats.passes) {
+ return '( ^ .^)';
+ }
+
+ return '( - .-)';
+ };
+ /**
+ * Move cursor up `n`.
+ *
+ * @private
+ * @param {number} n
+ */
+
+
+ NyanCat.prototype.cursorUp = function (n) {
+ write("\x1B[" + n + 'A');
+ };
+ /**
+ * Move cursor down `n`.
+ *
+ * @private
+ * @param {number} n
+ */
+
+
+ NyanCat.prototype.cursorDown = function (n) {
+ write("\x1B[" + n + 'B');
+ };
+ /**
+ * Generate rainbow colors.
+ *
+ * @private
+ * @return {Array}
+ */
+
+
+ NyanCat.prototype.generateColors = function () {
+ var colors = [];
+
+ for (var i = 0; i < 6 * 7; i++) {
+ var pi3 = Math.floor(Math.PI / 3);
+ var n = i * (1.0 / 6);
+ var r = Math.floor(3 * Math.sin(n) + 3);
+ var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
+ var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
+ colors.push(36 * r + 6 * g + b + 16);
+ }
+
+ return colors;
+ };
+ /**
+ * Apply rainbow to the given `str`.
+ *
+ * @private
+ * @param {string} str
+ * @return {string}
+ */
+
+
+ NyanCat.prototype.rainbowify = function (str) {
+ if (!base.useColors) {
+ return str;
+ }
+
+ var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
+ this.colorIndex += 1;
+ return "\x1B[38;5;" + color + 'm' + str + "\x1B[0m";
+ };
+ /**
+ * Stdout helper.
+ *
+ * @param {string} string A message to write to stdout.
+ */
+
+
+ function write(string) {
+ process$4.stdout.write(string);
+ }
+
+ NyanCat.description = '"nyan cat"';
+ });
+
+ var xunit = createCommonjsModule(function (module, exports) {
+ /**
+ * @module XUnit
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var createUnsupportedError = errors.createUnsupportedError;
+ var constants = runner.constants;
+ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
+ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
+ var EVENT_RUN_END = constants.EVENT_RUN_END;
+ var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
+ var STATE_FAILED = runnable.constants.STATE_FAILED;
+ var inherits = utils.inherits;
+ var escape = utils.escape;
+ /**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+ var Date = commonjsGlobal.Date;
+ /**
+ * Expose `XUnit`.
+ */
+
+ module.exports = XUnit;
+ /**
+ * Constructs a new `XUnit` reporter instance.
+ *
+ * @public
+ * @class
+ * @memberof Mocha.reporters
+ * @extends Mocha.reporters.Base
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+ function XUnit(runner, options) {
+ base.call(this, runner, options);
+ var stats = this.stats;
+ var tests = [];
+ var self = this; // the name of the test suite, as it will appear in the resulting XML file
+
+ var suiteName; // the default name of the test suite if none is provided
+
+ var DEFAULT_SUITE_NAME = 'Mocha Tests';
+
+ if (options && options.reporterOptions) {
+ if (options.reporterOptions.output) {
+ {
+ throw createUnsupportedError('file output not supported in browser');
+ }
+ } // get the suite name from the reporter options (if provided)
+
+
+ suiteName = options.reporterOptions.suiteName;
+ } // fall back to the default suite name
+
+
+ suiteName = suiteName || DEFAULT_SUITE_NAME;
+ runner.on(EVENT_TEST_PENDING, function (test) {
+ tests.push(test);
+ });
+ runner.on(EVENT_TEST_PASS, function (test) {
+ tests.push(test);
+ });
+ runner.on(EVENT_TEST_FAIL, function (test) {
+ tests.push(test);
+ });
+ runner.once(EVENT_RUN_END, function () {
+ self.write(tag('testsuite', {
+ name: suiteName,
+ tests: stats.tests,
+ failures: 0,
+ errors: stats.failures,
+ skipped: stats.tests - stats.failures - stats.passes,
+ timestamp: new Date().toUTCString(),
+ time: stats.duration / 1000 || 0
+ }, false));
+ tests.forEach(function (t) {
+ self.test(t);
+ });
+ self.write('');
+ });
+ }
+ /**
+ * Inherit from `Base.prototype`.
+ */
+
+
+ inherits(XUnit, base);
+ /**
+ * Override done to close the stream (if it's a file).
+ *
+ * @param failures
+ * @param {Function} fn
+ */
+
+ XUnit.prototype.done = function (failures, fn) {
+ if (this.fileStream) {
+ this.fileStream.end(function () {
+ fn(failures);
+ });
+ } else {
+ fn(failures);
+ }
+ };
+ /**
+ * Write out the given line.
+ *
+ * @param {string} line
+ */
+
+
+ XUnit.prototype.write = function (line) {
+ if (this.fileStream) {
+ this.fileStream.write(line + '\n');
+ } else if (_typeof(process$4) === 'object' && process$4.stdout) {
+ process$4.stdout.write(line + '\n');
+ } else {
+ base.consoleLog(line);
+ }
+ };
+ /**
+ * Output tag for the given `test.`
+ *
+ * @param {Test} test
+ */
+
+
+ XUnit.prototype.test = function (test) {
+ base.useColors = false;
+ var attrs = {
+ classname: test.parent.fullTitle(),
+ name: test.title,
+ time: test.duration / 1000 || 0
+ };
+
+ if (test.state === STATE_FAILED) {
+ var err = test.err;
+ var diff = !base.hideDiff && base.showDiff(err) ? '\n' + base.generateDiff(err.actual, err.expected) : '';
+ this.write(tag('testcase', attrs, false, tag('failure', {}, false, escape(err.message) + escape(diff) + '\n' + escape(err.stack))));
+ } else if (test.isPending()) {
+ this.write(tag('testcase', attrs, false, tag('skipped', {}, true)));
+ } else {
+ this.write(tag('testcase', attrs, true));
+ }
+ };
+ /**
+ * HTML tag helper.
+ *
+ * @param name
+ * @param attrs
+ * @param close
+ * @param content
+ * @return {string}
+ */
+
+
+ function tag(name, attrs, close, content) {
+ var end = close ? '/>' : '>';
+ var pairs = [];
+ var tag;
+
+ for (var key in attrs) {
+ if (Object.prototype.hasOwnProperty.call(attrs, key)) {
+ pairs.push(key + '="' + escape(attrs[key]) + '"');
+ }
+ }
+
+ tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
+
+ if (content) {
+ tag += content + '' + name + end;
+ }
+
+ return tag;
+ }
+
+ XUnit.description = 'XUnit-compatible XML output';
+ });
+
+ var markdown = createCommonjsModule(function (module, exports) {
+ /**
+ * @module Markdown
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var constants = runner.constants;
+ var EVENT_RUN_END = constants.EVENT_RUN_END;
+ var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
+ var EVENT_SUITE_END = constants.EVENT_SUITE_END;
+ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
+ /**
+ * Constants
+ */
+
+ var SUITE_PREFIX = '$';
+ /**
+ * Expose `Markdown`.
+ */
+
+ module.exports = Markdown;
+ /**
+ * Constructs a new `Markdown` reporter instance.
+ *
+ * @public
+ * @class
+ * @memberof Mocha.reporters
+ * @extends Mocha.reporters.Base
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+ function Markdown(runner, options) {
+ base.call(this, runner, options);
+ var level = 0;
+ var buf = '';
+
+ function title(str) {
+ return Array(level).join('#') + ' ' + str;
+ }
+
+ function mapTOC(suite, obj) {
+ var ret = obj;
+ var key = SUITE_PREFIX + suite.title;
+ obj = obj[key] = obj[key] || {
+ suite: suite
+ };
+ suite.suites.forEach(function (suite) {
+ mapTOC(suite, obj);
+ });
+ return ret;
+ }
+
+ function stringifyTOC(obj, level) {
+ ++level;
+ var buf = '';
+ var link;
+
+ for (var key in obj) {
+ if (key === 'suite') {
+ continue;
+ }
+
+ if (key !== SUITE_PREFIX) {
+ link = ' - [' + key.substring(1) + ']';
+ link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
+ buf += Array(level).join(' ') + link;
+ }
+
+ buf += stringifyTOC(obj[key], level);
+ }
+
+ return buf;
+ }
+
+ function generateTOC(suite) {
+ var obj = mapTOC(suite, {});
+ return stringifyTOC(obj, 0);
+ }
+
+ generateTOC(runner.suite);
+ runner.on(EVENT_SUITE_BEGIN, function (suite) {
+ ++level;
+ var slug = utils.slug(suite.fullTitle());
+ buf += ' ' + '\n';
+ buf += title(suite.title) + '\n';
+ });
+ runner.on(EVENT_SUITE_END, function () {
+ --level;
+ });
+ runner.on(EVENT_TEST_PASS, function (test) {
+ var code = utils.clean(test.body);
+ buf += test.title + '.\n';
+ buf += '\n```js\n';
+ buf += code + '\n';
+ buf += '```\n\n';
+ });
+ runner.once(EVENT_RUN_END, function () {
+ process$4.stdout.write('# TOC\n');
+ process$4.stdout.write(generateTOC(runner.suite));
+ process$4.stdout.write(buf);
+ });
+ }
+
+ Markdown.description = 'GitHub Flavored Markdown';
+ });
+
+ var progress = createCommonjsModule(function (module, exports) {
+ /**
+ * @module Progress
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var constants = runner.constants;
+ var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
+ var EVENT_TEST_END = constants.EVENT_TEST_END;
+ var EVENT_RUN_END = constants.EVENT_RUN_END;
+ var inherits = utils.inherits;
+ var color = base.color;
+ var cursor = base.cursor;
+ /**
+ * Expose `Progress`.
+ */
+
+ module.exports = Progress;
+ /**
+ * General progress bar color.
+ */
+
+ base.colors.progress = 90;
+ /**
+ * Constructs a new `Progress` reporter instance.
+ *
+ * @public
+ * @class
+ * @memberof Mocha.reporters
+ * @extends Mocha.reporters.Base
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+ function Progress(runner, options) {
+ base.call(this, runner, options);
+ var self = this;
+ var width = base.window.width * 0.5 | 0;
+ var total = runner.total;
+ var complete = 0;
+ var lastN = -1; // default chars
+
+ options = options || {};
+ var reporterOptions = options.reporterOptions || {};
+ options.open = reporterOptions.open || '[';
+ options.complete = reporterOptions.complete || '▬';
+ options.incomplete = reporterOptions.incomplete || base.symbols.dot;
+ options.close = reporterOptions.close || ']';
+ options.verbose = reporterOptions.verbose || false; // tests started
+
+ runner.on(EVENT_RUN_BEGIN, function () {
+ process$4.stdout.write('\n');
+ cursor.hide();
+ }); // tests complete
+
+ runner.on(EVENT_TEST_END, function () {
+ complete++;
+ var percent = complete / total;
+ var n = width * percent | 0;
+ var i = width - n;
+
+ if (n === lastN && !options.verbose) {
+ // Don't re-render the line if it hasn't changed
+ return;
+ }
+
+ lastN = n;
+ cursor.CR();
+ process$4.stdout.write("\x1B[J");
+ process$4.stdout.write(color('progress', ' ' + options.open));
+ process$4.stdout.write(Array(n).join(options.complete));
+ process$4.stdout.write(Array(i).join(options.incomplete));
+ process$4.stdout.write(color('progress', options.close));
+
+ if (options.verbose) {
+ process$4.stdout.write(color('progress', ' ' + complete + ' of ' + total));
+ }
+ }); // tests are complete, output some stats
+ // and the failures if any
+
+ runner.once(EVENT_RUN_END, function () {
+ cursor.show();
+ process$4.stdout.write('\n');
+ self.epilogue();
+ });
+ }
+ /**
+ * Inherit from `Base.prototype`.
+ */
+
+
+ inherits(Progress, base);
+ Progress.description = 'a progress bar';
+ });
+
+ var landing = createCommonjsModule(function (module, exports) {
+ /**
+ * @module Landing
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var inherits = utils.inherits;
+ var constants = runner.constants;
+ var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
+ var EVENT_RUN_END = constants.EVENT_RUN_END;
+ var EVENT_TEST_END = constants.EVENT_TEST_END;
+ var STATE_FAILED = runnable.constants.STATE_FAILED;
+ var cursor = base.cursor;
+ var color = base.color;
+ /**
+ * Expose `Landing`.
+ */
+
+ module.exports = Landing;
+ /**
+ * Airplane color.
+ */
+
+ base.colors.plane = 0;
+ /**
+ * Airplane crash color.
+ */
+
+ base.colors['plane crash'] = 31;
+ /**
+ * Runway color.
+ */
+
+ base.colors.runway = 90;
+ /**
+ * Constructs a new `Landing` reporter instance.
+ *
+ * @public
+ * @class
+ * @memberof Mocha.reporters
+ * @extends Mocha.reporters.Base
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+ function Landing(runner, options) {
+ base.call(this, runner, options);
+ var self = this;
+ var width = base.window.width * 0.75 | 0;
+ var stream = process$4.stdout;
+ var plane = color('plane', '✈');
+ var crashed = -1;
+ var n = 0;
+ var total = 0;
+
+ function runway() {
+ var buf = Array(width).join('-');
+ return ' ' + color('runway', buf);
+ }
+
+ runner.on(EVENT_RUN_BEGIN, function () {
+ stream.write('\n\n\n ');
+ cursor.hide();
+ });
+ runner.on(EVENT_TEST_END, function (test) {
+ // check if the plane crashed
+ var col = crashed === -1 ? width * ++n / ++total | 0 : crashed; // show the crash
+
+ if (test.state === STATE_FAILED) {
+ plane = color('plane crash', '✈');
+ crashed = col;
+ } // render landing strip
+
+
+ stream.write("\x1B[" + (width + 1) + "D\x1B[2A");
+ stream.write(runway());
+ stream.write('\n ');
+ stream.write(color('runway', Array(col).join('⋅')));
+ stream.write(plane);
+ stream.write(color('runway', Array(width - col).join('⋅') + '\n'));
+ stream.write(runway());
+ stream.write("\x1B[0m");
+ });
+ runner.once(EVENT_RUN_END, function () {
+ cursor.show();
+ process$4.stdout.write('\n');
+ self.epilogue();
+ }); // if cursor is hidden when we ctrl-C, then it will remain hidden unless...
+
+ process$4.once('SIGINT', function () {
+ cursor.show();
+ nextTick$1(function () {
+ process$4.kill(process$4.pid, 'SIGINT');
+ });
+ });
+ }
+ /**
+ * Inherit from `Base.prototype`.
+ */
+
+
+ inherits(Landing, base);
+ Landing.description = 'Unicode landing strip';
+ });
+
+ var jsonStream = createCommonjsModule(function (module, exports) {
+ /**
+ * @module JSONStream
+ */
+
+ /**
+ * Module dependencies.
+ */
+
+ var constants = runner.constants;
+ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
+ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
+ var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
+ var EVENT_RUN_END = constants.EVENT_RUN_END;
+ /**
+ * Expose `JSONStream`.
+ */
+
+ module.exports = JSONStream;
+ /**
+ * Constructs a new `JSONStream` reporter instance.
+ *
+ * @public
+ * @class
+ * @memberof Mocha.reporters
+ * @extends Mocha.reporters.Base
+ * @param {Runner} runner - Instance triggers reporter actions.
+ * @param {Object} [options] - runner options
+ */
+
+ function JSONStream(runner, options) {
+ base.call(this, runner, options);
+ var self = this;
+ var total = runner.total;
+ runner.once(EVENT_RUN_BEGIN, function () {
+ writeEvent(['start', {
+ total: total
+ }]);
+ });
+ runner.on(EVENT_TEST_PASS, function (test) {
+ writeEvent(['pass', clean(test)]);
+ });
+ runner.on(EVENT_TEST_FAIL, function (test, err) {
+ test = clean(test);
+ test.err = err.message;
+ test.stack = err.stack || null;
+ writeEvent(['fail', test]);
+ });
+ runner.once(EVENT_RUN_END, function () {
+ writeEvent(['end', self.stats]);
+ });
+ }
+ /**
+ * Mocha event to be written to the output stream.
+ * @typedef {Array} JSONStream~MochaEvent
+ */
+
+ /**
+ * Writes Mocha event to reporter output stream.
+ *
+ * @private
+ * @param {JSONStream~MochaEvent} event - Mocha event to be output.
+ */
+
+
+ function writeEvent(event) {
+ process$4.stdout.write(JSON.stringify(event) + '\n');
+ }
+ /**
+ * Returns an object literal representation of `test`
+ * free of cyclic properties, etc.
+ *
+ * @private
+ * @param {Test} test - Instance used as data source.
+ * @return {Object} object containing pared-down test instance data
+ */
+
+
+ function clean(test) {
+ return {
+ title: test.title,
+ fullTitle: test.fullTitle(),
+ file: test.file,
+ duration: test.duration,
+ currentRetry: test.currentRetry(),
+ speed: test.speed
+ };
+ }
+
+ JSONStream.description = 'newline delimited JSON events';
+ });
+
+ var reporters = createCommonjsModule(function (module, exports) {
+ // for dynamic (try/catch) requires, which Browserify doesn't handle.
+
+ exports.Base = exports.base = base;
+ exports.Dot = exports.dot = dot;
+ exports.Doc = exports.doc = doc;
+ exports.TAP = exports.tap = tap;
+ exports.JSON = exports.json = json;
+ exports.HTML = exports.html = html;
+ exports.List = exports.list = list;
+ exports.Min = exports.min = min;
+ exports.Spec = exports.spec = spec;
+ exports.Nyan = exports.nyan = nyan;
+ exports.XUnit = exports.xunit = xunit;
+ exports.Markdown = exports.markdown = markdown;
+ exports.Progress = exports.progress = progress;
+ exports.Landing = exports.landing = landing;
+ exports.JSONStream = exports['json-stream'] = jsonStream;
+ });
+
+ var name = "mocha";
+ var version = "9.1.2";
+ var homepage = "https://mochajs.org/";
+ var notifyLogo = "https://ibin.co/4QuRuGjXvl36.png";
+ var _package = {
+ name: name,
+ version: version,
+ homepage: homepage,
+ notifyLogo: notifyLogo
+ };
+
+ var _package$1 = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ name: name,
+ version: version,
+ homepage: homepage,
+ notifyLogo: notifyLogo,
+ 'default': _package
+ });
+
+ var require$$9 = getCjsExportFromNamespace(_package$1);
+
+ /**
+ * Web Notifications module.
+ * @module Growl
+ */
+
+ /**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+
+ var Date$3 = commonjsGlobal.Date;
+ var setTimeout$2 = commonjsGlobal.setTimeout;
+ var EVENT_RUN_END$1 = runner.constants.EVENT_RUN_END;
+ var isBrowser = utils.isBrowser;
+ /**
+ * Checks if browser notification support exists.
+ *
+ * @public
+ * @see {@link https://caniuse.com/#feat=notifications|Browser support (notifications)}
+ * @see {@link https://caniuse.com/#feat=promises|Browser support (promises)}
+ * @see {@link Mocha#growl}
+ * @see {@link Mocha#isGrowlCapable}
+ * @return {boolean} whether browser notification support exists
+ */
+
+ var isCapable = function isCapable() {
+ var hasNotificationSupport = ('Notification' in window);
+ var hasPromiseSupport = typeof Promise === 'function';
+ return isBrowser() && hasNotificationSupport && hasPromiseSupport;
+ };
+ /**
+ * Implements browser notifications as a pseudo-reporter.
+ *
+ * @public
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/notification|Notification API}
+ * @see {@link https://developers.google.com/web/fundamentals/push-notifications/display-a-notification|Displaying a Notification}
+ * @see {@link Growl#isPermitted}
+ * @see {@link Mocha#_growl}
+ * @param {Runner} runner - Runner instance.
+ */
+
+
+ var notify = function notify(runner) {
+ var promise = isPermitted();
+ /**
+ * Attempt notification.
+ */
+
+ var sendNotification = function sendNotification() {
+ // If user hasn't responded yet... "No notification for you!" (Seinfeld)
+ Promise.race([promise, Promise.resolve(undefined)]).then(canNotify).then(function () {
+ display(runner);
+ })["catch"](notPermitted);
+ };
+
+ runner.once(EVENT_RUN_END$1, sendNotification);
+ };
+ /**
+ * Checks if browser notification is permitted by user.
+ *
+ * @private
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Notification/permission|Notification.permission}
+ * @see {@link Mocha#growl}
+ * @see {@link Mocha#isGrowlPermitted}
+ * @returns {Promise} promise determining if browser notification
+ * permissible when fulfilled.
+ */
+
+
+ function isPermitted() {
+ var permitted = {
+ granted: function allow() {
+ return Promise.resolve(true);
+ },
+ denied: function deny() {
+ return Promise.resolve(false);
+ },
+ "default": function ask() {
+ return Notification.requestPermission().then(function (permission) {
+ return permission === 'granted';
+ });
+ }
+ };
+ return permitted[Notification.permission]();
+ }
+ /**
+ * @summary
+ * Determines if notification should proceed.
+ *
+ * @description
+ * Notification shall not proceed unless `value` is true.
+ *
+ * `value` will equal one of:
+ *
+ * true
(from `isPermitted`)
+ * false
(from `isPermitted`)
+ * undefined
(from `Promise.race`)
+ *
+ *
+ * @private
+ * @param {boolean|undefined} value - Determines if notification permissible.
+ * @returns {Promise} Notification can proceed
+ */
+
+
+ function canNotify(value) {
+ if (!value) {
+ var why = value === false ? 'blocked' : 'unacknowledged';
+ var reason = 'not permitted by user (' + why + ')';
+ return Promise.reject(new Error(reason));
+ }
+
+ return Promise.resolve();
+ }
+ /**
+ * Displays the notification.
+ *
+ * @private
+ * @param {Runner} runner - Runner instance.
+ */
+
+
+ function display(runner) {
+ var stats = runner.stats;
+ var symbol = {
+ cross: "\u274C",
+ tick: "\u2705"
+ };
+ var logo = require$$9.notifyLogo;
+
+ var _message;
+
+ var message;
+ var title;
+
+ if (stats.failures) {
+ _message = stats.failures + ' of ' + stats.tests + ' tests failed';
+ message = symbol.cross + ' ' + _message;
+ title = 'Failed';
+ } else {
+ _message = stats.passes + ' tests passed in ' + stats.duration + 'ms';
+ message = symbol.tick + ' ' + _message;
+ title = 'Passed';
+ } // Send notification
+
+
+ var options = {
+ badge: logo,
+ body: message,
+ dir: 'ltr',
+ icon: logo,
+ lang: 'en-US',
+ name: 'mocha',
+ requireInteraction: false,
+ timestamp: Date$3.now()
+ };
+ var notification = new Notification(title, options); // Autoclose after brief delay (makes various browsers act same)
+
+ var FORCE_DURATION = 4000;
+ setTimeout$2(notification.close.bind(notification), FORCE_DURATION);
+ }
+ /**
+ * As notifications are tangential to our purpose, just log the error.
+ *
+ * @private
+ * @param {Error} err - Why notification didn't happen.
+ */
+
+
+ function notPermitted(err) {
+ console.error('notification error:', err.message);
+ }
+
+ var growl = {
+ isCapable: isCapable,
+ notify: notify
+ };
+
+ var diff = true;
+ var extension = [
+ "js",
+ "cjs",
+ "mjs"
+ ];
+ var reporter = "spec";
+ var slow = 75;
+ var timeout = 2000;
+ var ui = "bdd";
+ var mocharc$1 = {
+ diff: diff,
+ extension: extension,
+ "package": "./package.json",
+ reporter: reporter,
+ slow: slow,
+ timeout: timeout,
+ ui: ui,
+ "watch-ignore": [
+ "node_modules",
+ ".git"
+ ]
+ };
+
+ var mocharc$2 = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ diff: diff,
+ extension: extension,
+ reporter: reporter,
+ slow: slow,
+ timeout: timeout,
+ ui: ui,
+ 'default': mocharc$1
+ });
+
+ /**
+ * Provides a factory function for a {@link StatsCollector} object.
+ * @module
+ */
+
+
+ var constants = runner.constants;
+ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
+ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
+ var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
+ var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
+ var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
+ var EVENT_RUN_END = constants.EVENT_RUN_END;
+ var EVENT_TEST_END = constants.EVENT_TEST_END;
+ /**
+ * Test statistics collector.
+ *
+ * @public
+ * @typedef {Object} StatsCollector
+ * @property {number} suites - integer count of suites run.
+ * @property {number} tests - integer count of tests run.
+ * @property {number} passes - integer count of passing tests.
+ * @property {number} pending - integer count of pending tests.
+ * @property {number} failures - integer count of failed tests.
+ * @property {Date} start - time when testing began.
+ * @property {Date} end - time when testing concluded.
+ * @property {number} duration - number of msecs that testing took.
+ */
+
+ var Date$2 = commonjsGlobal.Date;
+ /**
+ * Provides stats such as test duration, number of tests passed / failed etc., by listening for events emitted by `runner`.
+ *
+ * @private
+ * @param {Runner} runner - Runner instance
+ * @throws {TypeError} If falsy `runner`
+ */
+
+ function createStatsCollector(runner) {
+ /**
+ * @type StatsCollector
+ */
+ var stats = {
+ suites: 0,
+ tests: 0,
+ passes: 0,
+ pending: 0,
+ failures: 0
+ };
+
+ if (!runner) {
+ throw new TypeError('Missing runner argument');
+ }
+
+ runner.stats = stats;
+ runner.once(EVENT_RUN_BEGIN, function () {
+ stats.start = new Date$2();
+ });
+ runner.on(EVENT_SUITE_BEGIN, function (suite) {
+ suite.root || stats.suites++;
+ });
+ runner.on(EVENT_TEST_PASS, function () {
+ stats.passes++;
+ });
+ runner.on(EVENT_TEST_FAIL, function () {
+ stats.failures++;
+ });
+ runner.on(EVENT_TEST_PENDING, function () {
+ stats.pending++;
+ });
+ runner.on(EVENT_TEST_END, function () {
+ stats.tests++;
+ });
+ runner.once(EVENT_RUN_END, function () {
+ stats.end = new Date$2();
+ stats.duration = stats.end - stats.start;
+ });
+ }
+
+ var statsCollector = createStatsCollector;
+
+ var createInvalidArgumentTypeError = errors.createInvalidArgumentTypeError;
+ var isString = utils.isString;
+ var MOCHA_ID_PROP_NAME = utils.constants.MOCHA_ID_PROP_NAME;
+ var test = Test;
+ /**
+ * Initialize a new `Test` with the given `title` and callback `fn`.
+ *
+ * @public
+ * @class
+ * @extends Runnable
+ * @param {String} title - Test title (required)
+ * @param {Function} [fn] - Test callback. If omitted, the Test is considered "pending"
+ */
+
+ function Test(title, fn) {
+ if (!isString(title)) {
+ throw createInvalidArgumentTypeError('Test argument "title" should be a string. Received type "' + _typeof(title) + '"', 'title', 'string');
+ }
+
+ this.type = 'test';
+ runnable.call(this, title, fn);
+ this.reset();
+ }
+ /**
+ * Inherit from `Runnable.prototype`.
+ */
+
+
+ utils.inherits(Test, runnable);
+ /**
+ * Resets the state initially or for a next run.
+ */
+
+ Test.prototype.reset = function () {
+ runnable.prototype.reset.call(this);
+ this.pending = !this.fn;
+ delete this.state;
+ };
+ /**
+ * Set or get retried test
+ *
+ * @private
+ */
+
+
+ Test.prototype.retriedTest = function (n) {
+ if (!arguments.length) {
+ return this._retriedTest;
+ }
+
+ this._retriedTest = n;
+ };
+ /**
+ * Add test to the list of tests marked `only`.
+ *
+ * @private
+ */
+
+
+ Test.prototype.markOnly = function () {
+ this.parent.appendOnlyTest(this);
+ };
+
+ Test.prototype.clone = function () {
+ var test = new Test(this.title, this.fn);
+ test.timeout(this.timeout());
+ test.slow(this.slow());
+ test.retries(this.retries());
+ test.currentRetry(this.currentRetry());
+ test.retriedTest(this.retriedTest() || this);
+ test.globals(this.globals());
+ test.parent = this.parent;
+ test.file = this.file;
+ test.ctx = this.ctx;
+ return test;
+ };
+ /**
+ * Returns an minimal object suitable for transmission over IPC.
+ * Functions are represented by keys beginning with `$$`.
+ * @private
+ * @returns {Object}
+ */
+
+
+ Test.prototype.serialize = function serialize() {
+ return _defineProperty({
+ $$currentRetry: this._currentRetry,
+ $$fullTitle: this.fullTitle(),
+ $$isPending: Boolean(this.pending),
+ $$retriedTest: this._retriedTest || null,
+ $$slow: this._slow,
+ $$titlePath: this.titlePath(),
+ body: this.body,
+ duration: this.duration,
+ err: this.err,
+ parent: _defineProperty({
+ $$fullTitle: this.parent.fullTitle()
+ }, MOCHA_ID_PROP_NAME, this.parent.id),
+ speed: this.speed,
+ state: this.state,
+ title: this.title,
+ type: this.type,
+ file: this.file
+ }, MOCHA_ID_PROP_NAME, this.id);
+ };
+
+ /**
+ @module interfaces/common
+ */
+
+
+ var createMissingArgumentError = errors.createMissingArgumentError;
+ var createUnsupportedError = errors.createUnsupportedError;
+ var createForbiddenExclusivityError = errors.createForbiddenExclusivityError;
+ /**
+ * Functions common to more than one interface.
+ *
+ * @private
+ * @param {Suite[]} suites
+ * @param {Context} context
+ * @param {Mocha} mocha
+ * @return {Object} An object containing common functions.
+ */
+
+ var common = function common(suites, context, mocha) {
+ /**
+ * Check if the suite should be tested.
+ *
+ * @private
+ * @param {Suite} suite - suite to check
+ * @returns {boolean}
+ */
+ function shouldBeTested(suite) {
+ return !mocha.options.grep || mocha.options.grep && mocha.options.grep.test(suite.fullTitle()) && !mocha.options.invert;
+ }
+
+ return {
+ /**
+ * This is only present if flag --delay is passed into Mocha. It triggers
+ * root suite execution.
+ *
+ * @param {Suite} suite The root suite.
+ * @return {Function} A function which runs the root suite
+ */
+ runWithSuite: function runWithSuite(suite) {
+ return function run() {
+ suite.run();
+ };
+ },
+
+ /**
+ * Execute before running tests.
+ *
+ * @param {string} name
+ * @param {Function} fn
+ */
+ before: function before(name, fn) {
+ suites[0].beforeAll(name, fn);
+ },
+
+ /**
+ * Execute after running tests.
+ *
+ * @param {string} name
+ * @param {Function} fn
+ */
+ after: function after(name, fn) {
+ suites[0].afterAll(name, fn);
+ },
+
+ /**
+ * Execute before each test case.
+ *
+ * @param {string} name
+ * @param {Function} fn
+ */
+ beforeEach: function beforeEach(name, fn) {
+ suites[0].beforeEach(name, fn);
+ },
+
+ /**
+ * Execute after each test case.
+ *
+ * @param {string} name
+ * @param {Function} fn
+ */
+ afterEach: function afterEach(name, fn) {
+ suites[0].afterEach(name, fn);
+ },
+ suite: {
+ /**
+ * Create an exclusive Suite; convenience function
+ * See docstring for create() below.
+ *
+ * @param {Object} opts
+ * @returns {Suite}
+ */
+ only: function only(opts) {
+ if (mocha.options.forbidOnly) {
+ throw createForbiddenExclusivityError(mocha);
+ }
+
+ opts.isOnly = true;
+ return this.create(opts);
+ },
+
+ /**
+ * Create a Suite, but skip it; convenience function
+ * See docstring for create() below.
+ *
+ * @param {Object} opts
+ * @returns {Suite}
+ */
+ skip: function skip(opts) {
+ opts.pending = true;
+ return this.create(opts);
+ },
+
+ /**
+ * Creates a suite.
+ *
+ * @param {Object} opts Options
+ * @param {string} opts.title Title of Suite
+ * @param {Function} [opts.fn] Suite Function (not always applicable)
+ * @param {boolean} [opts.pending] Is Suite pending?
+ * @param {string} [opts.file] Filepath where this Suite resides
+ * @param {boolean} [opts.isOnly] Is Suite exclusive?
+ * @returns {Suite}
+ */
+ create: function create(opts) {
+ var suite$1 = suite.create(suites[0], opts.title);
+ suite$1.pending = Boolean(opts.pending);
+ suite$1.file = opts.file;
+ suites.unshift(suite$1);
+
+ if (opts.isOnly) {
+ suite$1.markOnly();
+ }
+
+ if (suite$1.pending && mocha.options.forbidPending && shouldBeTested(suite$1)) {
+ throw createUnsupportedError('Pending test forbidden');
+ }
+
+ if (typeof opts.fn === 'function') {
+ opts.fn.call(suite$1);
+ suites.shift();
+ } else if (typeof opts.fn === 'undefined' && !suite$1.pending) {
+ throw createMissingArgumentError('Suite "' + suite$1.fullTitle() + '" was defined but no callback was supplied. ' + 'Supply a callback or explicitly skip the suite.', 'callback', 'function');
+ } else if (!opts.fn && suite$1.pending) {
+ suites.shift();
+ }
+
+ return suite$1;
+ }
+ },
+ test: {
+ /**
+ * Exclusive test-case.
+ *
+ * @param {Object} mocha
+ * @param {Function} test
+ * @returns {*}
+ */
+ only: function only(mocha, test) {
+ if (mocha.options.forbidOnly) {
+ throw createForbiddenExclusivityError(mocha);
+ }
+
+ test.markOnly();
+ return test;
+ },
+
+ /**
+ * Pending test case.
+ *
+ * @param {string} title
+ */
+ skip: function skip(title) {
+ context.test(title);
+ }
+ }
+ };
+ };
+
+ var EVENT_FILE_PRE_REQUIRE$2 = suite.constants.EVENT_FILE_PRE_REQUIRE;
+ /**
+ * BDD-style interface:
+ *
+ * describe('Array', function() {
+ * describe('#indexOf()', function() {
+ * it('should return -1 when not present', function() {
+ * // ...
+ * });
+ *
+ * it('should return the index when present', function() {
+ * // ...
+ * });
+ * });
+ * });
+ *
+ * @param {Suite} suite Root suite.
+ */
+
+ var bdd$1 = function bddInterface(suite) {
+ var suites = [suite];
+ suite.on(EVENT_FILE_PRE_REQUIRE$2, function (context, file, mocha) {
+ var common$1 = common(suites, context, mocha);
+ context.before = common$1.before;
+ context.after = common$1.after;
+ context.beforeEach = common$1.beforeEach;
+ context.afterEach = common$1.afterEach;
+ context.run = mocha.options.delay && common$1.runWithSuite(suite);
+ /**
+ * Describe a "suite" with the given `title`
+ * and callback `fn` containing nested suites
+ * and/or tests.
+ */
+
+ context.describe = context.context = function (title, fn) {
+ return common$1.suite.create({
+ title: title,
+ file: file,
+ fn: fn
+ });
+ };
+ /**
+ * Pending describe.
+ */
+
+
+ context.xdescribe = context.xcontext = context.describe.skip = function (title, fn) {
+ return common$1.suite.skip({
+ title: title,
+ file: file,
+ fn: fn
+ });
+ };
+ /**
+ * Exclusive suite.
+ */
+
+
+ context.describe.only = function (title, fn) {
+ return common$1.suite.only({
+ title: title,
+ file: file,
+ fn: fn
+ });
+ };
+ /**
+ * Describe a specification or test-case
+ * with the given `title` and callback `fn`
+ * acting as a thunk.
+ */
+
+
+ context.it = context.specify = function (title, fn) {
+ var suite = suites[0];
+
+ if (suite.isPending()) {
+ fn = null;
+ }
+
+ var test$1 = new test(title, fn);
+ test$1.file = file;
+ suite.addTest(test$1);
+ return test$1;
+ };
+ /**
+ * Exclusive test-case.
+ */
+
+
+ context.it.only = function (title, fn) {
+ return common$1.test.only(mocha, context.it(title, fn));
+ };
+ /**
+ * Pending test case.
+ */
+
+
+ context.xit = context.xspecify = context.it.skip = function (title) {
+ return context.it(title);
+ };
+ });
+ };
+
+ var description$3 = 'BDD or RSpec style [default]';
+ bdd$1.description = description$3;
+
+ var EVENT_FILE_PRE_REQUIRE$1 = suite.constants.EVENT_FILE_PRE_REQUIRE;
+ /**
+ * TDD-style interface:
+ *
+ * suite('Array', function() {
+ * suite('#indexOf()', function() {
+ * suiteSetup(function() {
+ *
+ * });
+ *
+ * test('should return -1 when not present', function() {
+ *
+ * });
+ *
+ * test('should return the index when present', function() {
+ *
+ * });
+ *
+ * suiteTeardown(function() {
+ *
+ * });
+ * });
+ * });
+ *
+ * @param {Suite} suite Root suite.
+ */
+
+ var tdd$1 = function tdd(suite) {
+ var suites = [suite];
+ suite.on(EVENT_FILE_PRE_REQUIRE$1, function (context, file, mocha) {
+ var common$1 = common(suites, context, mocha);
+ context.setup = common$1.beforeEach;
+ context.teardown = common$1.afterEach;
+ context.suiteSetup = common$1.before;
+ context.suiteTeardown = common$1.after;
+ context.run = mocha.options.delay && common$1.runWithSuite(suite);
+ /**
+ * Describe a "suite" with the given `title` and callback `fn` containing
+ * nested suites and/or tests.
+ */
+
+ context.suite = function (title, fn) {
+ return common$1.suite.create({
+ title: title,
+ file: file,
+ fn: fn
+ });
+ };
+ /**
+ * Pending suite.
+ */
+
+
+ context.suite.skip = function (title, fn) {
+ return common$1.suite.skip({
+ title: title,
+ file: file,
+ fn: fn
+ });
+ };
+ /**
+ * Exclusive test-case.
+ */
+
+
+ context.suite.only = function (title, fn) {
+ return common$1.suite.only({
+ title: title,
+ file: file,
+ fn: fn
+ });
+ };
+ /**
+ * Describe a specification or test-case with the given `title` and
+ * callback `fn` acting as a thunk.
+ */
+
+
+ context.test = function (title, fn) {
+ var suite = suites[0];
+
+ if (suite.isPending()) {
+ fn = null;
+ }
+
+ var test$1 = new test(title, fn);
+ test$1.file = file;
+ suite.addTest(test$1);
+ return test$1;
+ };
+ /**
+ * Exclusive test-case.
+ */
+
+
+ context.test.only = function (title, fn) {
+ return common$1.test.only(mocha, context.test(title, fn));
+ };
+
+ context.test.skip = common$1.test.skip;
+ });
+ };
+
+ var description$2 = 'traditional "suite"/"test" instead of BDD\'s "describe"/"it"';
+ tdd$1.description = description$2;
+
+ var EVENT_FILE_PRE_REQUIRE = suite.constants.EVENT_FILE_PRE_REQUIRE;
+ /**
+ * QUnit-style interface:
+ *
+ * suite('Array');
+ *
+ * test('#length', function() {
+ * var arr = [1,2,3];
+ * ok(arr.length == 3);
+ * });
+ *
+ * test('#indexOf()', function() {
+ * var arr = [1,2,3];
+ * ok(arr.indexOf(1) == 0);
+ * ok(arr.indexOf(2) == 1);
+ * ok(arr.indexOf(3) == 2);
+ * });
+ *
+ * suite('String');
+ *
+ * test('#length', function() {
+ * ok('foo'.length == 3);
+ * });
+ *
+ * @param {Suite} suite Root suite.
+ */
+
+ var qunit$1 = function qUnitInterface(suite) {
+ var suites = [suite];
+ suite.on(EVENT_FILE_PRE_REQUIRE, function (context, file, mocha) {
+ var common$1 = common(suites, context, mocha);
+ context.before = common$1.before;
+ context.after = common$1.after;
+ context.beforeEach = common$1.beforeEach;
+ context.afterEach = common$1.afterEach;
+ context.run = mocha.options.delay && common$1.runWithSuite(suite);
+ /**
+ * Describe a "suite" with the given `title`.
+ */
+
+ context.suite = function (title) {
+ if (suites.length > 1) {
+ suites.shift();
+ }
+
+ return common$1.suite.create({
+ title: title,
+ file: file,
+ fn: false
+ });
+ };
+ /**
+ * Exclusive Suite.
+ */
+
+
+ context.suite.only = function (title) {
+ if (suites.length > 1) {
+ suites.shift();
+ }
+
+ return common$1.suite.only({
+ title: title,
+ file: file,
+ fn: false
+ });
+ };
+ /**
+ * Describe a specification or test-case
+ * with the given `title` and callback `fn`
+ * acting as a thunk.
+ */
+
+
+ context.test = function (title, fn) {
+ var test$1 = new test(title, fn);
+ test$1.file = file;
+ suites[0].addTest(test$1);
+ return test$1;
+ };
+ /**
+ * Exclusive test-case.
+ */
+
+
+ context.test.only = function (title, fn) {
+ return common$1.test.only(mocha, context.test(title, fn));
+ };
+
+ context.test.skip = common$1.test.skip;
+ });
+ };
+
+ var description$1 = 'QUnit style';
+ qunit$1.description = description$1;
+
+ /**
+ * Exports-style (as Node.js module) interface:
+ *
+ * exports.Array = {
+ * '#indexOf()': {
+ * 'should return -1 when the value is not present': function() {
+ *
+ * },
+ *
+ * 'should return the correct index when the value is present': function() {
+ *
+ * }
+ * }
+ * };
+ *
+ * @param {Suite} suite Root suite.
+ */
+
+
+ var exports$2 = function exports(suite$1) {
+ var suites = [suite$1];
+ suite$1.on(suite.constants.EVENT_FILE_REQUIRE, visit);
+
+ function visit(obj, file) {
+ var suite$1;
+
+ for (var key in obj) {
+ if (typeof obj[key] === 'function') {
+ var fn = obj[key];
+
+ switch (key) {
+ case 'before':
+ suites[0].beforeAll(fn);
+ break;
+
+ case 'after':
+ suites[0].afterAll(fn);
+ break;
+
+ case 'beforeEach':
+ suites[0].beforeEach(fn);
+ break;
+
+ case 'afterEach':
+ suites[0].afterEach(fn);
+ break;
+
+ default:
+ var test$1 = new test(key, fn);
+ test$1.file = file;
+ suites[0].addTest(test$1);
+ }
+ } else {
+ suite$1 = suite.create(suites[0], key);
+ suites.unshift(suite$1);
+ visit(obj[key], file);
+ suites.shift();
+ }
+ }
+ }
+ };
+
+ var description = 'Node.js module ("exports") style';
+ exports$2.description = description;
+
+ var bdd = bdd$1;
+ var tdd = tdd$1;
+ var qunit = qunit$1;
+ var exports$1 = exports$2;
+ var interfaces = {
+ bdd: bdd,
+ tdd: tdd,
+ qunit: qunit,
+ exports: exports$1
+ };
+
+ /**
+ * @module Context
+ */
+
+ /**
+ * Expose `Context`.
+ */
+
+ var context = Context;
+ /**
+ * Initialize a new `Context`.
+ *
+ * @private
+ */
+
+ function Context() {}
+ /**
+ * Set or get the context `Runnable` to `runnable`.
+ *
+ * @private
+ * @param {Runnable} runnable
+ * @return {Context} context
+ */
+
+
+ Context.prototype.runnable = function (runnable) {
+ if (!arguments.length) {
+ return this._runnable;
+ }
+
+ this.test = this._runnable = runnable;
+ return this;
+ };
+ /**
+ * Set or get test timeout `ms`.
+ *
+ * @private
+ * @param {number} ms
+ * @return {Context} self
+ */
+
+
+ Context.prototype.timeout = function (ms) {
+ if (!arguments.length) {
+ return this.runnable().timeout();
+ }
+
+ this.runnable().timeout(ms);
+ return this;
+ };
+ /**
+ * Set or get test slowness threshold `ms`.
+ *
+ * @private
+ * @param {number} ms
+ * @return {Context} self
+ */
+
+
+ Context.prototype.slow = function (ms) {
+ if (!arguments.length) {
+ return this.runnable().slow();
+ }
+
+ this.runnable().slow(ms);
+ return this;
+ };
+ /**
+ * Mark a test as skipped.
+ *
+ * @private
+ * @throws Pending
+ */
+
+
+ Context.prototype.skip = function () {
+ this.runnable().skip();
+ };
+ /**
+ * Set or get a number of allowed retries on failed tests
+ *
+ * @private
+ * @param {number} n
+ * @return {Context} self
+ */
+
+
+ Context.prototype.retries = function (n) {
+ if (!arguments.length) {
+ return this.runnable().retries();
+ }
+
+ this.runnable().retries(n);
+ return this;
+ };
+
+ var mocharc = getCjsExportFromNamespace(mocharc$2);
+
+ var mocha$1 = createCommonjsModule(function (module, exports) {
+ /*!
+ * mocha
+ * Copyright(c) 2011 TJ Holowaychuk
+ * MIT Licensed
+ */
+
+ var warn = errors.warn,
+ createInvalidReporterError = errors.createInvalidReporterError,
+ createInvalidInterfaceError = errors.createInvalidInterfaceError,
+ createMochaInstanceAlreadyDisposedError = errors.createMochaInstanceAlreadyDisposedError,
+ createMochaInstanceAlreadyRunningError = errors.createMochaInstanceAlreadyRunningError,
+ createUnsupportedError = errors.createUnsupportedError;
+ var _Suite$constants = suite.constants,
+ EVENT_FILE_PRE_REQUIRE = _Suite$constants.EVENT_FILE_PRE_REQUIRE,
+ EVENT_FILE_POST_REQUIRE = _Suite$constants.EVENT_FILE_POST_REQUIRE,
+ EVENT_FILE_REQUIRE = _Suite$constants.EVENT_FILE_REQUIRE;
+ var debug = browser('mocha:mocha');
+ exports = module.exports = Mocha;
+ /**
+ * A Mocha instance is a finite state machine.
+ * These are the states it can be in.
+ * @private
+ */
+
+ var mochaStates = utils.defineConstants({
+ /**
+ * Initial state of the mocha instance
+ * @private
+ */
+ INIT: 'init',
+
+ /**
+ * Mocha instance is running tests
+ * @private
+ */
+ RUNNING: 'running',
+
+ /**
+ * Mocha instance is done running tests and references to test functions and hooks are cleaned.
+ * You can reset this state by unloading the test files.
+ * @private
+ */
+ REFERENCES_CLEANED: 'referencesCleaned',
+
+ /**
+ * Mocha instance is disposed and can no longer be used.
+ * @private
+ */
+ DISPOSED: 'disposed'
+ });
+ /**
+ * To require local UIs and reporters when running in node.
+ */
+
+ if (!utils.isBrowser() && typeof module.paths !== 'undefined') {
+ var cwd = utils.cwd();
+ module.paths.push(cwd, path.join(cwd, 'node_modules'));
+ }
+ /**
+ * Expose internals.
+ * @private
+ */
+
+
+ exports.utils = utils;
+ exports.interfaces = interfaces;
+ /**
+ * @public
+ * @memberof Mocha
+ */
+
+ exports.reporters = reporters;
+ exports.Runnable = runnable;
+ exports.Context = context;
+ /**
+ *
+ * @memberof Mocha
+ */
+
+ exports.Runner = runner;
+ exports.Suite = suite;
+ exports.Hook = hook;
+ exports.Test = test;
+ var currentContext;
+
+ exports.afterEach = function () {
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ return (currentContext.afterEach || currentContext.teardown).apply(this, args);
+ };
+
+ exports.after = function () {
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ args[_key2] = arguments[_key2];
+ }
+
+ return (currentContext.after || currentContext.suiteTeardown).apply(this, args);
+ };
+
+ exports.beforeEach = function () {
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
+ args[_key3] = arguments[_key3];
+ }
+
+ return (currentContext.beforeEach || currentContext.setup).apply(this, args);
+ };
+
+ exports.before = function () {
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
+ args[_key4] = arguments[_key4];
+ }
+
+ return (currentContext.before || currentContext.suiteSetup).apply(this, args);
+ };
+
+ exports.describe = function () {
+ for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
+ args[_key5] = arguments[_key5];
+ }
+
+ return (currentContext.describe || currentContext.suite).apply(this, args);
+ };
+
+ exports.describe.only = function () {
+ for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
+ args[_key6] = arguments[_key6];
+ }
+
+ return (currentContext.describe || currentContext.suite).only.apply(this, args);
+ };
+
+ exports.describe.skip = function () {
+ for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
+ args[_key7] = arguments[_key7];
+ }
+
+ return (currentContext.describe || currentContext.suite).skip.apply(this, args);
+ };
+
+ exports.it = function () {
+ for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
+ args[_key8] = arguments[_key8];
+ }
+
+ return (currentContext.it || currentContext.test).apply(this, args);
+ };
+
+ exports.it.only = function () {
+ for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
+ args[_key9] = arguments[_key9];
+ }
+
+ return (currentContext.it || currentContext.test).only.apply(this, args);
+ };
+
+ exports.it.skip = function () {
+ for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {
+ args[_key10] = arguments[_key10];
+ }
+
+ return (currentContext.it || currentContext.test).skip.apply(this, args);
+ };
+
+ exports.xdescribe = exports.describe.skip;
+ exports.xit = exports.it.skip;
+ exports.setup = exports.beforeEach;
+ exports.suiteSetup = exports.before;
+ exports.suiteTeardown = exports.after;
+ exports.suite = exports.describe;
+ exports.teardown = exports.afterEach;
+ exports.test = exports.it;
+
+ exports.run = function () {
+ for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) {
+ args[_key11] = arguments[_key11];
+ }
+
+ return currentContext.run.apply(this, args);
+ };
+ /**
+ * Constructs a new Mocha instance with `options`.
+ *
+ * @public
+ * @class Mocha
+ * @param {Object} [options] - Settings object.
+ * @param {boolean} [options.allowUncaught] - Propagate uncaught errors?
+ * @param {boolean} [options.asyncOnly] - Force `done` callback or promise?
+ * @param {boolean} [options.bail] - Bail after first test failure?
+ * @param {boolean} [options.checkLeaks] - Check for global variable leaks?
+ * @param {boolean} [options.color] - Color TTY output from reporter?
+ * @param {boolean} [options.delay] - Delay root suite execution?
+ * @param {boolean} [options.diff] - Show diff on failure?
+ * @param {boolean} [options.dryRun] - Report tests without running them?
+ * @param {boolean} [options.failZero] - Fail test run if zero tests?
+ * @param {string} [options.fgrep] - Test filter given string.
+ * @param {boolean} [options.forbidOnly] - Tests marked `only` fail the suite?
+ * @param {boolean} [options.forbidPending] - Pending tests fail the suite?
+ * @param {boolean} [options.fullTrace] - Full stacktrace upon failure?
+ * @param {string[]} [options.global] - Variables expected in global scope.
+ * @param {RegExp|string} [options.grep] - Test filter given regular expression.
+ * @param {boolean} [options.growl] - Enable desktop notifications?
+ * @param {boolean} [options.inlineDiffs] - Display inline diffs?
+ * @param {boolean} [options.invert] - Invert test filter matches?
+ * @param {boolean} [options.noHighlighting] - Disable syntax highlighting?
+ * @param {string|constructor} [options.reporter] - Reporter name or constructor.
+ * @param {Object} [options.reporterOption] - Reporter settings object.
+ * @param {number} [options.retries] - Number of times to retry failed tests.
+ * @param {number} [options.slow] - Slow threshold value.
+ * @param {number|string} [options.timeout] - Timeout threshold value.
+ * @param {string} [options.ui] - Interface name.
+ * @param {boolean} [options.parallel] - Run jobs in parallel.
+ * @param {number} [options.jobs] - Max number of worker processes for parallel runs.
+ * @param {MochaRootHookObject} [options.rootHooks] - Hooks to bootstrap the root suite with.
+ * @param {string[]} [options.require] - Pathname of `rootHooks` plugin for parallel runs.
+ * @param {boolean} [options.isWorker] - Should be `true` if `Mocha` process is running in a worker process.
+ */
+
+
+ function Mocha() {
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ options = _objectSpread2(_objectSpread2({}, mocharc), options);
+ this.files = [];
+ this.options = options; // root suite
+
+ this.suite = new exports.Suite('', new exports.Context(), true);
+ this._cleanReferencesAfterRun = true;
+ this._state = mochaStates.INIT;
+ this.grep(options.grep).fgrep(options.fgrep).ui(options.ui).reporter(options.reporter, options.reporterOption || options.reporterOptions // for backwards compability
+ ).slow(options.slow).global(options.global); // this guard exists because Suite#timeout does not consider `undefined` to be valid input
+
+ if (typeof options.timeout !== 'undefined') {
+ this.timeout(options.timeout === false ? 0 : options.timeout);
+ }
+
+ if ('retries' in options) {
+ this.retries(options.retries);
+ }
+
+ ['allowUncaught', 'asyncOnly', 'bail', 'checkLeaks', 'color', 'delay', 'diff', 'dryRun', 'failZero', 'forbidOnly', 'forbidPending', 'fullTrace', 'growl', 'inlineDiffs', 'invert'].forEach(function (opt) {
+ if (options[opt]) {
+ this[opt]();
+ }
+ }, this);
+
+ if (options.rootHooks) {
+ this.rootHooks(options.rootHooks);
+ }
+ /**
+ * The class which we'll instantiate in {@link Mocha#run}. Defaults to
+ * {@link Runner} in serial mode; changes in parallel mode.
+ * @memberof Mocha
+ * @private
+ */
+
+
+ this._runnerClass = exports.Runner;
+ /**
+ * Whether or not to call {@link Mocha#loadFiles} implicitly when calling
+ * {@link Mocha#run}. If this is `true`, then it's up to the consumer to call
+ * {@link Mocha#loadFiles} _or_ {@link Mocha#loadFilesAsync}.
+ * @private
+ * @memberof Mocha
+ */
+
+ this._lazyLoadFiles = false;
+ /**
+ * It's useful for a Mocha instance to know if it's running in a worker process.
+ * We could derive this via other means, but it's helpful to have a flag to refer to.
+ * @memberof Mocha
+ * @private
+ */
+
+ this.isWorker = Boolean(options.isWorker);
+ this.globalSetup(options.globalSetup).globalTeardown(options.globalTeardown).enableGlobalSetup(options.enableGlobalSetup).enableGlobalTeardown(options.enableGlobalTeardown);
+
+ if (options.parallel && (typeof options.jobs === 'undefined' || options.jobs > 1)) {
+ debug('attempting to enable parallel mode');
+ this.parallelMode(true);
+ }
+ }
+ /**
+ * Enables or disables bailing on the first failure.
+ *
+ * @public
+ * @see [CLI option](../#-bail-b)
+ * @param {boolean} [bail=true] - Whether to bail on first error.
+ * @returns {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.bail = function (bail) {
+ this.suite.bail(bail !== false);
+ return this;
+ };
+ /**
+ * @summary
+ * Adds `file` to be loaded for execution.
+ *
+ * @description
+ * Useful for generic setup code that must be included within test suite.
+ *
+ * @public
+ * @see [CLI option](../#-file-filedirectoryglob)
+ * @param {string} file - Pathname of file to be loaded.
+ * @returns {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.addFile = function (file) {
+ this.files.push(file);
+ return this;
+ };
+ /**
+ * Sets reporter to `reporter`, defaults to "spec".
+ *
+ * @public
+ * @see [CLI option](../#-reporter-name-r-name)
+ * @see [Reporters](../#reporters)
+ * @param {String|Function} reporterName - Reporter name or constructor.
+ * @param {Object} [reporterOptions] - Options used to configure the reporter.
+ * @returns {Mocha} this
+ * @chainable
+ * @throws {Error} if requested reporter cannot be loaded
+ * @example
+ *
+ * // Use XUnit reporter and direct its output to file
+ * mocha.reporter('xunit', { output: '/path/to/testspec.xunit.xml' });
+ */
+
+
+ Mocha.prototype.reporter = function (reporterName, reporterOptions) {
+ if (typeof reporterName === 'function') {
+ this._reporter = reporterName;
+ } else {
+ reporterName = reporterName || 'spec';
+ var reporter; // Try to load a built-in reporter.
+
+ if (reporters[reporterName]) {
+ reporter = reporters[reporterName];
+ } // Try to load reporters from process.cwd() and node_modules
+
+
+ if (!reporter) {
+ try {
+ reporter = commonjsRequire(reporterName);
+ } catch (err) {
+ if (err.code === 'MODULE_NOT_FOUND') {
+ // Try to load reporters from a path (absolute or relative)
+ try {
+ reporter = commonjsRequire(path.resolve(utils.cwd(), reporterName));
+ } catch (_err) {
+ _err.code === 'MODULE_NOT_FOUND' ? warn("'".concat(reporterName, "' reporter not found")) : warn("'".concat(reporterName, "' reporter blew up with error:\n ").concat(err.stack));
+ }
+ } else {
+ warn("'".concat(reporterName, "' reporter blew up with error:\n ").concat(err.stack));
+ }
+ }
+ }
+
+ if (!reporter) {
+ throw createInvalidReporterError("invalid reporter '".concat(reporterName, "'"), reporterName);
+ }
+
+ this._reporter = reporter;
+ }
+
+ this.options.reporterOption = reporterOptions; // alias option name is used in public reporters xunit/tap/progress
+
+ this.options.reporterOptions = reporterOptions;
+ return this;
+ };
+ /**
+ * Sets test UI `name`, defaults to "bdd".
+ *
+ * @public
+ * @see [CLI option](../#-ui-name-u-name)
+ * @see [Interface DSLs](../#interfaces)
+ * @param {string|Function} [ui=bdd] - Interface name or class.
+ * @returns {Mocha} this
+ * @chainable
+ * @throws {Error} if requested interface cannot be loaded
+ */
+
+
+ Mocha.prototype.ui = function (ui) {
+ var bindInterface;
+
+ if (typeof ui === 'function') {
+ bindInterface = ui;
+ } else {
+ ui = ui || 'bdd';
+ bindInterface = exports.interfaces[ui];
+
+ if (!bindInterface) {
+ try {
+ bindInterface = commonjsRequire(ui);
+ } catch (err) {
+ throw createInvalidInterfaceError("invalid interface '".concat(ui, "'"), ui);
+ }
+ }
+ }
+
+ bindInterface(this.suite);
+ this.suite.on(EVENT_FILE_PRE_REQUIRE, function (context) {
+ currentContext = context;
+ });
+ return this;
+ };
+ /**
+ * Loads `files` prior to execution. Does not support ES Modules.
+ *
+ * @description
+ * The implementation relies on Node's `require` to execute
+ * the test interface functions and will be subject to its cache.
+ * Supports only CommonJS modules. To load ES modules, use Mocha#loadFilesAsync.
+ *
+ * @private
+ * @see {@link Mocha#addFile}
+ * @see {@link Mocha#run}
+ * @see {@link Mocha#unloadFiles}
+ * @see {@link Mocha#loadFilesAsync}
+ * @param {Function} [fn] - Callback invoked upon completion.
+ */
+
+
+ Mocha.prototype.loadFiles = function (fn) {
+ var self = this;
+ var suite = this.suite;
+ this.files.forEach(function (file) {
+ file = path.resolve(file);
+ suite.emit(EVENT_FILE_PRE_REQUIRE, commonjsGlobal, file, self);
+ suite.emit(EVENT_FILE_REQUIRE, commonjsRequire(), file, self);
+ suite.emit(EVENT_FILE_POST_REQUIRE, commonjsGlobal, file, self);
+ });
+ fn && fn();
+ };
+ /**
+ * Loads `files` prior to execution. Supports Node ES Modules.
+ *
+ * @description
+ * The implementation relies on Node's `require` and `import` to execute
+ * the test interface functions and will be subject to its cache.
+ * Supports both CJS and ESM modules.
+ *
+ * @public
+ * @see {@link Mocha#addFile}
+ * @see {@link Mocha#run}
+ * @see {@link Mocha#unloadFiles}
+ * @returns {Promise}
+ * @example
+ *
+ * // loads ESM (and CJS) test files asynchronously, then runs root suite
+ * mocha.loadFilesAsync()
+ * .then(() => mocha.run(failures => process.exitCode = failures ? 1 : 0))
+ * .catch(() => process.exitCode = 1);
+ */
+
+
+ Mocha.prototype.loadFilesAsync = function () {
+ var self = this;
+ var suite = this.suite;
+ this.lazyLoadFiles(true);
+ return require$$10.loadFilesAsync(this.files, function (file) {
+ suite.emit(EVENT_FILE_PRE_REQUIRE, commonjsGlobal, file, self);
+ }, function (file, resultModule) {
+ suite.emit(EVENT_FILE_REQUIRE, resultModule, file, self);
+ suite.emit(EVENT_FILE_POST_REQUIRE, commonjsGlobal, file, self);
+ });
+ };
+ /**
+ * Removes a previously loaded file from Node's `require` cache.
+ *
+ * @private
+ * @static
+ * @see {@link Mocha#unloadFiles}
+ * @param {string} file - Pathname of file to be unloaded.
+ */
+
+
+ Mocha.unloadFile = function (file) {
+ if (utils.isBrowser()) {
+ throw createUnsupportedError('unloadFile() is only suported in a Node.js environment');
+ }
+
+ return require$$10.unloadFile(file);
+ };
+ /**
+ * Unloads `files` from Node's `require` cache.
+ *
+ * @description
+ * This allows required files to be "freshly" reloaded, providing the ability
+ * to reuse a Mocha instance programmatically.
+ * Note: does not clear ESM module files from the cache
+ *
+ * Intended for consumers — not used internally
+ *
+ * @public
+ * @see {@link Mocha#run}
+ * @returns {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.unloadFiles = function () {
+ if (this._state === mochaStates.DISPOSED) {
+ throw createMochaInstanceAlreadyDisposedError('Mocha instance is already disposed, it cannot be used again.', this._cleanReferencesAfterRun, this);
+ }
+
+ this.files.forEach(function (file) {
+ Mocha.unloadFile(file);
+ });
+ this._state = mochaStates.INIT;
+ return this;
+ };
+ /**
+ * Sets `grep` filter after escaping RegExp special characters.
+ *
+ * @public
+ * @see {@link Mocha#grep}
+ * @param {string} str - Value to be converted to a regexp.
+ * @returns {Mocha} this
+ * @chainable
+ * @example
+ *
+ * // Select tests whose full title begins with `"foo"` followed by a period
+ * mocha.fgrep('foo.');
+ */
+
+
+ Mocha.prototype.fgrep = function (str) {
+ if (!str) {
+ return this;
+ }
+
+ return this.grep(new RegExp(escapeStringRegexp(str)));
+ };
+ /**
+ * @summary
+ * Sets `grep` filter used to select specific tests for execution.
+ *
+ * @description
+ * If `re` is a regexp-like string, it will be converted to regexp.
+ * The regexp is tested against the full title of each test (i.e., the
+ * name of the test preceded by titles of each its ancestral suites).
+ * As such, using an exact-match fixed pattern against the
+ * test name itself will not yield any matches.
+ *
+ * Previous filter value will be overwritten on each call!
+ *
+ * @public
+ * @see [CLI option](../#-grep-regexp-g-regexp)
+ * @see {@link Mocha#fgrep}
+ * @see {@link Mocha#invert}
+ * @param {RegExp|String} re - Regular expression used to select tests.
+ * @return {Mocha} this
+ * @chainable
+ * @example
+ *
+ * // Select tests whose full title contains `"match"`, ignoring case
+ * mocha.grep(/match/i);
+ * @example
+ *
+ * // Same as above but with regexp-like string argument
+ * mocha.grep('/match/i');
+ * @example
+ *
+ * // ## Anti-example
+ * // Given embedded test `it('only-this-test')`...
+ * mocha.grep('/^only-this-test$/'); // NO! Use `.only()` to do this!
+ */
+
+
+ Mocha.prototype.grep = function (re) {
+ if (utils.isString(re)) {
+ // extract args if it's regex-like, i.e: [string, pattern, flag]
+ var arg = re.match(/^\/(.*)\/([gimy]{0,4})$|.*/);
+ this.options.grep = new RegExp(arg[1] || arg[0], arg[2]);
+ } else {
+ this.options.grep = re;
+ }
+
+ return this;
+ };
+ /**
+ * Inverts `grep` matches.
+ *
+ * @public
+ * @see {@link Mocha#grep}
+ * @return {Mocha} this
+ * @chainable
+ * @example
+ *
+ * // Select tests whose full title does *not* contain `"match"`, ignoring case
+ * mocha.grep(/match/i).invert();
+ */
+
+
+ Mocha.prototype.invert = function () {
+ this.options.invert = true;
+ return this;
+ };
+ /**
+ * Enables or disables checking for global variables leaked while running tests.
+ *
+ * @public
+ * @see [CLI option](../#-check-leaks)
+ * @param {boolean} [checkLeaks=true] - Whether to check for global variable leaks.
+ * @return {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.checkLeaks = function (checkLeaks) {
+ this.options.checkLeaks = checkLeaks !== false;
+ return this;
+ };
+ /**
+ * Enables or disables whether or not to dispose after each test run.
+ * Disable this to ensure you can run the test suite multiple times.
+ * If disabled, be sure to dispose mocha when you're done to prevent memory leaks.
+ * @public
+ * @see {@link Mocha#dispose}
+ * @param {boolean} cleanReferencesAfterRun
+ * @return {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.cleanReferencesAfterRun = function (cleanReferencesAfterRun) {
+ this._cleanReferencesAfterRun = cleanReferencesAfterRun !== false;
+ return this;
+ };
+ /**
+ * Manually dispose this mocha instance. Mark this instance as `disposed` and unable to run more tests.
+ * It also removes function references to tests functions and hooks, so variables trapped in closures can be cleaned by the garbage collector.
+ * @public
+ */
+
+
+ Mocha.prototype.dispose = function () {
+ if (this._state === mochaStates.RUNNING) {
+ throw createMochaInstanceAlreadyRunningError('Cannot dispose while the mocha instance is still running tests.');
+ }
+
+ this.unloadFiles();
+ this._previousRunner && this._previousRunner.dispose();
+ this.suite.dispose();
+ this._state = mochaStates.DISPOSED;
+ };
+ /**
+ * Displays full stack trace upon test failure.
+ *
+ * @public
+ * @see [CLI option](../#-full-trace)
+ * @param {boolean} [fullTrace=true] - Whether to print full stacktrace upon failure.
+ * @return {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.fullTrace = function (fullTrace) {
+ this.options.fullTrace = fullTrace !== false;
+ return this;
+ };
+ /**
+ * Enables desktop notification support if prerequisite software installed.
+ *
+ * @public
+ * @see [CLI option](../#-growl-g)
+ * @return {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.growl = function () {
+ this.options.growl = this.isGrowlCapable();
+
+ if (!this.options.growl) {
+ var detail = utils.isBrowser() ? 'notification support not available in this browser...' : 'notification support prerequisites not installed...';
+ console.error(detail + ' cannot enable!');
+ }
+
+ return this;
+ };
+ /**
+ * @summary
+ * Determines if Growl support seems likely.
+ *
+ * @description
+ * Not available when run in browser.
+ *
+ * @private
+ * @see {@link Growl#isCapable}
+ * @see {@link Mocha#growl}
+ * @return {boolean} whether Growl support can be expected
+ */
+
+
+ Mocha.prototype.isGrowlCapable = growl.isCapable;
+ /**
+ * Implements desktop notifications using a pseudo-reporter.
+ *
+ * @private
+ * @see {@link Mocha#growl}
+ * @see {@link Growl#notify}
+ * @param {Runner} runner - Runner instance.
+ */
+
+ Mocha.prototype._growl = growl.notify;
+ /**
+ * Specifies whitelist of variable names to be expected in global scope.
+ *
+ * @public
+ * @see [CLI option](../#-global-variable-name)
+ * @see {@link Mocha#checkLeaks}
+ * @param {String[]|String} global - Accepted global variable name(s).
+ * @return {Mocha} this
+ * @chainable
+ * @example
+ *
+ * // Specify variables to be expected in global scope
+ * mocha.global(['jQuery', 'MyLib']);
+ */
+
+ Mocha.prototype.global = function (global) {
+ this.options.global = (this.options.global || []).concat(global).filter(Boolean).filter(function (elt, idx, arr) {
+ return arr.indexOf(elt) === idx;
+ });
+ return this;
+ }; // for backwards compability, 'globals' is an alias of 'global'
+
+
+ Mocha.prototype.globals = Mocha.prototype.global;
+ /**
+ * Enables or disables TTY color output by screen-oriented reporters.
+ *
+ * @public
+ * @see [CLI option](../#-color-c-colors)
+ * @param {boolean} [color=true] - Whether to enable color output.
+ * @return {Mocha} this
+ * @chainable
+ */
+
+ Mocha.prototype.color = function (color) {
+ this.options.color = color !== false;
+ return this;
+ };
+ /**
+ * Enables or disables reporter to use inline diffs (rather than +/-)
+ * in test failure output.
+ *
+ * @public
+ * @see [CLI option](../#-inline-diffs)
+ * @param {boolean} [inlineDiffs=true] - Whether to use inline diffs.
+ * @return {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.inlineDiffs = function (inlineDiffs) {
+ this.options.inlineDiffs = inlineDiffs !== false;
+ return this;
+ };
+ /**
+ * Enables or disables reporter to include diff in test failure output.
+ *
+ * @public
+ * @see [CLI option](../#-diff)
+ * @param {boolean} [diff=true] - Whether to show diff on failure.
+ * @return {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.diff = function (diff) {
+ this.options.diff = diff !== false;
+ return this;
+ };
+ /**
+ * @summary
+ * Sets timeout threshold value.
+ *
+ * @description
+ * A string argument can use shorthand (such as "2s") and will be converted.
+ * If the value is `0`, timeouts will be disabled.
+ *
+ * @public
+ * @see [CLI option](../#-timeout-ms-t-ms)
+ * @see [Timeouts](../#timeouts)
+ * @param {number|string} msecs - Timeout threshold value.
+ * @return {Mocha} this
+ * @chainable
+ * @example
+ *
+ * // Sets timeout to one second
+ * mocha.timeout(1000);
+ * @example
+ *
+ * // Same as above but using string argument
+ * mocha.timeout('1s');
+ */
+
+
+ Mocha.prototype.timeout = function (msecs) {
+ this.suite.timeout(msecs);
+ return this;
+ };
+ /**
+ * Sets the number of times to retry failed tests.
+ *
+ * @public
+ * @see [CLI option](../#-retries-n)
+ * @see [Retry Tests](../#retry-tests)
+ * @param {number} retry - Number of times to retry failed tests.
+ * @return {Mocha} this
+ * @chainable
+ * @example
+ *
+ * // Allow any failed test to retry one more time
+ * mocha.retries(1);
+ */
+
+
+ Mocha.prototype.retries = function (retry) {
+ this.suite.retries(retry);
+ return this;
+ };
+ /**
+ * Sets slowness threshold value.
+ *
+ * @public
+ * @see [CLI option](../#-slow-ms-s-ms)
+ * @param {number} msecs - Slowness threshold value.
+ * @return {Mocha} this
+ * @chainable
+ * @example
+ *
+ * // Sets "slow" threshold to half a second
+ * mocha.slow(500);
+ * @example
+ *
+ * // Same as above but using string argument
+ * mocha.slow('0.5s');
+ */
+
+
+ Mocha.prototype.slow = function (msecs) {
+ this.suite.slow(msecs);
+ return this;
+ };
+ /**
+ * Forces all tests to either accept a `done` callback or return a promise.
+ *
+ * @public
+ * @see [CLI option](../#-async-only-a)
+ * @param {boolean} [asyncOnly=true] - Whether to force `done` callback or promise.
+ * @return {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.asyncOnly = function (asyncOnly) {
+ this.options.asyncOnly = asyncOnly !== false;
+ return this;
+ };
+ /**
+ * Disables syntax highlighting (in browser).
+ *
+ * @public
+ * @return {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.noHighlighting = function () {
+ this.options.noHighlighting = true;
+ return this;
+ };
+ /**
+ * Enables or disables uncaught errors to propagate.
+ *
+ * @public
+ * @see [CLI option](../#-allow-uncaught)
+ * @param {boolean} [allowUncaught=true] - Whether to propagate uncaught errors.
+ * @return {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.allowUncaught = function (allowUncaught) {
+ this.options.allowUncaught = allowUncaught !== false;
+ return this;
+ };
+ /**
+ * @summary
+ * Delays root suite execution.
+ *
+ * @description
+ * Used to perform async operations before any suites are run.
+ *
+ * @public
+ * @see [delayed root suite](../#delayed-root-suite)
+ * @returns {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.delay = function delay() {
+ this.options.delay = true;
+ return this;
+ };
+ /**
+ * Enables or disables running tests in dry-run mode.
+ *
+ * @public
+ * @see [CLI option](../#-dry-run)
+ * @param {boolean} [dryRun=true] - Whether to activate dry-run mode.
+ * @return {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.dryRun = function (dryRun) {
+ this.options.dryRun = dryRun !== false;
+ return this;
+ };
+ /**
+ * Fails test run if no tests encountered with exit-code 1.
+ *
+ * @public
+ * @see [CLI option](../#-fail-zero)
+ * @param {boolean} [failZero=true] - Whether to fail test run.
+ * @return {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.failZero = function (failZero) {
+ this.options.failZero = failZero !== false;
+ return this;
+ };
+ /**
+ * Causes tests marked `only` to fail the suite.
+ *
+ * @public
+ * @see [CLI option](../#-forbid-only)
+ * @param {boolean} [forbidOnly=true] - Whether tests marked `only` fail the suite.
+ * @returns {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.forbidOnly = function (forbidOnly) {
+ this.options.forbidOnly = forbidOnly !== false;
+ return this;
+ };
+ /**
+ * Causes pending tests and tests marked `skip` to fail the suite.
+ *
+ * @public
+ * @see [CLI option](../#-forbid-pending)
+ * @param {boolean} [forbidPending=true] - Whether pending tests fail the suite.
+ * @returns {Mocha} this
+ * @chainable
+ */
+
+
+ Mocha.prototype.forbidPending = function (forbidPending) {
+ this.options.forbidPending = forbidPending !== false;
+ return this;
+ };
+ /**
+ * Throws an error if mocha is in the wrong state to be able to transition to a "running" state.
+ * @private
+ */
+
+
+ Mocha.prototype._guardRunningStateTransition = function () {
+ if (this._state === mochaStates.RUNNING) {
+ throw createMochaInstanceAlreadyRunningError('Mocha instance is currently running tests, cannot start a next test run until this one is done', this);
+ }
+
+ if (this._state === mochaStates.DISPOSED || this._state === mochaStates.REFERENCES_CLEANED) {
+ throw createMochaInstanceAlreadyDisposedError('Mocha instance is already disposed, cannot start a new test run. Please create a new mocha instance. Be sure to set disable `cleanReferencesAfterRun` when you want to reuse the same mocha instance for multiple test runs.', this._cleanReferencesAfterRun, this);
+ }
+ };
+ /**
+ * Mocha version as specified by "package.json".
+ *
+ * @name Mocha#version
+ * @type string
+ * @readonly
+ */
+
+
+ Object.defineProperty(Mocha.prototype, 'version', {
+ value: require$$9.version,
+ configurable: false,
+ enumerable: true,
+ writable: false
+ });
+ /**
+ * Callback to be invoked when test execution is complete.
+ *
+ * @private
+ * @callback DoneCB
+ * @param {number} failures - Number of failures that occurred.
+ */
+
+ /**
+ * Runs root suite and invokes `fn()` when complete.
+ *
+ * @description
+ * To run tests multiple times (or to run tests in files that are
+ * already in the `require` cache), make sure to clear them from
+ * the cache first!
+ *
+ * @public
+ * @see {@link Mocha#unloadFiles}
+ * @see {@link Runner#run}
+ * @param {DoneCB} [fn] - Callback invoked when test execution completed.
+ * @returns {Runner} runner instance
+ * @example
+ *
+ * // exit with non-zero status if there were test failures
+ * mocha.run(failures => process.exitCode = failures ? 1 : 0);
+ */
+
+ Mocha.prototype.run = function (fn) {
+ var _this = this;
+
+ this._guardRunningStateTransition();
+
+ this._state = mochaStates.RUNNING;
+
+ if (this._previousRunner) {
+ this._previousRunner.dispose();
+
+ this.suite.reset();
+ }
+
+ if (this.files.length && !this._lazyLoadFiles) {
+ this.loadFiles();
+ }
+
+ var suite = this.suite;
+ var options = this.options;
+ options.files = this.files;
+ var runner = new this._runnerClass(suite, {
+ cleanReferencesAfterRun: this._cleanReferencesAfterRun,
+ delay: options.delay,
+ dryRun: options.dryRun,
+ failZero: options.failZero
+ });
+ statsCollector(runner);
+ var reporter = new this._reporter(runner, options);
+ runner.checkLeaks = options.checkLeaks === true;
+ runner.fullStackTrace = options.fullTrace;
+ runner.asyncOnly = options.asyncOnly;
+ runner.allowUncaught = options.allowUncaught;
+ runner.forbidOnly = options.forbidOnly;
+ runner.forbidPending = options.forbidPending;
+
+ if (options.grep) {
+ runner.grep(options.grep, options.invert);
+ }
+
+ if (options.global) {
+ runner.globals(options.global);
+ }
+
+ if (options.growl) {
+ this._growl(runner);
+ }
+
+ if (options.color !== undefined) {
+ exports.reporters.Base.useColors = options.color;
+ }
+
+ exports.reporters.Base.inlineDiffs = options.inlineDiffs;
+ exports.reporters.Base.hideDiff = !options.diff;
+
+ var done = function done(failures) {
+ _this._previousRunner = runner;
+ _this._state = _this._cleanReferencesAfterRun ? mochaStates.REFERENCES_CLEANED : mochaStates.INIT;
+ fn = fn || utils.noop;
+
+ if (typeof reporter.done === 'function') {
+ reporter.done(failures, fn);
+ } else {
+ fn(failures);
+ }
+ };
+
+ var runAsync = /*#__PURE__*/function () {
+ var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(runner) {
+ var context, failureCount;
+ return regeneratorRuntime.wrap(function _callee$(_context) {
+ while (1) {
+ switch (_context.prev = _context.next) {
+ case 0:
+ if (!(_this.options.enableGlobalSetup && _this.hasGlobalSetupFixtures())) {
+ _context.next = 6;
+ break;
+ }
+
+ _context.next = 3;
+ return _this.runGlobalSetup(runner);
+
+ case 3:
+ _context.t0 = _context.sent;
+ _context.next = 7;
+ break;
+
+ case 6:
+ _context.t0 = {};
+
+ case 7:
+ context = _context.t0;
+ _context.next = 10;
+ return runner.runAsync({
+ files: _this.files,
+ options: options
+ });
+
+ case 10:
+ failureCount = _context.sent;
+
+ if (!(_this.options.enableGlobalTeardown && _this.hasGlobalTeardownFixtures())) {
+ _context.next = 14;
+ break;
+ }
+
+ _context.next = 14;
+ return _this.runGlobalTeardown(runner, {
+ context: context
+ });
+
+ case 14:
+ return _context.abrupt("return", failureCount);
+
+ case 15:
+ case "end":
+ return _context.stop();
+ }
+ }
+ }, _callee);
+ }));
+
+ return function runAsync(_x) {
+ return _ref.apply(this, arguments);
+ };
+ }(); // no "catch" here is intentional. errors coming out of
+ // Runner#run are considered uncaught/unhandled and caught
+ // by the `process` event listeners.
+ // also: returning anything other than `runner` would be a breaking
+ // change
+
+
+ runAsync(runner).then(done);
+ return runner;
+ };
+ /**
+ * Assigns hooks to the root suite
+ * @param {MochaRootHookObject} [hooks] - Hooks to assign to root suite
+ * @chainable
+ */
+
+
+ Mocha.prototype.rootHooks = function rootHooks() {
+ var _this2 = this;
+
+ var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
+ _ref2$beforeAll = _ref2.beforeAll,
+ beforeAll = _ref2$beforeAll === void 0 ? [] : _ref2$beforeAll,
+ _ref2$beforeEach = _ref2.beforeEach,
+ beforeEach = _ref2$beforeEach === void 0 ? [] : _ref2$beforeEach,
+ _ref2$afterAll = _ref2.afterAll,
+ afterAll = _ref2$afterAll === void 0 ? [] : _ref2$afterAll,
+ _ref2$afterEach = _ref2.afterEach,
+ afterEach = _ref2$afterEach === void 0 ? [] : _ref2$afterEach;
+
+ beforeAll = utils.castArray(beforeAll);
+ beforeEach = utils.castArray(beforeEach);
+ afterAll = utils.castArray(afterAll);
+ afterEach = utils.castArray(afterEach);
+ beforeAll.forEach(function (hook) {
+ _this2.suite.beforeAll(hook);
+ });
+ beforeEach.forEach(function (hook) {
+ _this2.suite.beforeEach(hook);
+ });
+ afterAll.forEach(function (hook) {
+ _this2.suite.afterAll(hook);
+ });
+ afterEach.forEach(function (hook) {
+ _this2.suite.afterEach(hook);
+ });
+ return this;
+ };
+ /**
+ * Toggles parallel mode.
+ *
+ * Must be run before calling {@link Mocha#run}. Changes the `Runner` class to
+ * use; also enables lazy file loading if not already done so.
+ *
+ * Warning: when passed `false` and lazy loading has been enabled _via any means_ (including calling `parallelMode(true)`), this method will _not_ disable lazy loading. Lazy loading is a prerequisite for parallel
+ * mode, but parallel mode is _not_ a prerequisite for lazy loading!
+ * @param {boolean} [enable] - If `true`, enable; otherwise disable.
+ * @throws If run in browser
+ * @throws If Mocha not in `INIT` state
+ * @returns {Mocha}
+ * @chainable
+ * @public
+ */
+
+
+ Mocha.prototype.parallelMode = function parallelMode() {
+ var enable = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
+
+ if (utils.isBrowser()) {
+ throw createUnsupportedError('parallel mode is only supported in Node.js');
+ }
+
+ var parallel = Boolean(enable);
+
+ if (parallel === this.options.parallel && this._lazyLoadFiles && this._runnerClass !== exports.Runner) {
+ return this;
+ }
+
+ if (this._state !== mochaStates.INIT) {
+ throw createUnsupportedError('cannot change parallel mode after having called run()');
+ }
+
+ this.options.parallel = parallel; // swap Runner class
+
+ this._runnerClass = parallel ? require$$10 : exports.Runner; // lazyLoadFiles may have been set `true` otherwise (for ESM loading),
+ // so keep `true` if so.
+
+ return this.lazyLoadFiles(this._lazyLoadFiles || parallel);
+ };
+ /**
+ * Disables implicit call to {@link Mocha#loadFiles} in {@link Mocha#run}. This
+ * setting is used by watch mode, parallel mode, and for loading ESM files.
+ * @todo This should throw if we've already loaded files; such behavior
+ * necessitates adding a new state.
+ * @param {boolean} [enable] - If `true`, disable eager loading of files in
+ * {@link Mocha#run}
+ * @chainable
+ * @public
+ */
+
+
+ Mocha.prototype.lazyLoadFiles = function lazyLoadFiles(enable) {
+ this._lazyLoadFiles = enable === true;
+ debug('set lazy load to %s', enable);
+ return this;
+ };
+ /**
+ * Configures one or more global setup fixtures.
+ *
+ * If given no parameters, _unsets_ any previously-set fixtures.
+ * @chainable
+ * @public
+ * @param {MochaGlobalFixture|MochaGlobalFixture[]} [setupFns] - Global setup fixture(s)
+ * @returns {Mocha}
+ */
+
+
+ Mocha.prototype.globalSetup = function globalSetup() {
+ var setupFns = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
+ setupFns = utils.castArray(setupFns);
+ this.options.globalSetup = setupFns;
+ debug('configured %d global setup functions', setupFns.length);
+ return this;
+ };
+ /**
+ * Configures one or more global teardown fixtures.
+ *
+ * If given no parameters, _unsets_ any previously-set fixtures.
+ * @chainable
+ * @public
+ * @param {MochaGlobalFixture|MochaGlobalFixture[]} [teardownFns] - Global teardown fixture(s)
+ * @returns {Mocha}
+ */
+
+
+ Mocha.prototype.globalTeardown = function globalTeardown() {
+ var teardownFns = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
+ teardownFns = utils.castArray(teardownFns);
+ this.options.globalTeardown = teardownFns;
+ debug('configured %d global teardown functions', teardownFns.length);
+ return this;
+ };
+ /**
+ * Run any global setup fixtures sequentially, if any.
+ *
+ * This is _automatically called_ by {@link Mocha#run} _unless_ the `runGlobalSetup` option is `false`; see {@link Mocha#enableGlobalSetup}.
+ *
+ * The context object this function resolves with should be consumed by {@link Mocha#runGlobalTeardown}.
+ * @param {object} [context] - Context object if already have one
+ * @public
+ * @returns {Promise} Context object
+ */
+
+
+ Mocha.prototype.runGlobalSetup = /*#__PURE__*/function () {
+ var _runGlobalSetup = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
+ var context,
+ globalSetup,
+ _args2 = arguments;
+ return regeneratorRuntime.wrap(function _callee2$(_context2) {
+ while (1) {
+ switch (_context2.prev = _context2.next) {
+ case 0:
+ context = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {};
+ globalSetup = this.options.globalSetup;
+
+ if (!(globalSetup && globalSetup.length)) {
+ _context2.next = 7;
+ break;
+ }
+
+ debug('run(): global setup starting');
+ _context2.next = 6;
+ return this._runGlobalFixtures(globalSetup, context);
+
+ case 6:
+ debug('run(): global setup complete');
+
+ case 7:
+ return _context2.abrupt("return", context);
+
+ case 8:
+ case "end":
+ return _context2.stop();
+ }
+ }
+ }, _callee2, this);
+ }));
+
+ function runGlobalSetup() {
+ return _runGlobalSetup.apply(this, arguments);
+ }
+
+ return runGlobalSetup;
+ }();
+ /**
+ * Run any global teardown fixtures sequentially, if any.
+ *
+ * This is _automatically called_ by {@link Mocha#run} _unless_ the `runGlobalTeardown` option is `false`; see {@link Mocha#enableGlobalTeardown}.
+ *
+ * Should be called with context object returned by {@link Mocha#runGlobalSetup}, if applicable.
+ * @param {object} [context] - Context object if already have one
+ * @public
+ * @returns {Promise} Context object
+ */
+
+
+ Mocha.prototype.runGlobalTeardown = /*#__PURE__*/function () {
+ var _runGlobalTeardown = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
+ var context,
+ globalTeardown,
+ _args3 = arguments;
+ return regeneratorRuntime.wrap(function _callee3$(_context3) {
+ while (1) {
+ switch (_context3.prev = _context3.next) {
+ case 0:
+ context = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : {};
+ globalTeardown = this.options.globalTeardown;
+
+ if (!(globalTeardown && globalTeardown.length)) {
+ _context3.next = 6;
+ break;
+ }
+
+ debug('run(): global teardown starting');
+ _context3.next = 6;
+ return this._runGlobalFixtures(globalTeardown, context);
+
+ case 6:
+ debug('run(): global teardown complete');
+ return _context3.abrupt("return", context);
+
+ case 8:
+ case "end":
+ return _context3.stop();
+ }
+ }
+ }, _callee3, this);
+ }));
+
+ function runGlobalTeardown() {
+ return _runGlobalTeardown.apply(this, arguments);
+ }
+
+ return runGlobalTeardown;
+ }();
+ /**
+ * Run global fixtures sequentially with context `context`
+ * @private
+ * @param {MochaGlobalFixture[]} [fixtureFns] - Fixtures to run
+ * @param {object} [context] - context object
+ * @returns {Promise} context object
+ */
+
+
+ Mocha.prototype._runGlobalFixtures = /*#__PURE__*/function () {
+ var _runGlobalFixtures2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
+ var fixtureFns,
+ context,
+ _iteratorAbruptCompletion,
+ _didIteratorError,
+ _iteratorError,
+ _iterator,
+ _step,
+ fixtureFn,
+ _args4 = arguments;
+
+ return regeneratorRuntime.wrap(function _callee4$(_context4) {
+ while (1) {
+ switch (_context4.prev = _context4.next) {
+ case 0:
+ fixtureFns = _args4.length > 0 && _args4[0] !== undefined ? _args4[0] : [];
+ context = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : {};
+ _iteratorAbruptCompletion = false;
+ _didIteratorError = false;
+ _context4.prev = 4;
+ _iterator = _asyncIterator(fixtureFns);
+
+ case 6:
+ _context4.next = 8;
+ return _iterator.next();
+
+ case 8:
+ if (!(_iteratorAbruptCompletion = !(_step = _context4.sent).done)) {
+ _context4.next = 15;
+ break;
+ }
+
+ fixtureFn = _step.value;
+ _context4.next = 12;
+ return fixtureFn.call(context);
+
+ case 12:
+ _iteratorAbruptCompletion = false;
+ _context4.next = 6;
+ break;
+
+ case 15:
+ _context4.next = 21;
+ break;
+
+ case 17:
+ _context4.prev = 17;
+ _context4.t0 = _context4["catch"](4);
+ _didIteratorError = true;
+ _iteratorError = _context4.t0;
+
+ case 21:
+ _context4.prev = 21;
+ _context4.prev = 22;
+
+ if (!(_iteratorAbruptCompletion && _iterator["return"] != null)) {
+ _context4.next = 26;
+ break;
+ }
+
+ _context4.next = 26;
+ return _iterator["return"]();
+
+ case 26:
+ _context4.prev = 26;
+
+ if (!_didIteratorError) {
+ _context4.next = 29;
+ break;
+ }
+
+ throw _iteratorError;
+
+ case 29:
+ return _context4.finish(26);
+
+ case 30:
+ return _context4.finish(21);
+
+ case 31:
+ return _context4.abrupt("return", context);
+
+ case 32:
+ case "end":
+ return _context4.stop();
+ }
+ }
+ }, _callee4, null, [[4, 17, 21, 31], [22,, 26, 30]]);
+ }));
+
+ function _runGlobalFixtures() {
+ return _runGlobalFixtures2.apply(this, arguments);
+ }
+
+ return _runGlobalFixtures;
+ }();
+ /**
+ * Toggle execution of any global setup fixture(s)
+ *
+ * @chainable
+ * @public
+ * @param {boolean } [enabled=true] - If `false`, do not run global setup fixture
+ * @returns {Mocha}
+ */
+
+
+ Mocha.prototype.enableGlobalSetup = function enableGlobalSetup() {
+ var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
+ this.options.enableGlobalSetup = Boolean(enabled);
+ return this;
+ };
+ /**
+ * Toggle execution of any global teardown fixture(s)
+ *
+ * @chainable
+ * @public
+ * @param {boolean } [enabled=true] - If `false`, do not run global teardown fixture
+ * @returns {Mocha}
+ */
+
+
+ Mocha.prototype.enableGlobalTeardown = function enableGlobalTeardown() {
+ var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
+ this.options.enableGlobalTeardown = Boolean(enabled);
+ return this;
+ };
+ /**
+ * Returns `true` if one or more global setup fixtures have been supplied.
+ * @public
+ * @returns {boolean}
+ */
+
+
+ Mocha.prototype.hasGlobalSetupFixtures = function hasGlobalSetupFixtures() {
+ return Boolean(this.options.globalSetup.length);
+ };
+ /**
+ * Returns `true` if one or more global teardown fixtures have been supplied.
+ * @public
+ * @returns {boolean}
+ */
+
+
+ Mocha.prototype.hasGlobalTeardownFixtures = function hasGlobalTeardownFixtures() {
+ return Boolean(this.options.globalTeardown.length);
+ };
+ /**
+ * An alternative way to define root hooks that works with parallel runs.
+ * @typedef {Object} MochaRootHookObject
+ * @property {Function|Function[]} [beforeAll] - "Before all" hook(s)
+ * @property {Function|Function[]} [beforeEach] - "Before each" hook(s)
+ * @property {Function|Function[]} [afterAll] - "After all" hook(s)
+ * @property {Function|Function[]} [afterEach] - "After each" hook(s)
+ */
+
+ /**
+ * An function that returns a {@link MochaRootHookObject}, either sync or async.
+ @callback MochaRootHookFunction
+ * @returns {MochaRootHookObject|Promise}
+ */
+
+ /**
+ * A function that's invoked _once_ which is either sync or async.
+ * Can be a "teardown" or "setup". These will all share the same context.
+ * @callback MochaGlobalFixture
+ * @returns {void|Promise}
+ */
+
+ /**
+ * An object making up all necessary parts of a plugin loader and aggregator
+ * @typedef {Object} PluginDefinition
+ * @property {string} exportName - Named export to use
+ * @property {string} [optionName] - Option name for Mocha constructor (use `exportName` if omitted)
+ * @property {PluginValidator} [validate] - Validator function
+ * @property {PluginFinalizer} [finalize] - Finalizer/aggregator function
+ */
+
+ /**
+ * A (sync) function to assert a user-supplied plugin implementation is valid.
+ *
+ * Defined in a {@link PluginDefinition}.
+
+ * @callback PluginValidator
+ * @param {*} value - Value to check
+ * @this {PluginDefinition}
+ * @returns {void}
+ */
+
+ /**
+ * A function to finalize plugins impls of a particular ilk
+ * @callback PluginFinalizer
+ * @param {Array<*>} impls - User-supplied implementations
+ * @returns {Promise<*>|*}
+ */
+
+ });
+
+ /* eslint no-unused-vars: off */
+
+ /* eslint-env commonjs */
+
+ /**
+ * Shim process.stdout.
+ */
+
+
+ process$4.stdout = browserStdout({
+ label: false
+ });
+ /**
+ * Create a Mocha instance.
+ *
+ * @return {undefined}
+ */
+
+ var mocha = new mocha$1({
+ reporter: 'html'
+ });
+ /**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+ var Date$1 = commonjsGlobal.Date;
+ var setTimeout$1 = commonjsGlobal.setTimeout;
+ commonjsGlobal.setInterval;
+ commonjsGlobal.clearTimeout;
+ commonjsGlobal.clearInterval;
+ var uncaughtExceptionHandlers = [];
+ var originalOnerrorHandler = commonjsGlobal.onerror;
+ /**
+ * Remove uncaughtException listener.
+ * Revert to original onerror handler if previously defined.
+ */
+
+ process$4.removeListener = function (e, fn) {
+ if (e === 'uncaughtException') {
+ if (originalOnerrorHandler) {
+ commonjsGlobal.onerror = originalOnerrorHandler;
+ } else {
+ commonjsGlobal.onerror = function () {};
+ }
+
+ var i = uncaughtExceptionHandlers.indexOf(fn);
+
+ if (i !== -1) {
+ uncaughtExceptionHandlers.splice(i, 1);
+ }
+ }
+ };
+ /**
+ * Implements listenerCount for 'uncaughtException'.
+ */
+
+
+ process$4.listenerCount = function (name) {
+ if (name === 'uncaughtException') {
+ return uncaughtExceptionHandlers.length;
+ }
+
+ return 0;
+ };
+ /**
+ * Implements uncaughtException listener.
+ */
+
+
+ process$4.on = function (e, fn) {
+ if (e === 'uncaughtException') {
+ commonjsGlobal.onerror = function (err, url, line) {
+ fn(new Error(err + ' (' + url + ':' + line + ')'));
+ return !mocha.options.allowUncaught;
+ };
+
+ uncaughtExceptionHandlers.push(fn);
+ }
+ };
+
+ process$4.listeners = function (e) {
+ if (e === 'uncaughtException') {
+ return uncaughtExceptionHandlers;
+ }
+
+ return [];
+ }; // The BDD UI is registered by default, but no UI will be functional in the
+ // browser without an explicit call to the overridden `mocha.ui` (see below).
+ // Ensure that this default UI does not expose its methods to the global scope.
+
+
+ mocha.suite.removeAllListeners('pre-require');
+ var immediateQueue = [];
+ var immediateTimeout;
+
+ function timeslice() {
+ var immediateStart = new Date$1().getTime();
+
+ while (immediateQueue.length && new Date$1().getTime() - immediateStart < 100) {
+ immediateQueue.shift()();
+ }
+
+ if (immediateQueue.length) {
+ immediateTimeout = setTimeout$1(timeslice, 0);
+ } else {
+ immediateTimeout = null;
+ }
}
+ /**
+ * High-performance override of Runner.immediately.
+ */
+ mocha$1.Runner.immediately = function (callback) {
+ immediateQueue.push(callback);
-/***/ })
-/******/ ])
-});
-;
-},{}],49:[function(require,module,exports){
-'use strict';
-
-var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
-
-module.exports = function (str) {
- if (typeof str !== 'string') {
- throw new TypeError('Expected a string');
- }
-
- return str.replace(matchOperatorsRe, '\\$&');
-};
-
-},{}],50:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node 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.
-
-var objectCreate = Object.create || objectCreatePolyfill
-var objectKeys = Object.keys || objectKeysPolyfill
-var bind = Function.prototype.bind || functionBindPolyfill
-
-function EventEmitter() {
- if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
- this._events = objectCreate(null);
- this._eventsCount = 0;
- }
-
- this._maxListeners = this._maxListeners || undefined;
-}
-module.exports = EventEmitter;
-
-// Backwards-compat with node 0.10.x
-EventEmitter.EventEmitter = EventEmitter;
-
-EventEmitter.prototype._events = undefined;
-EventEmitter.prototype._maxListeners = undefined;
-
-// By default EventEmitters will print a warning if more than 10 listeners are
-// added to it. This is a useful default which helps finding memory leaks.
-var defaultMaxListeners = 10;
-
-var hasDefineProperty;
-try {
- var o = {};
- if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
- hasDefineProperty = o.x === 0;
-} catch (err) { hasDefineProperty = false }
-if (hasDefineProperty) {
- Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
- enumerable: true,
- get: function() {
- return defaultMaxListeners;
- },
- set: function(arg) {
- // check whether the input is a positive number (whose value is zero or
- // greater and not a NaN).
- if (typeof arg !== 'number' || arg < 0 || arg !== arg)
- throw new TypeError('"defaultMaxListeners" must be a positive number');
- defaultMaxListeners = arg;
- }
- });
-} else {
- EventEmitter.defaultMaxListeners = defaultMaxListeners;
-}
-
-// Obviously not all Emitters should be limited to 10. This function allows
-// that to be increased. Set to zero for unlimited.
-EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
- if (typeof n !== 'number' || n < 0 || isNaN(n))
- throw new TypeError('"n" argument must be a positive number');
- this._maxListeners = n;
- return this;
-};
-
-function $getMaxListeners(that) {
- if (that._maxListeners === undefined)
- return EventEmitter.defaultMaxListeners;
- return that._maxListeners;
-}
-
-EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
- return $getMaxListeners(this);
-};
-
-// These standalone emit* functions are used to optimize calling of event
-// handlers for fast cases because emit() itself often has a variable number of
-// arguments and can be deoptimized because of that. These functions always have
-// the same number of arguments and thus do not get deoptimized, so the code
-// inside them can execute faster.
-function emitNone(handler, isFn, self) {
- if (isFn)
- handler.call(self);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self);
- }
-}
-function emitOne(handler, isFn, self, arg1) {
- if (isFn)
- handler.call(self, arg1);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self, arg1);
- }
-}
-function emitTwo(handler, isFn, self, arg1, arg2) {
- if (isFn)
- handler.call(self, arg1, arg2);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self, arg1, arg2);
- }
-}
-function emitThree(handler, isFn, self, arg1, arg2, arg3) {
- if (isFn)
- handler.call(self, arg1, arg2, arg3);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self, arg1, arg2, arg3);
- }
-}
-
-function emitMany(handler, isFn, self, args) {
- if (isFn)
- handler.apply(self, args);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].apply(self, args);
- }
-}
-
-EventEmitter.prototype.emit = function emit(type) {
- var er, handler, len, args, i, events;
- var doError = (type === 'error');
-
- events = this._events;
- if (events)
- doError = (doError && events.error == null);
- else if (!doError)
- return false;
-
- // If there is no 'error' event listener then throw.
- if (doError) {
- if (arguments.length > 1)
- er = arguments[1];
- if (er instanceof Error) {
- throw er; // Unhandled 'error' event
- } else {
- // At least give some kind of context to the user
- var err = new Error('Unhandled "error" event. (' + er + ')');
- err.context = er;
- throw err;
- }
- return false;
- }
-
- handler = events[type];
-
- if (!handler)
- return false;
-
- var isFn = typeof handler === 'function';
- len = arguments.length;
- switch (len) {
- // fast cases
- case 1:
- emitNone(handler, isFn, this);
- break;
- case 2:
- emitOne(handler, isFn, this, arguments[1]);
- break;
- case 3:
- emitTwo(handler, isFn, this, arguments[1], arguments[2]);
- break;
- case 4:
- emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
- break;
- // slower
- default:
- args = new Array(len - 1);
- for (i = 1; i < len; i++)
- args[i - 1] = arguments[i];
- emitMany(handler, isFn, this, args);
- }
-
- return true;
-};
-
-function _addListener(target, type, listener, prepend) {
- var m;
- var events;
- var existing;
-
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
-
- events = target._events;
- if (!events) {
- events = target._events = objectCreate(null);
- target._eventsCount = 0;
- } else {
- // To avoid recursion in the case that type === "newListener"! Before
- // adding it to the listeners, first emit "newListener".
- if (events.newListener) {
- target.emit('newListener', type,
- listener.listener ? listener.listener : listener);
-
- // Re-assign `events` because a newListener handler could have caused the
- // this._events to be assigned to a new object
- events = target._events;
- }
- existing = events[type];
- }
-
- if (!existing) {
- // Optimize the case of one listener. Don't need the extra array object.
- existing = events[type] = listener;
- ++target._eventsCount;
- } else {
- if (typeof existing === 'function') {
- // Adding the second element, need to change to array.
- existing = events[type] =
- prepend ? [listener, existing] : [existing, listener];
- } else {
- // If we've already got an array, just append.
- if (prepend) {
- existing.unshift(listener);
- } else {
- existing.push(listener);
- }
- }
-
- // Check for listener leak
- if (!existing.warned) {
- m = $getMaxListeners(target);
- if (m && m > 0 && existing.length > m) {
- existing.warned = true;
- var w = new Error('Possible EventEmitter memory leak detected. ' +
- existing.length + ' "' + String(type) + '" listeners ' +
- 'added. Use emitter.setMaxListeners() to ' +
- 'increase limit.');
- w.name = 'MaxListenersExceededWarning';
- w.emitter = target;
- w.type = type;
- w.count = existing.length;
- if (typeof console === 'object' && console.warn) {
- console.warn('%s: %s', w.name, w.message);
- }
- }
- }
- }
-
- return target;
-}
-
-EventEmitter.prototype.addListener = function addListener(type, listener) {
- return _addListener(this, type, listener, false);
-};
-
-EventEmitter.prototype.on = EventEmitter.prototype.addListener;
-
-EventEmitter.prototype.prependListener =
- function prependListener(type, listener) {
- return _addListener(this, type, listener, true);
- };
-
-function onceWrapper() {
- if (!this.fired) {
- this.target.removeListener(this.type, this.wrapFn);
- this.fired = true;
- switch (arguments.length) {
- case 0:
- return this.listener.call(this.target);
- case 1:
- return this.listener.call(this.target, arguments[0]);
- case 2:
- return this.listener.call(this.target, arguments[0], arguments[1]);
- case 3:
- return this.listener.call(this.target, arguments[0], arguments[1],
- arguments[2]);
- default:
- var args = new Array(arguments.length);
- for (var i = 0; i < args.length; ++i)
- args[i] = arguments[i];
- this.listener.apply(this.target, args);
- }
- }
-}
-
-function _onceWrap(target, type, listener) {
- var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
- var wrapped = bind.call(onceWrapper, state);
- wrapped.listener = listener;
- state.wrapFn = wrapped;
- return wrapped;
-}
-
-EventEmitter.prototype.once = function once(type, listener) {
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
- this.on(type, _onceWrap(this, type, listener));
- return this;
-};
-
-EventEmitter.prototype.prependOnceListener =
- function prependOnceListener(type, listener) {
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
- this.prependListener(type, _onceWrap(this, type, listener));
- return this;
- };
-
-// Emits a 'removeListener' event if and only if the listener was removed.
-EventEmitter.prototype.removeListener =
- function removeListener(type, listener) {
- var list, events, position, i, originalListener;
-
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
-
- events = this._events;
- if (!events)
- return this;
-
- list = events[type];
- if (!list)
- return this;
-
- if (list === listener || list.listener === listener) {
- if (--this._eventsCount === 0)
- this._events = objectCreate(null);
- else {
- delete events[type];
- if (events.removeListener)
- this.emit('removeListener', type, list.listener || listener);
- }
- } else if (typeof list !== 'function') {
- position = -1;
-
- for (i = list.length - 1; i >= 0; i--) {
- if (list[i] === listener || list[i].listener === listener) {
- originalListener = list[i].listener;
- position = i;
- break;
- }
- }
-
- if (position < 0)
- return this;
-
- if (position === 0)
- list.shift();
- else
- spliceOne(list, position);
-
- if (list.length === 1)
- events[type] = list[0];
-
- if (events.removeListener)
- this.emit('removeListener', type, originalListener || listener);
- }
-
- return this;
- };
-
-EventEmitter.prototype.removeAllListeners =
- function removeAllListeners(type) {
- var listeners, events, i;
-
- events = this._events;
- if (!events)
- return this;
-
- // not listening for removeListener, no need to emit
- if (!events.removeListener) {
- if (arguments.length === 0) {
- this._events = objectCreate(null);
- this._eventsCount = 0;
- } else if (events[type]) {
- if (--this._eventsCount === 0)
- this._events = objectCreate(null);
- else
- delete events[type];
- }
- return this;
- }
-
- // emit removeListener for all listeners on all events
- if (arguments.length === 0) {
- var keys = objectKeys(events);
- var key;
- for (i = 0; i < keys.length; ++i) {
- key = keys[i];
- if (key === 'removeListener') continue;
- this.removeAllListeners(key);
- }
- this.removeAllListeners('removeListener');
- this._events = objectCreate(null);
- this._eventsCount = 0;
- return this;
- }
-
- listeners = events[type];
-
- if (typeof listeners === 'function') {
- this.removeListener(type, listeners);
- } else if (listeners) {
- // LIFO order
- for (i = listeners.length - 1; i >= 0; i--) {
- this.removeListener(type, listeners[i]);
- }
- }
-
- return this;
- };
-
-function _listeners(target, type, unwrap) {
- var events = target._events;
-
- if (!events)
- return [];
-
- var evlistener = events[type];
- if (!evlistener)
- return [];
-
- if (typeof evlistener === 'function')
- return unwrap ? [evlistener.listener || evlistener] : [evlistener];
-
- return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
-}
-
-EventEmitter.prototype.listeners = function listeners(type) {
- return _listeners(this, type, true);
-};
-
-EventEmitter.prototype.rawListeners = function rawListeners(type) {
- return _listeners(this, type, false);
-};
-
-EventEmitter.listenerCount = function(emitter, type) {
- if (typeof emitter.listenerCount === 'function') {
- return emitter.listenerCount(type);
- } else {
- return listenerCount.call(emitter, type);
- }
-};
-
-EventEmitter.prototype.listenerCount = listenerCount;
-function listenerCount(type) {
- var events = this._events;
-
- if (events) {
- var evlistener = events[type];
-
- if (typeof evlistener === 'function') {
- return 1;
- } else if (evlistener) {
- return evlistener.length;
- }
- }
-
- return 0;
-}
-
-EventEmitter.prototype.eventNames = function eventNames() {
- return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
-};
-
-// About 1.5x faster than the two-arg version of Array#splice().
-function spliceOne(list, index) {
- for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
- list[i] = list[k];
- list.pop();
-}
-
-function arrayClone(arr, n) {
- var copy = new Array(n);
- for (var i = 0; i < n; ++i)
- copy[i] = arr[i];
- return copy;
-}
-
-function unwrapListeners(arr) {
- var ret = new Array(arr.length);
- for (var i = 0; i < ret.length; ++i) {
- ret[i] = arr[i].listener || arr[i];
- }
- return ret;
-}
-
-function objectCreatePolyfill(proto) {
- var F = function() {};
- F.prototype = proto;
- return new F;
-}
-function objectKeysPolyfill(obj) {
- var keys = [];
- for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
- keys.push(k);
- }
- return k;
-}
-function functionBindPolyfill(context) {
- var fn = this;
- return function () {
- return fn.apply(context, arguments);
- };
-}
-
-},{}],51:[function(require,module,exports){
-'use strict';
-
-/* eslint no-invalid-this: 1 */
-
-var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
-var slice = Array.prototype.slice;
-var toStr = Object.prototype.toString;
-var funcType = '[object Function]';
-
-module.exports = function bind(that) {
- var target = this;
- if (typeof target !== 'function' || toStr.call(target) !== funcType) {
- throw new TypeError(ERROR_MESSAGE + target);
- }
- var args = slice.call(arguments, 1);
-
- var bound;
- var binder = function () {
- if (this instanceof bound) {
- var result = target.apply(
- this,
- args.concat(slice.call(arguments))
- );
- if (Object(result) === result) {
- return result;
- }
- return this;
- } else {
- return target.apply(
- that,
- args.concat(slice.call(arguments))
- );
- }
- };
-
- var boundLength = Math.max(0, target.length - args.length);
- var boundArgs = [];
- for (var i = 0; i < boundLength; i++) {
- boundArgs.push('$' + i);
- }
-
- bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
-
- if (target.prototype) {
- var Empty = function Empty() {};
- Empty.prototype = target.prototype;
- bound.prototype = new Empty();
- Empty.prototype = null;
- }
-
- return bound;
-};
-
-},{}],52:[function(require,module,exports){
-'use strict';
-
-var implementation = require('./implementation');
-
-module.exports = Function.prototype.bind || implementation;
-
-},{"./implementation":51}],53:[function(require,module,exports){
-'use strict';
-
-/* eslint complexity: [2, 17], max-statements: [2, 33] */
-module.exports = function hasSymbols() {
- if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
- if (typeof Symbol.iterator === 'symbol') { return true; }
-
- var obj = {};
- var sym = Symbol('test');
- var symObj = Object(sym);
- if (typeof sym === 'string') { return false; }
-
- if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
- if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
-
- // temp disabled per https://github.com/ljharb/object.assign/issues/17
- // if (sym instanceof Symbol) { return false; }
- // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
- // if (!(symObj instanceof Symbol)) { return false; }
-
- // if (typeof Symbol.prototype.toString !== 'function') { return false; }
- // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
-
- var symVal = 42;
- obj[sym] = symVal;
- for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax
- if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
-
- if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
-
- var syms = Object.getOwnPropertySymbols(obj);
- if (syms.length !== 1 || syms[0] !== sym) { return false; }
-
- if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
-
- if (typeof Object.getOwnPropertyDescriptor === 'function') {
- var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
- if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
- }
-
- return true;
-};
-
-},{}],54:[function(require,module,exports){
-(function (global){
-/*! https://mths.be/he v1.2.0 by @mathias | MIT license */
-;(function(root) {
-
- // Detect free variables `exports`.
- var freeExports = typeof exports == 'object' && exports;
-
- // Detect free variable `module`.
- var freeModule = typeof module == 'object' && module &&
- module.exports == freeExports && module;
-
- // Detect free variable `global`, from Node.js or Browserified code,
- // and use it as `root`.
- var freeGlobal = typeof global == 'object' && global;
- if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
- root = freeGlobal;
- }
-
- /*--------------------------------------------------------------------------*/
-
- // All astral symbols.
- var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
- // All ASCII symbols (not just printable ASCII) except those listed in the
- // first column of the overrides table.
- // https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides
- var regexAsciiWhitelist = /[\x01-\x7F]/g;
- // All BMP symbols that are not ASCII newlines, printable ASCII symbols, or
- // code points listed in the first column of the overrides table on
- // https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides.
- var regexBmpWhitelist = /[\x01-\t\x0B\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g;
-
- var regexEncodeNonAscii = /<\u20D2|=\u20E5|>\u20D2|\u205F\u200A|\u219D\u0338|\u2202\u0338|\u2220\u20D2|\u2229\uFE00|\u222A\uFE00|\u223C\u20D2|\u223D\u0331|\u223E\u0333|\u2242\u0338|\u224B\u0338|\u224D\u20D2|\u224E\u0338|\u224F\u0338|\u2250\u0338|\u2261\u20E5|\u2264\u20D2|\u2265\u20D2|\u2266\u0338|\u2267\u0338|\u2268\uFE00|\u2269\uFE00|\u226A\u0338|\u226A\u20D2|\u226B\u0338|\u226B\u20D2|\u227F\u0338|\u2282\u20D2|\u2283\u20D2|\u228A\uFE00|\u228B\uFE00|\u228F\u0338|\u2290\u0338|\u2293\uFE00|\u2294\uFE00|\u22B4\u20D2|\u22B5\u20D2|\u22D8\u0338|\u22D9\u0338|\u22DA\uFE00|\u22DB\uFE00|\u22F5\u0338|\u22F9\u0338|\u2933\u0338|\u29CF\u0338|\u29D0\u0338|\u2A6D\u0338|\u2A70\u0338|\u2A7D\u0338|\u2A7E\u0338|\u2AA1\u0338|\u2AA2\u0338|\u2AAC\uFE00|\u2AAD\uFE00|\u2AAF\u0338|\u2AB0\u0338|\u2AC5\u0338|\u2AC6\u0338|\u2ACB\uFE00|\u2ACC\uFE00|\u2AFD\u20E5|[\xA0-\u0113\u0116-\u0122\u0124-\u012B\u012E-\u014D\u0150-\u017E\u0192\u01B5\u01F5\u0237\u02C6\u02C7\u02D8-\u02DD\u0311\u0391-\u03A1\u03A3-\u03A9\u03B1-\u03C9\u03D1\u03D2\u03D5\u03D6\u03DC\u03DD\u03F0\u03F1\u03F5\u03F6\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E\u045F\u2002-\u2005\u2007-\u2010\u2013-\u2016\u2018-\u201A\u201C-\u201E\u2020-\u2022\u2025\u2026\u2030-\u2035\u2039\u203A\u203E\u2041\u2043\u2044\u204F\u2057\u205F-\u2063\u20AC\u20DB\u20DC\u2102\u2105\u210A-\u2113\u2115-\u211E\u2122\u2124\u2127-\u2129\u212C\u212D\u212F-\u2131\u2133-\u2138\u2145-\u2148\u2153-\u215E\u2190-\u219B\u219D-\u21A7\u21A9-\u21AE\u21B0-\u21B3\u21B5-\u21B7\u21BA-\u21DB\u21DD\u21E4\u21E5\u21F5\u21FD-\u2205\u2207-\u2209\u220B\u220C\u220F-\u2214\u2216-\u2218\u221A\u221D-\u2238\u223A-\u2257\u2259\u225A\u225C\u225F-\u2262\u2264-\u228B\u228D-\u229B\u229D-\u22A5\u22A7-\u22B0\u22B2-\u22BB\u22BD-\u22DB\u22DE-\u22E3\u22E6-\u22F7\u22F9-\u22FE\u2305\u2306\u2308-\u2310\u2312\u2313\u2315\u2316\u231C-\u231F\u2322\u2323\u232D\u232E\u2336\u233D\u233F\u237C\u23B0\u23B1\u23B4-\u23B6\u23DC-\u23DF\u23E2\u23E7\u2423\u24C8\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2550-\u256C\u2580\u2584\u2588\u2591-\u2593\u25A1\u25AA\u25AB\u25AD\u25AE\u25B1\u25B3-\u25B5\u25B8\u25B9\u25BD-\u25BF\u25C2\u25C3\u25CA\u25CB\u25EC\u25EF\u25F8-\u25FC\u2605\u2606\u260E\u2640\u2642\u2660\u2663\u2665\u2666\u266A\u266D-\u266F\u2713\u2717\u2720\u2736\u2758\u2772\u2773\u27C8\u27C9\u27E6-\u27ED\u27F5-\u27FA\u27FC\u27FF\u2902-\u2905\u290C-\u2913\u2916\u2919-\u2920\u2923-\u292A\u2933\u2935-\u2939\u293C\u293D\u2945\u2948-\u294B\u294E-\u2976\u2978\u2979\u297B-\u297F\u2985\u2986\u298B-\u2996\u299A\u299C\u299D\u29A4-\u29B7\u29B9\u29BB\u29BC\u29BE-\u29C5\u29C9\u29CD-\u29D0\u29DC-\u29DE\u29E3-\u29E5\u29EB\u29F4\u29F6\u2A00-\u2A02\u2A04\u2A06\u2A0C\u2A0D\u2A10-\u2A17\u2A22-\u2A27\u2A29\u2A2A\u2A2D-\u2A31\u2A33-\u2A3C\u2A3F\u2A40\u2A42-\u2A4D\u2A50\u2A53-\u2A58\u2A5A-\u2A5D\u2A5F\u2A66\u2A6A\u2A6D-\u2A75\u2A77-\u2A9A\u2A9D-\u2AA2\u2AA4-\u2AB0\u2AB3-\u2AC8\u2ACB\u2ACC\u2ACF-\u2ADB\u2AE4\u2AE6-\u2AE9\u2AEB-\u2AF3\u2AFD\uFB00-\uFB04]|\uD835[\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDCCF\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDD6B]/g;
- var encodeMap = {'\xAD':'shy','\u200C':'zwnj','\u200D':'zwj','\u200E':'lrm','\u2063':'ic','\u2062':'it','\u2061':'af','\u200F':'rlm','\u200B':'ZeroWidthSpace','\u2060':'NoBreak','\u0311':'DownBreve','\u20DB':'tdot','\u20DC':'DotDot','\t':'Tab','\n':'NewLine','\u2008':'puncsp','\u205F':'MediumSpace','\u2009':'thinsp','\u200A':'hairsp','\u2004':'emsp13','\u2002':'ensp','\u2005':'emsp14','\u2003':'emsp','\u2007':'numsp','\xA0':'nbsp','\u205F\u200A':'ThickSpace','\u203E':'oline','_':'lowbar','\u2010':'dash','\u2013':'ndash','\u2014':'mdash','\u2015':'horbar',',':'comma',';':'semi','\u204F':'bsemi',':':'colon','\u2A74':'Colone','!':'excl','\xA1':'iexcl','?':'quest','\xBF':'iquest','.':'period','\u2025':'nldr','\u2026':'mldr','\xB7':'middot','\'':'apos','\u2018':'lsquo','\u2019':'rsquo','\u201A':'sbquo','\u2039':'lsaquo','\u203A':'rsaquo','"':'quot','\u201C':'ldquo','\u201D':'rdquo','\u201E':'bdquo','\xAB':'laquo','\xBB':'raquo','(':'lpar',')':'rpar','[':'lsqb',']':'rsqb','{':'lcub','}':'rcub','\u2308':'lceil','\u2309':'rceil','\u230A':'lfloor','\u230B':'rfloor','\u2985':'lopar','\u2986':'ropar','\u298B':'lbrke','\u298C':'rbrke','\u298D':'lbrkslu','\u298E':'rbrksld','\u298F':'lbrksld','\u2990':'rbrkslu','\u2991':'langd','\u2992':'rangd','\u2993':'lparlt','\u2994':'rpargt','\u2995':'gtlPar','\u2996':'ltrPar','\u27E6':'lobrk','\u27E7':'robrk','\u27E8':'lang','\u27E9':'rang','\u27EA':'Lang','\u27EB':'Rang','\u27EC':'loang','\u27ED':'roang','\u2772':'lbbrk','\u2773':'rbbrk','\u2016':'Vert','\xA7':'sect','\xB6':'para','@':'commat','*':'ast','/':'sol','undefined':null,'&':'amp','#':'num','%':'percnt','\u2030':'permil','\u2031':'pertenk','\u2020':'dagger','\u2021':'Dagger','\u2022':'bull','\u2043':'hybull','\u2032':'prime','\u2033':'Prime','\u2034':'tprime','\u2057':'qprime','\u2035':'bprime','\u2041':'caret','`':'grave','\xB4':'acute','\u02DC':'tilde','^':'Hat','\xAF':'macr','\u02D8':'breve','\u02D9':'dot','\xA8':'die','\u02DA':'ring','\u02DD':'dblac','\xB8':'cedil','\u02DB':'ogon','\u02C6':'circ','\u02C7':'caron','\xB0':'deg','\xA9':'copy','\xAE':'reg','\u2117':'copysr','\u2118':'wp','\u211E':'rx','\u2127':'mho','\u2129':'iiota','\u2190':'larr','\u219A':'nlarr','\u2192':'rarr','\u219B':'nrarr','\u2191':'uarr','\u2193':'darr','\u2194':'harr','\u21AE':'nharr','\u2195':'varr','\u2196':'nwarr','\u2197':'nearr','\u2198':'searr','\u2199':'swarr','\u219D':'rarrw','\u219D\u0338':'nrarrw','\u219E':'Larr','\u219F':'Uarr','\u21A0':'Rarr','\u21A1':'Darr','\u21A2':'larrtl','\u21A3':'rarrtl','\u21A4':'mapstoleft','\u21A5':'mapstoup','\u21A6':'map','\u21A7':'mapstodown','\u21A9':'larrhk','\u21AA':'rarrhk','\u21AB':'larrlp','\u21AC':'rarrlp','\u21AD':'harrw','\u21B0':'lsh','\u21B1':'rsh','\u21B2':'ldsh','\u21B3':'rdsh','\u21B5':'crarr','\u21B6':'cularr','\u21B7':'curarr','\u21BA':'olarr','\u21BB':'orarr','\u21BC':'lharu','\u21BD':'lhard','\u21BE':'uharr','\u21BF':'uharl','\u21C0':'rharu','\u21C1':'rhard','\u21C2':'dharr','\u21C3':'dharl','\u21C4':'rlarr','\u21C5':'udarr','\u21C6':'lrarr','\u21C7':'llarr','\u21C8':'uuarr','\u21C9':'rrarr','\u21CA':'ddarr','\u21CB':'lrhar','\u21CC':'rlhar','\u21D0':'lArr','\u21CD':'nlArr','\u21D1':'uArr','\u21D2':'rArr','\u21CF':'nrArr','\u21D3':'dArr','\u21D4':'iff','\u21CE':'nhArr','\u21D5':'vArr','\u21D6':'nwArr','\u21D7':'neArr','\u21D8':'seArr','\u21D9':'swArr','\u21DA':'lAarr','\u21DB':'rAarr','\u21DD':'zigrarr','\u21E4':'larrb','\u21E5':'rarrb','\u21F5':'duarr','\u21FD':'loarr','\u21FE':'roarr','\u21FF':'hoarr','\u2200':'forall','\u2201':'comp','\u2202':'part','\u2202\u0338':'npart','\u2203':'exist','\u2204':'nexist','\u2205':'empty','\u2207':'Del','\u2208':'in','\u2209':'notin','\u220B':'ni','\u220C':'notni','\u03F6':'bepsi','\u220F':'prod','\u2210':'coprod','\u2211':'sum','+':'plus','\xB1':'pm','\xF7':'div','\xD7':'times','<':'lt','\u226E':'nlt','<\u20D2':'nvlt','=':'equals','\u2260':'ne','=\u20E5':'bne','\u2A75':'Equal','>':'gt','\u226F':'ngt','>\u20D2':'nvgt','\xAC':'not','|':'vert','\xA6':'brvbar','\u2212':'minus','\u2213':'mp','\u2214':'plusdo','\u2044':'frasl','\u2216':'setmn','\u2217':'lowast','\u2218':'compfn','\u221A':'Sqrt','\u221D':'prop','\u221E':'infin','\u221F':'angrt','\u2220':'ang','\u2220\u20D2':'nang','\u2221':'angmsd','\u2222':'angsph','\u2223':'mid','\u2224':'nmid','\u2225':'par','\u2226':'npar','\u2227':'and','\u2228':'or','\u2229':'cap','\u2229\uFE00':'caps','\u222A':'cup','\u222A\uFE00':'cups','\u222B':'int','\u222C':'Int','\u222D':'tint','\u2A0C':'qint','\u222E':'oint','\u222F':'Conint','\u2230':'Cconint','\u2231':'cwint','\u2232':'cwconint','\u2233':'awconint','\u2234':'there4','\u2235':'becaus','\u2236':'ratio','\u2237':'Colon','\u2238':'minusd','\u223A':'mDDot','\u223B':'homtht','\u223C':'sim','\u2241':'nsim','\u223C\u20D2':'nvsim','\u223D':'bsim','\u223D\u0331':'race','\u223E':'ac','\u223E\u0333':'acE','\u223F':'acd','\u2240':'wr','\u2242':'esim','\u2242\u0338':'nesim','\u2243':'sime','\u2244':'nsime','\u2245':'cong','\u2247':'ncong','\u2246':'simne','\u2248':'ap','\u2249':'nap','\u224A':'ape','\u224B':'apid','\u224B\u0338':'napid','\u224C':'bcong','\u224D':'CupCap','\u226D':'NotCupCap','\u224D\u20D2':'nvap','\u224E':'bump','\u224E\u0338':'nbump','\u224F':'bumpe','\u224F\u0338':'nbumpe','\u2250':'doteq','\u2250\u0338':'nedot','\u2251':'eDot','\u2252':'efDot','\u2253':'erDot','\u2254':'colone','\u2255':'ecolon','\u2256':'ecir','\u2257':'cire','\u2259':'wedgeq','\u225A':'veeeq','\u225C':'trie','\u225F':'equest','\u2261':'equiv','\u2262':'nequiv','\u2261\u20E5':'bnequiv','\u2264':'le','\u2270':'nle','\u2264\u20D2':'nvle','\u2265':'ge','\u2271':'nge','\u2265\u20D2':'nvge','\u2266':'lE','\u2266\u0338':'nlE','\u2267':'gE','\u2267\u0338':'ngE','\u2268\uFE00':'lvnE','\u2268':'lnE','\u2269':'gnE','\u2269\uFE00':'gvnE','\u226A':'ll','\u226A\u0338':'nLtv','\u226A\u20D2':'nLt','\u226B':'gg','\u226B\u0338':'nGtv','\u226B\u20D2':'nGt','\u226C':'twixt','\u2272':'lsim','\u2274':'nlsim','\u2273':'gsim','\u2275':'ngsim','\u2276':'lg','\u2278':'ntlg','\u2277':'gl','\u2279':'ntgl','\u227A':'pr','\u2280':'npr','\u227B':'sc','\u2281':'nsc','\u227C':'prcue','\u22E0':'nprcue','\u227D':'sccue','\u22E1':'nsccue','\u227E':'prsim','\u227F':'scsim','\u227F\u0338':'NotSucceedsTilde','\u2282':'sub','\u2284':'nsub','\u2282\u20D2':'vnsub','\u2283':'sup','\u2285':'nsup','\u2283\u20D2':'vnsup','\u2286':'sube','\u2288':'nsube','\u2287':'supe','\u2289':'nsupe','\u228A\uFE00':'vsubne','\u228A':'subne','\u228B\uFE00':'vsupne','\u228B':'supne','\u228D':'cupdot','\u228E':'uplus','\u228F':'sqsub','\u228F\u0338':'NotSquareSubset','\u2290':'sqsup','\u2290\u0338':'NotSquareSuperset','\u2291':'sqsube','\u22E2':'nsqsube','\u2292':'sqsupe','\u22E3':'nsqsupe','\u2293':'sqcap','\u2293\uFE00':'sqcaps','\u2294':'sqcup','\u2294\uFE00':'sqcups','\u2295':'oplus','\u2296':'ominus','\u2297':'otimes','\u2298':'osol','\u2299':'odot','\u229A':'ocir','\u229B':'oast','\u229D':'odash','\u229E':'plusb','\u229F':'minusb','\u22A0':'timesb','\u22A1':'sdotb','\u22A2':'vdash','\u22AC':'nvdash','\u22A3':'dashv','\u22A4':'top','\u22A5':'bot','\u22A7':'models','\u22A8':'vDash','\u22AD':'nvDash','\u22A9':'Vdash','\u22AE':'nVdash','\u22AA':'Vvdash','\u22AB':'VDash','\u22AF':'nVDash','\u22B0':'prurel','\u22B2':'vltri','\u22EA':'nltri','\u22B3':'vrtri','\u22EB':'nrtri','\u22B4':'ltrie','\u22EC':'nltrie','\u22B4\u20D2':'nvltrie','\u22B5':'rtrie','\u22ED':'nrtrie','\u22B5\u20D2':'nvrtrie','\u22B6':'origof','\u22B7':'imof','\u22B8':'mumap','\u22B9':'hercon','\u22BA':'intcal','\u22BB':'veebar','\u22BD':'barvee','\u22BE':'angrtvb','\u22BF':'lrtri','\u22C0':'Wedge','\u22C1':'Vee','\u22C2':'xcap','\u22C3':'xcup','\u22C4':'diam','\u22C5':'sdot','\u22C6':'Star','\u22C7':'divonx','\u22C8':'bowtie','\u22C9':'ltimes','\u22CA':'rtimes','\u22CB':'lthree','\u22CC':'rthree','\u22CD':'bsime','\u22CE':'cuvee','\u22CF':'cuwed','\u22D0':'Sub','\u22D1':'Sup','\u22D2':'Cap','\u22D3':'Cup','\u22D4':'fork','\u22D5':'epar','\u22D6':'ltdot','\u22D7':'gtdot','\u22D8':'Ll','\u22D8\u0338':'nLl','\u22D9':'Gg','\u22D9\u0338':'nGg','\u22DA\uFE00':'lesg','\u22DA':'leg','\u22DB':'gel','\u22DB\uFE00':'gesl','\u22DE':'cuepr','\u22DF':'cuesc','\u22E6':'lnsim','\u22E7':'gnsim','\u22E8':'prnsim','\u22E9':'scnsim','\u22EE':'vellip','\u22EF':'ctdot','\u22F0':'utdot','\u22F1':'dtdot','\u22F2':'disin','\u22F3':'isinsv','\u22F4':'isins','\u22F5':'isindot','\u22F5\u0338':'notindot','\u22F6':'notinvc','\u22F7':'notinvb','\u22F9':'isinE','\u22F9\u0338':'notinE','\u22FA':'nisd','\u22FB':'xnis','\u22FC':'nis','\u22FD':'notnivc','\u22FE':'notnivb','\u2305':'barwed','\u2306':'Barwed','\u230C':'drcrop','\u230D':'dlcrop','\u230E':'urcrop','\u230F':'ulcrop','\u2310':'bnot','\u2312':'profline','\u2313':'profsurf','\u2315':'telrec','\u2316':'target','\u231C':'ulcorn','\u231D':'urcorn','\u231E':'dlcorn','\u231F':'drcorn','\u2322':'frown','\u2323':'smile','\u232D':'cylcty','\u232E':'profalar','\u2336':'topbot','\u233D':'ovbar','\u233F':'solbar','\u237C':'angzarr','\u23B0':'lmoust','\u23B1':'rmoust','\u23B4':'tbrk','\u23B5':'bbrk','\u23B6':'bbrktbrk','\u23DC':'OverParenthesis','\u23DD':'UnderParenthesis','\u23DE':'OverBrace','\u23DF':'UnderBrace','\u23E2':'trpezium','\u23E7':'elinters','\u2423':'blank','\u2500':'boxh','\u2502':'boxv','\u250C':'boxdr','\u2510':'boxdl','\u2514':'boxur','\u2518':'boxul','\u251C':'boxvr','\u2524':'boxvl','\u252C':'boxhd','\u2534':'boxhu','\u253C':'boxvh','\u2550':'boxH','\u2551':'boxV','\u2552':'boxdR','\u2553':'boxDr','\u2554':'boxDR','\u2555':'boxdL','\u2556':'boxDl','\u2557':'boxDL','\u2558':'boxuR','\u2559':'boxUr','\u255A':'boxUR','\u255B':'boxuL','\u255C':'boxUl','\u255D':'boxUL','\u255E':'boxvR','\u255F':'boxVr','\u2560':'boxVR','\u2561':'boxvL','\u2562':'boxVl','\u2563':'boxVL','\u2564':'boxHd','\u2565':'boxhD','\u2566':'boxHD','\u2567':'boxHu','\u2568':'boxhU','\u2569':'boxHU','\u256A':'boxvH','\u256B':'boxVh','\u256C':'boxVH','\u2580':'uhblk','\u2584':'lhblk','\u2588':'block','\u2591':'blk14','\u2592':'blk12','\u2593':'blk34','\u25A1':'squ','\u25AA':'squf','\u25AB':'EmptyVerySmallSquare','\u25AD':'rect','\u25AE':'marker','\u25B1':'fltns','\u25B3':'xutri','\u25B4':'utrif','\u25B5':'utri','\u25B8':'rtrif','\u25B9':'rtri','\u25BD':'xdtri','\u25BE':'dtrif','\u25BF':'dtri','\u25C2':'ltrif','\u25C3':'ltri','\u25CA':'loz','\u25CB':'cir','\u25EC':'tridot','\u25EF':'xcirc','\u25F8':'ultri','\u25F9':'urtri','\u25FA':'lltri','\u25FB':'EmptySmallSquare','\u25FC':'FilledSmallSquare','\u2605':'starf','\u2606':'star','\u260E':'phone','\u2640':'female','\u2642':'male','\u2660':'spades','\u2663':'clubs','\u2665':'hearts','\u2666':'diams','\u266A':'sung','\u2713':'check','\u2717':'cross','\u2720':'malt','\u2736':'sext','\u2758':'VerticalSeparator','\u27C8':'bsolhsub','\u27C9':'suphsol','\u27F5':'xlarr','\u27F6':'xrarr','\u27F7':'xharr','\u27F8':'xlArr','\u27F9':'xrArr','\u27FA':'xhArr','\u27FC':'xmap','\u27FF':'dzigrarr','\u2902':'nvlArr','\u2903':'nvrArr','\u2904':'nvHarr','\u2905':'Map','\u290C':'lbarr','\u290D':'rbarr','\u290E':'lBarr','\u290F':'rBarr','\u2910':'RBarr','\u2911':'DDotrahd','\u2912':'UpArrowBar','\u2913':'DownArrowBar','\u2916':'Rarrtl','\u2919':'latail','\u291A':'ratail','\u291B':'lAtail','\u291C':'rAtail','\u291D':'larrfs','\u291E':'rarrfs','\u291F':'larrbfs','\u2920':'rarrbfs','\u2923':'nwarhk','\u2924':'nearhk','\u2925':'searhk','\u2926':'swarhk','\u2927':'nwnear','\u2928':'toea','\u2929':'tosa','\u292A':'swnwar','\u2933':'rarrc','\u2933\u0338':'nrarrc','\u2935':'cudarrr','\u2936':'ldca','\u2937':'rdca','\u2938':'cudarrl','\u2939':'larrpl','\u293C':'curarrm','\u293D':'cularrp','\u2945':'rarrpl','\u2948':'harrcir','\u2949':'Uarrocir','\u294A':'lurdshar','\u294B':'ldrushar','\u294E':'LeftRightVector','\u294F':'RightUpDownVector','\u2950':'DownLeftRightVector','\u2951':'LeftUpDownVector','\u2952':'LeftVectorBar','\u2953':'RightVectorBar','\u2954':'RightUpVectorBar','\u2955':'RightDownVectorBar','\u2956':'DownLeftVectorBar','\u2957':'DownRightVectorBar','\u2958':'LeftUpVectorBar','\u2959':'LeftDownVectorBar','\u295A':'LeftTeeVector','\u295B':'RightTeeVector','\u295C':'RightUpTeeVector','\u295D':'RightDownTeeVector','\u295E':'DownLeftTeeVector','\u295F':'DownRightTeeVector','\u2960':'LeftUpTeeVector','\u2961':'LeftDownTeeVector','\u2962':'lHar','\u2963':'uHar','\u2964':'rHar','\u2965':'dHar','\u2966':'luruhar','\u2967':'ldrdhar','\u2968':'ruluhar','\u2969':'rdldhar','\u296A':'lharul','\u296B':'llhard','\u296C':'rharul','\u296D':'lrhard','\u296E':'udhar','\u296F':'duhar','\u2970':'RoundImplies','\u2971':'erarr','\u2972':'simrarr','\u2973':'larrsim','\u2974':'rarrsim','\u2975':'rarrap','\u2976':'ltlarr','\u2978':'gtrarr','\u2979':'subrarr','\u297B':'suplarr','\u297C':'lfisht','\u297D':'rfisht','\u297E':'ufisht','\u297F':'dfisht','\u299A':'vzigzag','\u299C':'vangrt','\u299D':'angrtvbd','\u29A4':'ange','\u29A5':'range','\u29A6':'dwangle','\u29A7':'uwangle','\u29A8':'angmsdaa','\u29A9':'angmsdab','\u29AA':'angmsdac','\u29AB':'angmsdad','\u29AC':'angmsdae','\u29AD':'angmsdaf','\u29AE':'angmsdag','\u29AF':'angmsdah','\u29B0':'bemptyv','\u29B1':'demptyv','\u29B2':'cemptyv','\u29B3':'raemptyv','\u29B4':'laemptyv','\u29B5':'ohbar','\u29B6':'omid','\u29B7':'opar','\u29B9':'operp','\u29BB':'olcross','\u29BC':'odsold','\u29BE':'olcir','\u29BF':'ofcir','\u29C0':'olt','\u29C1':'ogt','\u29C2':'cirscir','\u29C3':'cirE','\u29C4':'solb','\u29C5':'bsolb','\u29C9':'boxbox','\u29CD':'trisb','\u29CE':'rtriltri','\u29CF':'LeftTriangleBar','\u29CF\u0338':'NotLeftTriangleBar','\u29D0':'RightTriangleBar','\u29D0\u0338':'NotRightTriangleBar','\u29DC':'iinfin','\u29DD':'infintie','\u29DE':'nvinfin','\u29E3':'eparsl','\u29E4':'smeparsl','\u29E5':'eqvparsl','\u29EB':'lozf','\u29F4':'RuleDelayed','\u29F6':'dsol','\u2A00':'xodot','\u2A01':'xoplus','\u2A02':'xotime','\u2A04':'xuplus','\u2A06':'xsqcup','\u2A0D':'fpartint','\u2A10':'cirfnint','\u2A11':'awint','\u2A12':'rppolint','\u2A13':'scpolint','\u2A14':'npolint','\u2A15':'pointint','\u2A16':'quatint','\u2A17':'intlarhk','\u2A22':'pluscir','\u2A23':'plusacir','\u2A24':'simplus','\u2A25':'plusdu','\u2A26':'plussim','\u2A27':'plustwo','\u2A29':'mcomma','\u2A2A':'minusdu','\u2A2D':'loplus','\u2A2E':'roplus','\u2A2F':'Cross','\u2A30':'timesd','\u2A31':'timesbar','\u2A33':'smashp','\u2A34':'lotimes','\u2A35':'rotimes','\u2A36':'otimesas','\u2A37':'Otimes','\u2A38':'odiv','\u2A39':'triplus','\u2A3A':'triminus','\u2A3B':'tritime','\u2A3C':'iprod','\u2A3F':'amalg','\u2A40':'capdot','\u2A42':'ncup','\u2A43':'ncap','\u2A44':'capand','\u2A45':'cupor','\u2A46':'cupcap','\u2A47':'capcup','\u2A48':'cupbrcap','\u2A49':'capbrcup','\u2A4A':'cupcup','\u2A4B':'capcap','\u2A4C':'ccups','\u2A4D':'ccaps','\u2A50':'ccupssm','\u2A53':'And','\u2A54':'Or','\u2A55':'andand','\u2A56':'oror','\u2A57':'orslope','\u2A58':'andslope','\u2A5A':'andv','\u2A5B':'orv','\u2A5C':'andd','\u2A5D':'ord','\u2A5F':'wedbar','\u2A66':'sdote','\u2A6A':'simdot','\u2A6D':'congdot','\u2A6D\u0338':'ncongdot','\u2A6E':'easter','\u2A6F':'apacir','\u2A70':'apE','\u2A70\u0338':'napE','\u2A71':'eplus','\u2A72':'pluse','\u2A73':'Esim','\u2A77':'eDDot','\u2A78':'equivDD','\u2A79':'ltcir','\u2A7A':'gtcir','\u2A7B':'ltquest','\u2A7C':'gtquest','\u2A7D':'les','\u2A7D\u0338':'nles','\u2A7E':'ges','\u2A7E\u0338':'nges','\u2A7F':'lesdot','\u2A80':'gesdot','\u2A81':'lesdoto','\u2A82':'gesdoto','\u2A83':'lesdotor','\u2A84':'gesdotol','\u2A85':'lap','\u2A86':'gap','\u2A87':'lne','\u2A88':'gne','\u2A89':'lnap','\u2A8A':'gnap','\u2A8B':'lEg','\u2A8C':'gEl','\u2A8D':'lsime','\u2A8E':'gsime','\u2A8F':'lsimg','\u2A90':'gsiml','\u2A91':'lgE','\u2A92':'glE','\u2A93':'lesges','\u2A94':'gesles','\u2A95':'els','\u2A96':'egs','\u2A97':'elsdot','\u2A98':'egsdot','\u2A99':'el','\u2A9A':'eg','\u2A9D':'siml','\u2A9E':'simg','\u2A9F':'simlE','\u2AA0':'simgE','\u2AA1':'LessLess','\u2AA1\u0338':'NotNestedLessLess','\u2AA2':'GreaterGreater','\u2AA2\u0338':'NotNestedGreaterGreater','\u2AA4':'glj','\u2AA5':'gla','\u2AA6':'ltcc','\u2AA7':'gtcc','\u2AA8':'lescc','\u2AA9':'gescc','\u2AAA':'smt','\u2AAB':'lat','\u2AAC':'smte','\u2AAC\uFE00':'smtes','\u2AAD':'late','\u2AAD\uFE00':'lates','\u2AAE':'bumpE','\u2AAF':'pre','\u2AAF\u0338':'npre','\u2AB0':'sce','\u2AB0\u0338':'nsce','\u2AB3':'prE','\u2AB4':'scE','\u2AB5':'prnE','\u2AB6':'scnE','\u2AB7':'prap','\u2AB8':'scap','\u2AB9':'prnap','\u2ABA':'scnap','\u2ABB':'Pr','\u2ABC':'Sc','\u2ABD':'subdot','\u2ABE':'supdot','\u2ABF':'subplus','\u2AC0':'supplus','\u2AC1':'submult','\u2AC2':'supmult','\u2AC3':'subedot','\u2AC4':'supedot','\u2AC5':'subE','\u2AC5\u0338':'nsubE','\u2AC6':'supE','\u2AC6\u0338':'nsupE','\u2AC7':'subsim','\u2AC8':'supsim','\u2ACB\uFE00':'vsubnE','\u2ACB':'subnE','\u2ACC\uFE00':'vsupnE','\u2ACC':'supnE','\u2ACF':'csub','\u2AD0':'csup','\u2AD1':'csube','\u2AD2':'csupe','\u2AD3':'subsup','\u2AD4':'supsub','\u2AD5':'subsub','\u2AD6':'supsup','\u2AD7':'suphsub','\u2AD8':'supdsub','\u2AD9':'forkv','\u2ADA':'topfork','\u2ADB':'mlcp','\u2AE4':'Dashv','\u2AE6':'Vdashl','\u2AE7':'Barv','\u2AE8':'vBar','\u2AE9':'vBarv','\u2AEB':'Vbar','\u2AEC':'Not','\u2AED':'bNot','\u2AEE':'rnmid','\u2AEF':'cirmid','\u2AF0':'midcir','\u2AF1':'topcir','\u2AF2':'nhpar','\u2AF3':'parsim','\u2AFD':'parsl','\u2AFD\u20E5':'nparsl','\u266D':'flat','\u266E':'natur','\u266F':'sharp','\xA4':'curren','\xA2':'cent','$':'dollar','\xA3':'pound','\xA5':'yen','\u20AC':'euro','\xB9':'sup1','\xBD':'half','\u2153':'frac13','\xBC':'frac14','\u2155':'frac15','\u2159':'frac16','\u215B':'frac18','\xB2':'sup2','\u2154':'frac23','\u2156':'frac25','\xB3':'sup3','\xBE':'frac34','\u2157':'frac35','\u215C':'frac38','\u2158':'frac45','\u215A':'frac56','\u215D':'frac58','\u215E':'frac78','\uD835\uDCB6':'ascr','\uD835\uDD52':'aopf','\uD835\uDD1E':'afr','\uD835\uDD38':'Aopf','\uD835\uDD04':'Afr','\uD835\uDC9C':'Ascr','\xAA':'ordf','\xE1':'aacute','\xC1':'Aacute','\xE0':'agrave','\xC0':'Agrave','\u0103':'abreve','\u0102':'Abreve','\xE2':'acirc','\xC2':'Acirc','\xE5':'aring','\xC5':'angst','\xE4':'auml','\xC4':'Auml','\xE3':'atilde','\xC3':'Atilde','\u0105':'aogon','\u0104':'Aogon','\u0101':'amacr','\u0100':'Amacr','\xE6':'aelig','\xC6':'AElig','\uD835\uDCB7':'bscr','\uD835\uDD53':'bopf','\uD835\uDD1F':'bfr','\uD835\uDD39':'Bopf','\u212C':'Bscr','\uD835\uDD05':'Bfr','\uD835\uDD20':'cfr','\uD835\uDCB8':'cscr','\uD835\uDD54':'copf','\u212D':'Cfr','\uD835\uDC9E':'Cscr','\u2102':'Copf','\u0107':'cacute','\u0106':'Cacute','\u0109':'ccirc','\u0108':'Ccirc','\u010D':'ccaron','\u010C':'Ccaron','\u010B':'cdot','\u010A':'Cdot','\xE7':'ccedil','\xC7':'Ccedil','\u2105':'incare','\uD835\uDD21':'dfr','\u2146':'dd','\uD835\uDD55':'dopf','\uD835\uDCB9':'dscr','\uD835\uDC9F':'Dscr','\uD835\uDD07':'Dfr','\u2145':'DD','\uD835\uDD3B':'Dopf','\u010F':'dcaron','\u010E':'Dcaron','\u0111':'dstrok','\u0110':'Dstrok','\xF0':'eth','\xD0':'ETH','\u2147':'ee','\u212F':'escr','\uD835\uDD22':'efr','\uD835\uDD56':'eopf','\u2130':'Escr','\uD835\uDD08':'Efr','\uD835\uDD3C':'Eopf','\xE9':'eacute','\xC9':'Eacute','\xE8':'egrave','\xC8':'Egrave','\xEA':'ecirc','\xCA':'Ecirc','\u011B':'ecaron','\u011A':'Ecaron','\xEB':'euml','\xCB':'Euml','\u0117':'edot','\u0116':'Edot','\u0119':'eogon','\u0118':'Eogon','\u0113':'emacr','\u0112':'Emacr','\uD835\uDD23':'ffr','\uD835\uDD57':'fopf','\uD835\uDCBB':'fscr','\uD835\uDD09':'Ffr','\uD835\uDD3D':'Fopf','\u2131':'Fscr','\uFB00':'fflig','\uFB03':'ffilig','\uFB04':'ffllig','\uFB01':'filig','fj':'fjlig','\uFB02':'fllig','\u0192':'fnof','\u210A':'gscr','\uD835\uDD58':'gopf','\uD835\uDD24':'gfr','\uD835\uDCA2':'Gscr','\uD835\uDD3E':'Gopf','\uD835\uDD0A':'Gfr','\u01F5':'gacute','\u011F':'gbreve','\u011E':'Gbreve','\u011D':'gcirc','\u011C':'Gcirc','\u0121':'gdot','\u0120':'Gdot','\u0122':'Gcedil','\uD835\uDD25':'hfr','\u210E':'planckh','\uD835\uDCBD':'hscr','\uD835\uDD59':'hopf','\u210B':'Hscr','\u210C':'Hfr','\u210D':'Hopf','\u0125':'hcirc','\u0124':'Hcirc','\u210F':'hbar','\u0127':'hstrok','\u0126':'Hstrok','\uD835\uDD5A':'iopf','\uD835\uDD26':'ifr','\uD835\uDCBE':'iscr','\u2148':'ii','\uD835\uDD40':'Iopf','\u2110':'Iscr','\u2111':'Im','\xED':'iacute','\xCD':'Iacute','\xEC':'igrave','\xCC':'Igrave','\xEE':'icirc','\xCE':'Icirc','\xEF':'iuml','\xCF':'Iuml','\u0129':'itilde','\u0128':'Itilde','\u0130':'Idot','\u012F':'iogon','\u012E':'Iogon','\u012B':'imacr','\u012A':'Imacr','\u0133':'ijlig','\u0132':'IJlig','\u0131':'imath','\uD835\uDCBF':'jscr','\uD835\uDD5B':'jopf','\uD835\uDD27':'jfr','\uD835\uDCA5':'Jscr','\uD835\uDD0D':'Jfr','\uD835\uDD41':'Jopf','\u0135':'jcirc','\u0134':'Jcirc','\u0237':'jmath','\uD835\uDD5C':'kopf','\uD835\uDCC0':'kscr','\uD835\uDD28':'kfr','\uD835\uDCA6':'Kscr','\uD835\uDD42':'Kopf','\uD835\uDD0E':'Kfr','\u0137':'kcedil','\u0136':'Kcedil','\uD835\uDD29':'lfr','\uD835\uDCC1':'lscr','\u2113':'ell','\uD835\uDD5D':'lopf','\u2112':'Lscr','\uD835\uDD0F':'Lfr','\uD835\uDD43':'Lopf','\u013A':'lacute','\u0139':'Lacute','\u013E':'lcaron','\u013D':'Lcaron','\u013C':'lcedil','\u013B':'Lcedil','\u0142':'lstrok','\u0141':'Lstrok','\u0140':'lmidot','\u013F':'Lmidot','\uD835\uDD2A':'mfr','\uD835\uDD5E':'mopf','\uD835\uDCC2':'mscr','\uD835\uDD10':'Mfr','\uD835\uDD44':'Mopf','\u2133':'Mscr','\uD835\uDD2B':'nfr','\uD835\uDD5F':'nopf','\uD835\uDCC3':'nscr','\u2115':'Nopf','\uD835\uDCA9':'Nscr','\uD835\uDD11':'Nfr','\u0144':'nacute','\u0143':'Nacute','\u0148':'ncaron','\u0147':'Ncaron','\xF1':'ntilde','\xD1':'Ntilde','\u0146':'ncedil','\u0145':'Ncedil','\u2116':'numero','\u014B':'eng','\u014A':'ENG','\uD835\uDD60':'oopf','\uD835\uDD2C':'ofr','\u2134':'oscr','\uD835\uDCAA':'Oscr','\uD835\uDD12':'Ofr','\uD835\uDD46':'Oopf','\xBA':'ordm','\xF3':'oacute','\xD3':'Oacute','\xF2':'ograve','\xD2':'Ograve','\xF4':'ocirc','\xD4':'Ocirc','\xF6':'ouml','\xD6':'Ouml','\u0151':'odblac','\u0150':'Odblac','\xF5':'otilde','\xD5':'Otilde','\xF8':'oslash','\xD8':'Oslash','\u014D':'omacr','\u014C':'Omacr','\u0153':'oelig','\u0152':'OElig','\uD835\uDD2D':'pfr','\uD835\uDCC5':'pscr','\uD835\uDD61':'popf','\u2119':'Popf','\uD835\uDD13':'Pfr','\uD835\uDCAB':'Pscr','\uD835\uDD62':'qopf','\uD835\uDD2E':'qfr','\uD835\uDCC6':'qscr','\uD835\uDCAC':'Qscr','\uD835\uDD14':'Qfr','\u211A':'Qopf','\u0138':'kgreen','\uD835\uDD2F':'rfr','\uD835\uDD63':'ropf','\uD835\uDCC7':'rscr','\u211B':'Rscr','\u211C':'Re','\u211D':'Ropf','\u0155':'racute','\u0154':'Racute','\u0159':'rcaron','\u0158':'Rcaron','\u0157':'rcedil','\u0156':'Rcedil','\uD835\uDD64':'sopf','\uD835\uDCC8':'sscr','\uD835\uDD30':'sfr','\uD835\uDD4A':'Sopf','\uD835\uDD16':'Sfr','\uD835\uDCAE':'Sscr','\u24C8':'oS','\u015B':'sacute','\u015A':'Sacute','\u015D':'scirc','\u015C':'Scirc','\u0161':'scaron','\u0160':'Scaron','\u015F':'scedil','\u015E':'Scedil','\xDF':'szlig','\uD835\uDD31':'tfr','\uD835\uDCC9':'tscr','\uD835\uDD65':'topf','\uD835\uDCAF':'Tscr','\uD835\uDD17':'Tfr','\uD835\uDD4B':'Topf','\u0165':'tcaron','\u0164':'Tcaron','\u0163':'tcedil','\u0162':'Tcedil','\u2122':'trade','\u0167':'tstrok','\u0166':'Tstrok','\uD835\uDCCA':'uscr','\uD835\uDD66':'uopf','\uD835\uDD32':'ufr','\uD835\uDD4C':'Uopf','\uD835\uDD18':'Ufr','\uD835\uDCB0':'Uscr','\xFA':'uacute','\xDA':'Uacute','\xF9':'ugrave','\xD9':'Ugrave','\u016D':'ubreve','\u016C':'Ubreve','\xFB':'ucirc','\xDB':'Ucirc','\u016F':'uring','\u016E':'Uring','\xFC':'uuml','\xDC':'Uuml','\u0171':'udblac','\u0170':'Udblac','\u0169':'utilde','\u0168':'Utilde','\u0173':'uogon','\u0172':'Uogon','\u016B':'umacr','\u016A':'Umacr','\uD835\uDD33':'vfr','\uD835\uDD67':'vopf','\uD835\uDCCB':'vscr','\uD835\uDD19':'Vfr','\uD835\uDD4D':'Vopf','\uD835\uDCB1':'Vscr','\uD835\uDD68':'wopf','\uD835\uDCCC':'wscr','\uD835\uDD34':'wfr','\uD835\uDCB2':'Wscr','\uD835\uDD4E':'Wopf','\uD835\uDD1A':'Wfr','\u0175':'wcirc','\u0174':'Wcirc','\uD835\uDD35':'xfr','\uD835\uDCCD':'xscr','\uD835\uDD69':'xopf','\uD835\uDD4F':'Xopf','\uD835\uDD1B':'Xfr','\uD835\uDCB3':'Xscr','\uD835\uDD36':'yfr','\uD835\uDCCE':'yscr','\uD835\uDD6A':'yopf','\uD835\uDCB4':'Yscr','\uD835\uDD1C':'Yfr','\uD835\uDD50':'Yopf','\xFD':'yacute','\xDD':'Yacute','\u0177':'ycirc','\u0176':'Ycirc','\xFF':'yuml','\u0178':'Yuml','\uD835\uDCCF':'zscr','\uD835\uDD37':'zfr','\uD835\uDD6B':'zopf','\u2128':'Zfr','\u2124':'Zopf','\uD835\uDCB5':'Zscr','\u017A':'zacute','\u0179':'Zacute','\u017E':'zcaron','\u017D':'Zcaron','\u017C':'zdot','\u017B':'Zdot','\u01B5':'imped','\xFE':'thorn','\xDE':'THORN','\u0149':'napos','\u03B1':'alpha','\u0391':'Alpha','\u03B2':'beta','\u0392':'Beta','\u03B3':'gamma','\u0393':'Gamma','\u03B4':'delta','\u0394':'Delta','\u03B5':'epsi','\u03F5':'epsiv','\u0395':'Epsilon','\u03DD':'gammad','\u03DC':'Gammad','\u03B6':'zeta','\u0396':'Zeta','\u03B7':'eta','\u0397':'Eta','\u03B8':'theta','\u03D1':'thetav','\u0398':'Theta','\u03B9':'iota','\u0399':'Iota','\u03BA':'kappa','\u03F0':'kappav','\u039A':'Kappa','\u03BB':'lambda','\u039B':'Lambda','\u03BC':'mu','\xB5':'micro','\u039C':'Mu','\u03BD':'nu','\u039D':'Nu','\u03BE':'xi','\u039E':'Xi','\u03BF':'omicron','\u039F':'Omicron','\u03C0':'pi','\u03D6':'piv','\u03A0':'Pi','\u03C1':'rho','\u03F1':'rhov','\u03A1':'Rho','\u03C3':'sigma','\u03A3':'Sigma','\u03C2':'sigmaf','\u03C4':'tau','\u03A4':'Tau','\u03C5':'upsi','\u03A5':'Upsilon','\u03D2':'Upsi','\u03C6':'phi','\u03D5':'phiv','\u03A6':'Phi','\u03C7':'chi','\u03A7':'Chi','\u03C8':'psi','\u03A8':'Psi','\u03C9':'omega','\u03A9':'ohm','\u0430':'acy','\u0410':'Acy','\u0431':'bcy','\u0411':'Bcy','\u0432':'vcy','\u0412':'Vcy','\u0433':'gcy','\u0413':'Gcy','\u0453':'gjcy','\u0403':'GJcy','\u0434':'dcy','\u0414':'Dcy','\u0452':'djcy','\u0402':'DJcy','\u0435':'iecy','\u0415':'IEcy','\u0451':'iocy','\u0401':'IOcy','\u0454':'jukcy','\u0404':'Jukcy','\u0436':'zhcy','\u0416':'ZHcy','\u0437':'zcy','\u0417':'Zcy','\u0455':'dscy','\u0405':'DScy','\u0438':'icy','\u0418':'Icy','\u0456':'iukcy','\u0406':'Iukcy','\u0457':'yicy','\u0407':'YIcy','\u0439':'jcy','\u0419':'Jcy','\u0458':'jsercy','\u0408':'Jsercy','\u043A':'kcy','\u041A':'Kcy','\u045C':'kjcy','\u040C':'KJcy','\u043B':'lcy','\u041B':'Lcy','\u0459':'ljcy','\u0409':'LJcy','\u043C':'mcy','\u041C':'Mcy','\u043D':'ncy','\u041D':'Ncy','\u045A':'njcy','\u040A':'NJcy','\u043E':'ocy','\u041E':'Ocy','\u043F':'pcy','\u041F':'Pcy','\u0440':'rcy','\u0420':'Rcy','\u0441':'scy','\u0421':'Scy','\u0442':'tcy','\u0422':'Tcy','\u045B':'tshcy','\u040B':'TSHcy','\u0443':'ucy','\u0423':'Ucy','\u045E':'ubrcy','\u040E':'Ubrcy','\u0444':'fcy','\u0424':'Fcy','\u0445':'khcy','\u0425':'KHcy','\u0446':'tscy','\u0426':'TScy','\u0447':'chcy','\u0427':'CHcy','\u045F':'dzcy','\u040F':'DZcy','\u0448':'shcy','\u0428':'SHcy','\u0449':'shchcy','\u0429':'SHCHcy','\u044A':'hardcy','\u042A':'HARDcy','\u044B':'ycy','\u042B':'Ycy','\u044C':'softcy','\u042C':'SOFTcy','\u044D':'ecy','\u042D':'Ecy','\u044E':'yucy','\u042E':'YUcy','\u044F':'yacy','\u042F':'YAcy','\u2135':'aleph','\u2136':'beth','\u2137':'gimel','\u2138':'daleth'};
-
- var regexEscape = /["&'<>`]/g;
- var escapeMap = {
- '"': '"',
- '&': '&',
- '\'': ''',
- '<': '<',
- // See https://mathiasbynens.be/notes/ambiguous-ampersands: in HTML, the
- // following is not strictly necessary unless it’s part of a tag or an
- // unquoted attribute value. We’re only escaping it to support those
- // situations, and for XML support.
- '>': '>',
- // In Internet Explorer ≤ 8, the backtick character can be used
- // to break out of (un)quoted attribute values or HTML comments.
- // See http://html5sec.org/#102, http://html5sec.org/#108, and
- // http://html5sec.org/#133.
- '`': '`'
- };
-
- var regexInvalidEntity = /(?:[xX][^a-fA-F0-9]|[^0-9xX])/;
- var regexInvalidRawCodePoint = /[\0-\x08\x0B\x0E-\x1F\x7F-\x9F\uFDD0-\uFDEF\uFFFE\uFFFF]|[\uD83F\uD87F\uD8BF\uD8FF\uD93F\uD97F\uD9BF\uD9FF\uDA3F\uDA7F\uDABF\uDAFF\uDB3F\uDB7F\uDBBF\uDBFF][\uDFFE\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
- var regexDecode = /&(CounterClockwiseContourIntegral|DoubleLongLeftRightArrow|ClockwiseContourIntegral|NotNestedGreaterGreater|NotSquareSupersetEqual|DiacriticalDoubleAcute|NotRightTriangleEqual|NotSucceedsSlantEqual|NotPrecedesSlantEqual|CloseCurlyDoubleQuote|NegativeVeryThinSpace|DoubleContourIntegral|FilledVerySmallSquare|CapitalDifferentialD|OpenCurlyDoubleQuote|EmptyVerySmallSquare|NestedGreaterGreater|DoubleLongRightArrow|NotLeftTriangleEqual|NotGreaterSlantEqual|ReverseUpEquilibrium|DoubleLeftRightArrow|NotSquareSubsetEqual|NotDoubleVerticalBar|RightArrowLeftArrow|NotGreaterFullEqual|NotRightTriangleBar|SquareSupersetEqual|DownLeftRightVector|DoubleLongLeftArrow|leftrightsquigarrow|LeftArrowRightArrow|NegativeMediumSpace|blacktriangleright|RightDownVectorBar|PrecedesSlantEqual|RightDoubleBracket|SucceedsSlantEqual|NotLeftTriangleBar|RightTriangleEqual|SquareIntersection|RightDownTeeVector|ReverseEquilibrium|NegativeThickSpace|longleftrightarrow|Longleftrightarrow|LongLeftRightArrow|DownRightTeeVector|DownRightVectorBar|GreaterSlantEqual|SquareSubsetEqual|LeftDownVectorBar|LeftDoubleBracket|VerticalSeparator|rightleftharpoons|NotGreaterGreater|NotSquareSuperset|blacktriangleleft|blacktriangledown|NegativeThinSpace|LeftDownTeeVector|NotLessSlantEqual|leftrightharpoons|DoubleUpDownArrow|DoubleVerticalBar|LeftTriangleEqual|FilledSmallSquare|twoheadrightarrow|NotNestedLessLess|DownLeftTeeVector|DownLeftVectorBar|RightAngleBracket|NotTildeFullEqual|NotReverseElement|RightUpDownVector|DiacriticalTilde|NotSucceedsTilde|circlearrowright|NotPrecedesEqual|rightharpoondown|DoubleRightArrow|NotSucceedsEqual|NonBreakingSpace|NotRightTriangle|LessEqualGreater|RightUpTeeVector|LeftAngleBracket|GreaterFullEqual|DownArrowUpArrow|RightUpVectorBar|twoheadleftarrow|GreaterEqualLess|downharpoonright|RightTriangleBar|ntrianglerighteq|NotSupersetEqual|LeftUpDownVector|DiacriticalAcute|rightrightarrows|vartriangleright|UpArrowDownArrow|DiacriticalGrave|UnderParenthesis|EmptySmallSquare|LeftUpVectorBar|leftrightarrows|DownRightVector|downharpoonleft|trianglerighteq|ShortRightArrow|OverParenthesis|DoubleLeftArrow|DoubleDownArrow|NotSquareSubset|bigtriangledown|ntrianglelefteq|UpperRightArrow|curvearrowright|vartriangleleft|NotLeftTriangle|nleftrightarrow|LowerRightArrow|NotHumpDownHump|NotGreaterTilde|rightthreetimes|LeftUpTeeVector|NotGreaterEqual|straightepsilon|LeftTriangleBar|rightsquigarrow|ContourIntegral|rightleftarrows|CloseCurlyQuote|RightDownVector|LeftRightVector|nLeftrightarrow|leftharpoondown|circlearrowleft|SquareSuperset|OpenCurlyQuote|hookrightarrow|HorizontalLine|DiacriticalDot|NotLessGreater|ntriangleright|DoubleRightTee|InvisibleComma|InvisibleTimes|LowerLeftArrow|DownLeftVector|NotSubsetEqual|curvearrowleft|trianglelefteq|NotVerticalBar|TildeFullEqual|downdownarrows|NotGreaterLess|RightTeeVector|ZeroWidthSpace|looparrowright|LongRightArrow|doublebarwedge|ShortLeftArrow|ShortDownArrow|RightVectorBar|GreaterGreater|ReverseElement|rightharpoonup|LessSlantEqual|leftthreetimes|upharpoonright|rightarrowtail|LeftDownVector|Longrightarrow|NestedLessLess|UpperLeftArrow|nshortparallel|leftleftarrows|leftrightarrow|Leftrightarrow|LeftRightArrow|longrightarrow|upharpoonleft|RightArrowBar|ApplyFunction|LeftTeeVector|leftarrowtail|NotEqualTilde|varsubsetneqq|varsupsetneqq|RightTeeArrow|SucceedsEqual|SucceedsTilde|LeftVectorBar|SupersetEqual|hookleftarrow|DifferentialD|VerticalTilde|VeryThinSpace|blacktriangle|bigtriangleup|LessFullEqual|divideontimes|leftharpoonup|UpEquilibrium|ntriangleleft|RightTriangle|measuredangle|shortparallel|longleftarrow|Longleftarrow|LongLeftArrow|DoubleLeftTee|Poincareplane|PrecedesEqual|triangleright|DoubleUpArrow|RightUpVector|fallingdotseq|looparrowleft|PrecedesTilde|NotTildeEqual|NotTildeTilde|smallsetminus|Proportional|triangleleft|triangledown|UnderBracket|NotHumpEqual|exponentiale|ExponentialE|NotLessTilde|HilbertSpace|RightCeiling|blacklozenge|varsupsetneq|HumpDownHump|GreaterEqual|VerticalLine|LeftTeeArrow|NotLessEqual|DownTeeArrow|LeftTriangle|varsubsetneq|Intersection|NotCongruent|DownArrowBar|LeftUpVector|LeftArrowBar|risingdotseq|GreaterTilde|RoundImplies|SquareSubset|ShortUpArrow|NotSuperset|quaternions|precnapprox|backepsilon|preccurlyeq|OverBracket|blacksquare|MediumSpace|VerticalBar|circledcirc|circleddash|CircleMinus|CircleTimes|LessGreater|curlyeqprec|curlyeqsucc|diamondsuit|UpDownArrow|Updownarrow|RuleDelayed|Rrightarrow|updownarrow|RightVector|nRightarrow|nrightarrow|eqslantless|LeftCeiling|Equilibrium|SmallCircle|expectation|NotSucceeds|thickapprox|GreaterLess|SquareUnion|NotPrecedes|NotLessLess|straightphi|succnapprox|succcurlyeq|SubsetEqual|sqsupseteq|Proportion|Laplacetrf|ImaginaryI|supsetneqq|NotGreater|gtreqqless|NotElement|ThickSpace|TildeEqual|TildeTilde|Fouriertrf|rmoustache|EqualTilde|eqslantgtr|UnderBrace|LeftVector|UpArrowBar|nLeftarrow|nsubseteqq|subsetneqq|nsupseteqq|nleftarrow|succapprox|lessapprox|UpTeeArrow|upuparrows|curlywedge|lesseqqgtr|varepsilon|varnothing|RightFloor|complement|CirclePlus|sqsubseteq|Lleftarrow|circledast|RightArrow|Rightarrow|rightarrow|lmoustache|Bernoullis|precapprox|mapstoleft|mapstodown|longmapsto|dotsquare|downarrow|DoubleDot|nsubseteq|supsetneq|leftarrow|nsupseteq|subsetneq|ThinSpace|ngeqslant|subseteqq|HumpEqual|NotSubset|triangleq|NotCupCap|lesseqgtr|heartsuit|TripleDot|Leftarrow|Coproduct|Congruent|varpropto|complexes|gvertneqq|LeftArrow|LessTilde|supseteqq|MinusPlus|CircleDot|nleqslant|NotExists|gtreqless|nparallel|UnionPlus|LeftFloor|checkmark|CenterDot|centerdot|Mellintrf|gtrapprox|bigotimes|OverBrace|spadesuit|therefore|pitchfork|rationals|PlusMinus|Backslash|Therefore|DownBreve|backsimeq|backprime|DownArrow|nshortmid|Downarrow|lvertneqq|eqvparsl|imagline|imagpart|infintie|integers|Integral|intercal|LessLess|Uarrocir|intlarhk|sqsupset|angmsdaf|sqsubset|llcorner|vartheta|cupbrcap|lnapprox|Superset|SuchThat|succnsim|succneqq|angmsdag|biguplus|curlyvee|trpezium|Succeeds|NotTilde|bigwedge|angmsdah|angrtvbd|triminus|cwconint|fpartint|lrcorner|smeparsl|subseteq|urcorner|lurdshar|laemptyv|DDotrahd|approxeq|ldrushar|awconint|mapstoup|backcong|shortmid|triangle|geqslant|gesdotol|timesbar|circledR|circledS|setminus|multimap|naturals|scpolint|ncongdot|RightTee|boxminus|gnapprox|boxtimes|andslope|thicksim|angmsdaa|varsigma|cirfnint|rtriltri|angmsdab|rppolint|angmsdac|barwedge|drbkarow|clubsuit|thetasym|bsolhsub|capbrcup|dzigrarr|doteqdot|DotEqual|dotminus|UnderBar|NotEqual|realpart|otimesas|ulcorner|hksearow|hkswarow|parallel|PartialD|elinters|emptyset|plusacir|bbrktbrk|angmsdad|pointint|bigoplus|angmsdae|Precedes|bigsqcup|varkappa|notindot|supseteq|precneqq|precnsim|profalar|profline|profsurf|leqslant|lesdotor|raemptyv|subplus|notnivb|notnivc|subrarr|zigrarr|vzigzag|submult|subedot|Element|between|cirscir|larrbfs|larrsim|lotimes|lbrksld|lbrkslu|lozenge|ldrdhar|dbkarow|bigcirc|epsilon|simrarr|simplus|ltquest|Epsilon|luruhar|gtquest|maltese|npolint|eqcolon|npreceq|bigodot|ddagger|gtrless|bnequiv|harrcir|ddotseq|equivDD|backsim|demptyv|nsqsube|nsqsupe|Upsilon|nsubset|upsilon|minusdu|nsucceq|swarrow|nsupset|coloneq|searrow|boxplus|napprox|natural|asympeq|alefsym|congdot|nearrow|bigstar|diamond|supplus|tritime|LeftTee|nvinfin|triplus|NewLine|nvltrie|nvrtrie|nwarrow|nexists|Diamond|ruluhar|Implies|supmult|angzarr|suplarr|suphsub|questeq|because|digamma|Because|olcross|bemptyv|omicron|Omicron|rotimes|NoBreak|intprod|angrtvb|orderof|uwangle|suphsol|lesdoto|orslope|DownTee|realine|cudarrl|rdldhar|OverBar|supedot|lessdot|supdsub|topfork|succsim|rbrkslu|rbrksld|pertenk|cudarrr|isindot|planckh|lessgtr|pluscir|gesdoto|plussim|plustwo|lesssim|cularrp|rarrsim|Cayleys|notinva|notinvb|notinvc|UpArrow|Uparrow|uparrow|NotLess|dwangle|precsim|Product|curarrm|Cconint|dotplus|rarrbfs|ccupssm|Cedilla|cemptyv|notniva|quatint|frac35|frac38|frac45|frac56|frac58|frac78|tridot|xoplus|gacute|gammad|Gammad|lfisht|lfloor|bigcup|sqsupe|gbreve|Gbreve|lharul|sqsube|sqcups|Gcedil|apacir|llhard|lmidot|Lmidot|lmoust|andand|sqcaps|approx|Abreve|spades|circeq|tprime|divide|topcir|Assign|topbot|gesdot|divonx|xuplus|timesd|gesles|atilde|solbar|SOFTcy|loplus|timesb|lowast|lowbar|dlcorn|dlcrop|softcy|dollar|lparlt|thksim|lrhard|Atilde|lsaquo|smashp|bigvee|thinsp|wreath|bkarow|lsquor|lstrok|Lstrok|lthree|ltimes|ltlarr|DotDot|simdot|ltrPar|weierp|xsqcup|angmsd|sigmav|sigmaf|zeetrf|Zcaron|zcaron|mapsto|vsupne|thetav|cirmid|marker|mcomma|Zacute|vsubnE|there4|gtlPar|vsubne|bottom|gtrarr|SHCHcy|shchcy|midast|midcir|middot|minusb|minusd|gtrdot|bowtie|sfrown|mnplus|models|colone|seswar|Colone|mstpos|searhk|gtrsim|nacute|Nacute|boxbox|telrec|hairsp|Tcedil|nbumpe|scnsim|ncaron|Ncaron|ncedil|Ncedil|hamilt|Scedil|nearhk|hardcy|HARDcy|tcedil|Tcaron|commat|nequiv|nesear|tcaron|target|hearts|nexist|varrho|scedil|Scaron|scaron|hellip|Sacute|sacute|hercon|swnwar|compfn|rtimes|rthree|rsquor|rsaquo|zacute|wedgeq|homtht|barvee|barwed|Barwed|rpargt|horbar|conint|swarhk|roplus|nltrie|hslash|hstrok|Hstrok|rmoust|Conint|bprime|hybull|hyphen|iacute|Iacute|supsup|supsub|supsim|varphi|coprod|brvbar|agrave|Supset|supset|igrave|Igrave|notinE|Agrave|iiiint|iinfin|copysr|wedbar|Verbar|vangrt|becaus|incare|verbar|inodot|bullet|drcorn|intcal|drcrop|cularr|vellip|Utilde|bumpeq|cupcap|dstrok|Dstrok|CupCap|cupcup|cupdot|eacute|Eacute|supdot|iquest|easter|ecaron|Ecaron|ecolon|isinsv|utilde|itilde|Itilde|curarr|succeq|Bumpeq|cacute|ulcrop|nparsl|Cacute|nprcue|egrave|Egrave|nrarrc|nrarrw|subsup|subsub|nrtrie|jsercy|nsccue|Jsercy|kappav|kcedil|Kcedil|subsim|ulcorn|nsimeq|egsdot|veebar|kgreen|capand|elsdot|Subset|subset|curren|aacute|lacute|Lacute|emptyv|ntilde|Ntilde|lagran|lambda|Lambda|capcap|Ugrave|langle|subdot|emsp13|numero|emsp14|nvdash|nvDash|nVdash|nVDash|ugrave|ufisht|nvHarr|larrfs|nvlArr|larrhk|larrlp|larrpl|nvrArr|Udblac|nwarhk|larrtl|nwnear|oacute|Oacute|latail|lAtail|sstarf|lbrace|odblac|Odblac|lbrack|udblac|odsold|eparsl|lcaron|Lcaron|ograve|Ograve|lcedil|Lcedil|Aacute|ssmile|ssetmn|squarf|ldquor|capcup|ominus|cylcty|rharul|eqcirc|dagger|rfloor|rfisht|Dagger|daleth|equals|origof|capdot|equest|dcaron|Dcaron|rdquor|oslash|Oslash|otilde|Otilde|otimes|Otimes|urcrop|Ubreve|ubreve|Yacute|Uacute|uacute|Rcedil|rcedil|urcorn|parsim|Rcaron|Vdashl|rcaron|Tstrok|percnt|period|permil|Exists|yacute|rbrack|rbrace|phmmat|ccaron|Ccaron|planck|ccedil|plankv|tstrok|female|plusdo|plusdu|ffilig|plusmn|ffllig|Ccedil|rAtail|dfisht|bernou|ratail|Rarrtl|rarrtl|angsph|rarrpl|rarrlp|rarrhk|xwedge|xotime|forall|ForAll|Vvdash|vsupnE|preceq|bigcap|frac12|frac13|frac14|primes|rarrfs|prnsim|frac15|Square|frac16|square|lesdot|frac18|frac23|propto|prurel|rarrap|rangle|puncsp|frac25|Racute|qprime|racute|lesges|frac34|abreve|AElig|eqsim|utdot|setmn|urtri|Equal|Uring|seArr|uring|searr|dashv|Dashv|mumap|nabla|iogon|Iogon|sdote|sdotb|scsim|napid|napos|equiv|natur|Acirc|dblac|erarr|nbump|iprod|erDot|ucirc|awint|esdot|angrt|ncong|isinE|scnap|Scirc|scirc|ndash|isins|Ubrcy|nearr|neArr|isinv|nedot|ubrcy|acute|Ycirc|iukcy|Iukcy|xutri|nesim|caret|jcirc|Jcirc|caron|twixt|ddarr|sccue|exist|jmath|sbquo|ngeqq|angst|ccaps|lceil|ngsim|UpTee|delta|Delta|rtrif|nharr|nhArr|nhpar|rtrie|jukcy|Jukcy|kappa|rsquo|Kappa|nlarr|nlArr|TSHcy|rrarr|aogon|Aogon|fflig|xrarr|tshcy|ccirc|nleqq|filig|upsih|nless|dharl|nlsim|fjlig|ropar|nltri|dharr|robrk|roarr|fllig|fltns|roang|rnmid|subnE|subne|lAarr|trisb|Ccirc|acirc|ccups|blank|VDash|forkv|Vdash|langd|cedil|blk12|blk14|laquo|strns|diams|notin|vDash|larrb|blk34|block|disin|uplus|vdash|vBarv|aelig|starf|Wedge|check|xrArr|lates|lbarr|lBarr|notni|lbbrk|bcong|frasl|lbrke|frown|vrtri|vprop|vnsup|gamma|Gamma|wedge|xodot|bdquo|srarr|doteq|ldquo|boxdl|boxdL|gcirc|Gcirc|boxDl|boxDL|boxdr|boxdR|boxDr|TRADE|trade|rlhar|boxDR|vnsub|npart|vltri|rlarr|boxhd|boxhD|nprec|gescc|nrarr|nrArr|boxHd|boxHD|boxhu|boxhU|nrtri|boxHu|clubs|boxHU|times|colon|Colon|gimel|xlArr|Tilde|nsime|tilde|nsmid|nspar|THORN|thorn|xlarr|nsube|nsubE|thkap|xhArr|comma|nsucc|boxul|boxuL|nsupe|nsupE|gneqq|gnsim|boxUl|boxUL|grave|boxur|boxuR|boxUr|boxUR|lescc|angle|bepsi|boxvh|varpi|boxvH|numsp|Theta|gsime|gsiml|theta|boxVh|boxVH|boxvl|gtcir|gtdot|boxvL|boxVl|boxVL|crarr|cross|Cross|nvsim|boxvr|nwarr|nwArr|sqsup|dtdot|Uogon|lhard|lharu|dtrif|ocirc|Ocirc|lhblk|duarr|odash|sqsub|Hacek|sqcup|llarr|duhar|oelig|OElig|ofcir|boxvR|uogon|lltri|boxVr|csube|uuarr|ohbar|csupe|ctdot|olarr|olcir|harrw|oline|sqcap|omacr|Omacr|omega|Omega|boxVR|aleph|lneqq|lnsim|loang|loarr|rharu|lobrk|hcirc|operp|oplus|rhard|Hcirc|orarr|Union|order|ecirc|Ecirc|cuepr|szlig|cuesc|breve|reals|eDDot|Breve|hoarr|lopar|utrif|rdquo|Umacr|umacr|efDot|swArr|ultri|alpha|rceil|ovbar|swarr|Wcirc|wcirc|smtes|smile|bsemi|lrarr|aring|parsl|lrhar|bsime|uhblk|lrtri|cupor|Aring|uharr|uharl|slarr|rbrke|bsolb|lsime|rbbrk|RBarr|lsimg|phone|rBarr|rbarr|icirc|lsquo|Icirc|emacr|Emacr|ratio|simne|plusb|simlE|simgE|simeq|pluse|ltcir|ltdot|empty|xharr|xdtri|iexcl|Alpha|ltrie|rarrw|pound|ltrif|xcirc|bumpe|prcue|bumpE|asymp|amacr|cuvee|Sigma|sigma|iiint|udhar|iiota|ijlig|IJlig|supnE|imacr|Imacr|prime|Prime|image|prnap|eogon|Eogon|rarrc|mdash|mDDot|cuwed|imath|supne|imped|Amacr|udarr|prsim|micro|rarrb|cwint|raquo|infin|eplus|range|rangd|Ucirc|radic|minus|amalg|veeeq|rAarr|epsiv|ycirc|quest|sharp|quot|zwnj|Qscr|race|qscr|Qopf|qopf|qint|rang|Rang|Zscr|zscr|Zopf|zopf|rarr|rArr|Rarr|Pscr|pscr|prop|prod|prnE|prec|ZHcy|zhcy|prap|Zeta|zeta|Popf|popf|Zdot|plus|zdot|Yuml|yuml|phiv|YUcy|yucy|Yscr|yscr|perp|Yopf|yopf|part|para|YIcy|Ouml|rcub|yicy|YAcy|rdca|ouml|osol|Oscr|rdsh|yacy|real|oscr|xvee|andd|rect|andv|Xscr|oror|ordm|ordf|xscr|ange|aopf|Aopf|rHar|Xopf|opar|Oopf|xopf|xnis|rhov|oopf|omid|xmap|oint|apid|apos|ogon|ascr|Ascr|odot|odiv|xcup|xcap|ocir|oast|nvlt|nvle|nvgt|nvge|nvap|Wscr|wscr|auml|ntlg|ntgl|nsup|nsub|nsim|Nscr|nscr|nsce|Wopf|ring|npre|wopf|npar|Auml|Barv|bbrk|Nopf|nopf|nmid|nLtv|beta|ropf|Ropf|Beta|beth|nles|rpar|nleq|bnot|bNot|nldr|NJcy|rscr|Rscr|Vscr|vscr|rsqb|njcy|bopf|nisd|Bopf|rtri|Vopf|nGtv|ngtr|vopf|boxh|boxH|boxv|nges|ngeq|boxV|bscr|scap|Bscr|bsim|Vert|vert|bsol|bull|bump|caps|cdot|ncup|scnE|ncap|nbsp|napE|Cdot|cent|sdot|Vbar|nang|vBar|chcy|Mscr|mscr|sect|semi|CHcy|Mopf|mopf|sext|circ|cire|mldr|mlcp|cirE|comp|shcy|SHcy|vArr|varr|cong|copf|Copf|copy|COPY|malt|male|macr|lvnE|cscr|ltri|sime|ltcc|simg|Cscr|siml|csub|Uuml|lsqb|lsim|uuml|csup|Lscr|lscr|utri|smid|lpar|cups|smte|lozf|darr|Lopf|Uscr|solb|lopf|sopf|Sopf|lneq|uscr|spar|dArr|lnap|Darr|dash|Sqrt|LJcy|ljcy|lHar|dHar|Upsi|upsi|diam|lesg|djcy|DJcy|leqq|dopf|Dopf|dscr|Dscr|dscy|ldsh|ldca|squf|DScy|sscr|Sscr|dsol|lcub|late|star|Star|Uopf|Larr|lArr|larr|uopf|dtri|dzcy|sube|subE|Lang|lang|Kscr|kscr|Kopf|kopf|KJcy|kjcy|KHcy|khcy|DZcy|ecir|edot|eDot|Jscr|jscr|succ|Jopf|jopf|Edot|uHar|emsp|ensp|Iuml|iuml|eopf|isin|Iscr|iscr|Eopf|epar|sung|epsi|escr|sup1|sup2|sup3|Iota|iota|supe|supE|Iopf|iopf|IOcy|iocy|Escr|esim|Esim|imof|Uarr|QUOT|uArr|uarr|euml|IEcy|iecy|Idot|Euml|euro|excl|Hscr|hscr|Hopf|hopf|TScy|tscy|Tscr|hbar|tscr|flat|tbrk|fnof|hArr|harr|half|fopf|Fopf|tdot|gvnE|fork|trie|gtcc|fscr|Fscr|gdot|gsim|Gscr|gscr|Gopf|gopf|gneq|Gdot|tosa|gnap|Topf|topf|geqq|toea|GJcy|gjcy|tint|gesl|mid|Sfr|ggg|top|ges|gla|glE|glj|geq|gne|gEl|gel|gnE|Gcy|gcy|gap|Tfr|tfr|Tcy|tcy|Hat|Tau|Ffr|tau|Tab|hfr|Hfr|ffr|Fcy|fcy|icy|Icy|iff|ETH|eth|ifr|Ifr|Eta|eta|int|Int|Sup|sup|ucy|Ucy|Sum|sum|jcy|ENG|ufr|Ufr|eng|Jcy|jfr|els|ell|egs|Efr|efr|Jfr|uml|kcy|Kcy|Ecy|ecy|kfr|Kfr|lap|Sub|sub|lat|lcy|Lcy|leg|Dot|dot|lEg|leq|les|squ|div|die|lfr|Lfr|lgE|Dfr|dfr|Del|deg|Dcy|dcy|lne|lnE|sol|loz|smt|Cup|lrm|cup|lsh|Lsh|sim|shy|map|Map|mcy|Mcy|mfr|Mfr|mho|gfr|Gfr|sfr|cir|Chi|chi|nap|Cfr|vcy|Vcy|cfr|Scy|scy|ncy|Ncy|vee|Vee|Cap|cap|nfr|scE|sce|Nfr|nge|ngE|nGg|vfr|Vfr|ngt|bot|nGt|nis|niv|Rsh|rsh|nle|nlE|bne|Bfr|bfr|nLl|nlt|nLt|Bcy|bcy|not|Not|rlm|wfr|Wfr|npr|nsc|num|ocy|ast|Ocy|ofr|xfr|Xfr|Ofr|ogt|ohm|apE|olt|Rho|ape|rho|Rfr|rfr|ord|REG|ang|reg|orv|And|and|AMP|Rcy|amp|Afr|ycy|Ycy|yen|yfr|Yfr|rcy|par|pcy|Pcy|pfr|Pfr|phi|Phi|afr|Acy|acy|zcy|Zcy|piv|acE|acd|zfr|Zfr|pre|prE|psi|Psi|qfr|Qfr|zwj|Or|ge|Gg|gt|gg|el|oS|lt|Lt|LT|Re|lg|gl|eg|ne|Im|it|le|DD|wp|wr|nu|Nu|dd|lE|Sc|sc|pi|Pi|ee|af|ll|Ll|rx|gE|xi|pm|Xi|ic|pr|Pr|in|ni|mp|mu|ac|Mu|or|ap|Gt|GT|ii);|&(Aacute|Agrave|Atilde|Ccedil|Eacute|Egrave|Iacute|Igrave|Ntilde|Oacute|Ograve|Oslash|Otilde|Uacute|Ugrave|Yacute|aacute|agrave|atilde|brvbar|ccedil|curren|divide|eacute|egrave|frac12|frac14|frac34|iacute|igrave|iquest|middot|ntilde|oacute|ograve|oslash|otilde|plusmn|uacute|ugrave|yacute|AElig|Acirc|Aring|Ecirc|Icirc|Ocirc|THORN|Ucirc|acirc|acute|aelig|aring|cedil|ecirc|icirc|iexcl|laquo|micro|ocirc|pound|raquo|szlig|thorn|times|ucirc|Auml|COPY|Euml|Iuml|Ouml|QUOT|Uuml|auml|cent|copy|euml|iuml|macr|nbsp|ordf|ordm|ouml|para|quot|sect|sup1|sup2|sup3|uuml|yuml|AMP|ETH|REG|amp|deg|eth|not|reg|shy|uml|yen|GT|LT|gt|lt)(?!;)([=a-zA-Z0-9]?)|([0-9]+)(;?)|[xX]([a-fA-F0-9]+)(;?)|&([0-9a-zA-Z]+)/g;
- var decodeMap = {'aacute':'\xE1','Aacute':'\xC1','abreve':'\u0103','Abreve':'\u0102','ac':'\u223E','acd':'\u223F','acE':'\u223E\u0333','acirc':'\xE2','Acirc':'\xC2','acute':'\xB4','acy':'\u0430','Acy':'\u0410','aelig':'\xE6','AElig':'\xC6','af':'\u2061','afr':'\uD835\uDD1E','Afr':'\uD835\uDD04','agrave':'\xE0','Agrave':'\xC0','alefsym':'\u2135','aleph':'\u2135','alpha':'\u03B1','Alpha':'\u0391','amacr':'\u0101','Amacr':'\u0100','amalg':'\u2A3F','amp':'&','AMP':'&','and':'\u2227','And':'\u2A53','andand':'\u2A55','andd':'\u2A5C','andslope':'\u2A58','andv':'\u2A5A','ang':'\u2220','ange':'\u29A4','angle':'\u2220','angmsd':'\u2221','angmsdaa':'\u29A8','angmsdab':'\u29A9','angmsdac':'\u29AA','angmsdad':'\u29AB','angmsdae':'\u29AC','angmsdaf':'\u29AD','angmsdag':'\u29AE','angmsdah':'\u29AF','angrt':'\u221F','angrtvb':'\u22BE','angrtvbd':'\u299D','angsph':'\u2222','angst':'\xC5','angzarr':'\u237C','aogon':'\u0105','Aogon':'\u0104','aopf':'\uD835\uDD52','Aopf':'\uD835\uDD38','ap':'\u2248','apacir':'\u2A6F','ape':'\u224A','apE':'\u2A70','apid':'\u224B','apos':'\'','ApplyFunction':'\u2061','approx':'\u2248','approxeq':'\u224A','aring':'\xE5','Aring':'\xC5','ascr':'\uD835\uDCB6','Ascr':'\uD835\uDC9C','Assign':'\u2254','ast':'*','asymp':'\u2248','asympeq':'\u224D','atilde':'\xE3','Atilde':'\xC3','auml':'\xE4','Auml':'\xC4','awconint':'\u2233','awint':'\u2A11','backcong':'\u224C','backepsilon':'\u03F6','backprime':'\u2035','backsim':'\u223D','backsimeq':'\u22CD','Backslash':'\u2216','Barv':'\u2AE7','barvee':'\u22BD','barwed':'\u2305','Barwed':'\u2306','barwedge':'\u2305','bbrk':'\u23B5','bbrktbrk':'\u23B6','bcong':'\u224C','bcy':'\u0431','Bcy':'\u0411','bdquo':'\u201E','becaus':'\u2235','because':'\u2235','Because':'\u2235','bemptyv':'\u29B0','bepsi':'\u03F6','bernou':'\u212C','Bernoullis':'\u212C','beta':'\u03B2','Beta':'\u0392','beth':'\u2136','between':'\u226C','bfr':'\uD835\uDD1F','Bfr':'\uD835\uDD05','bigcap':'\u22C2','bigcirc':'\u25EF','bigcup':'\u22C3','bigodot':'\u2A00','bigoplus':'\u2A01','bigotimes':'\u2A02','bigsqcup':'\u2A06','bigstar':'\u2605','bigtriangledown':'\u25BD','bigtriangleup':'\u25B3','biguplus':'\u2A04','bigvee':'\u22C1','bigwedge':'\u22C0','bkarow':'\u290D','blacklozenge':'\u29EB','blacksquare':'\u25AA','blacktriangle':'\u25B4','blacktriangledown':'\u25BE','blacktriangleleft':'\u25C2','blacktriangleright':'\u25B8','blank':'\u2423','blk12':'\u2592','blk14':'\u2591','blk34':'\u2593','block':'\u2588','bne':'=\u20E5','bnequiv':'\u2261\u20E5','bnot':'\u2310','bNot':'\u2AED','bopf':'\uD835\uDD53','Bopf':'\uD835\uDD39','bot':'\u22A5','bottom':'\u22A5','bowtie':'\u22C8','boxbox':'\u29C9','boxdl':'\u2510','boxdL':'\u2555','boxDl':'\u2556','boxDL':'\u2557','boxdr':'\u250C','boxdR':'\u2552','boxDr':'\u2553','boxDR':'\u2554','boxh':'\u2500','boxH':'\u2550','boxhd':'\u252C','boxhD':'\u2565','boxHd':'\u2564','boxHD':'\u2566','boxhu':'\u2534','boxhU':'\u2568','boxHu':'\u2567','boxHU':'\u2569','boxminus':'\u229F','boxplus':'\u229E','boxtimes':'\u22A0','boxul':'\u2518','boxuL':'\u255B','boxUl':'\u255C','boxUL':'\u255D','boxur':'\u2514','boxuR':'\u2558','boxUr':'\u2559','boxUR':'\u255A','boxv':'\u2502','boxV':'\u2551','boxvh':'\u253C','boxvH':'\u256A','boxVh':'\u256B','boxVH':'\u256C','boxvl':'\u2524','boxvL':'\u2561','boxVl':'\u2562','boxVL':'\u2563','boxvr':'\u251C','boxvR':'\u255E','boxVr':'\u255F','boxVR':'\u2560','bprime':'\u2035','breve':'\u02D8','Breve':'\u02D8','brvbar':'\xA6','bscr':'\uD835\uDCB7','Bscr':'\u212C','bsemi':'\u204F','bsim':'\u223D','bsime':'\u22CD','bsol':'\\','bsolb':'\u29C5','bsolhsub':'\u27C8','bull':'\u2022','bullet':'\u2022','bump':'\u224E','bumpe':'\u224F','bumpE':'\u2AAE','bumpeq':'\u224F','Bumpeq':'\u224E','cacute':'\u0107','Cacute':'\u0106','cap':'\u2229','Cap':'\u22D2','capand':'\u2A44','capbrcup':'\u2A49','capcap':'\u2A4B','capcup':'\u2A47','capdot':'\u2A40','CapitalDifferentialD':'\u2145','caps':'\u2229\uFE00','caret':'\u2041','caron':'\u02C7','Cayleys':'\u212D','ccaps':'\u2A4D','ccaron':'\u010D','Ccaron':'\u010C','ccedil':'\xE7','Ccedil':'\xC7','ccirc':'\u0109','Ccirc':'\u0108','Cconint':'\u2230','ccups':'\u2A4C','ccupssm':'\u2A50','cdot':'\u010B','Cdot':'\u010A','cedil':'\xB8','Cedilla':'\xB8','cemptyv':'\u29B2','cent':'\xA2','centerdot':'\xB7','CenterDot':'\xB7','cfr':'\uD835\uDD20','Cfr':'\u212D','chcy':'\u0447','CHcy':'\u0427','check':'\u2713','checkmark':'\u2713','chi':'\u03C7','Chi':'\u03A7','cir':'\u25CB','circ':'\u02C6','circeq':'\u2257','circlearrowleft':'\u21BA','circlearrowright':'\u21BB','circledast':'\u229B','circledcirc':'\u229A','circleddash':'\u229D','CircleDot':'\u2299','circledR':'\xAE','circledS':'\u24C8','CircleMinus':'\u2296','CirclePlus':'\u2295','CircleTimes':'\u2297','cire':'\u2257','cirE':'\u29C3','cirfnint':'\u2A10','cirmid':'\u2AEF','cirscir':'\u29C2','ClockwiseContourIntegral':'\u2232','CloseCurlyDoubleQuote':'\u201D','CloseCurlyQuote':'\u2019','clubs':'\u2663','clubsuit':'\u2663','colon':':','Colon':'\u2237','colone':'\u2254','Colone':'\u2A74','coloneq':'\u2254','comma':',','commat':'@','comp':'\u2201','compfn':'\u2218','complement':'\u2201','complexes':'\u2102','cong':'\u2245','congdot':'\u2A6D','Congruent':'\u2261','conint':'\u222E','Conint':'\u222F','ContourIntegral':'\u222E','copf':'\uD835\uDD54','Copf':'\u2102','coprod':'\u2210','Coproduct':'\u2210','copy':'\xA9','COPY':'\xA9','copysr':'\u2117','CounterClockwiseContourIntegral':'\u2233','crarr':'\u21B5','cross':'\u2717','Cross':'\u2A2F','cscr':'\uD835\uDCB8','Cscr':'\uD835\uDC9E','csub':'\u2ACF','csube':'\u2AD1','csup':'\u2AD0','csupe':'\u2AD2','ctdot':'\u22EF','cudarrl':'\u2938','cudarrr':'\u2935','cuepr':'\u22DE','cuesc':'\u22DF','cularr':'\u21B6','cularrp':'\u293D','cup':'\u222A','Cup':'\u22D3','cupbrcap':'\u2A48','cupcap':'\u2A46','CupCap':'\u224D','cupcup':'\u2A4A','cupdot':'\u228D','cupor':'\u2A45','cups':'\u222A\uFE00','curarr':'\u21B7','curarrm':'\u293C','curlyeqprec':'\u22DE','curlyeqsucc':'\u22DF','curlyvee':'\u22CE','curlywedge':'\u22CF','curren':'\xA4','curvearrowleft':'\u21B6','curvearrowright':'\u21B7','cuvee':'\u22CE','cuwed':'\u22CF','cwconint':'\u2232','cwint':'\u2231','cylcty':'\u232D','dagger':'\u2020','Dagger':'\u2021','daleth':'\u2138','darr':'\u2193','dArr':'\u21D3','Darr':'\u21A1','dash':'\u2010','dashv':'\u22A3','Dashv':'\u2AE4','dbkarow':'\u290F','dblac':'\u02DD','dcaron':'\u010F','Dcaron':'\u010E','dcy':'\u0434','Dcy':'\u0414','dd':'\u2146','DD':'\u2145','ddagger':'\u2021','ddarr':'\u21CA','DDotrahd':'\u2911','ddotseq':'\u2A77','deg':'\xB0','Del':'\u2207','delta':'\u03B4','Delta':'\u0394','demptyv':'\u29B1','dfisht':'\u297F','dfr':'\uD835\uDD21','Dfr':'\uD835\uDD07','dHar':'\u2965','dharl':'\u21C3','dharr':'\u21C2','DiacriticalAcute':'\xB4','DiacriticalDot':'\u02D9','DiacriticalDoubleAcute':'\u02DD','DiacriticalGrave':'`','DiacriticalTilde':'\u02DC','diam':'\u22C4','diamond':'\u22C4','Diamond':'\u22C4','diamondsuit':'\u2666','diams':'\u2666','die':'\xA8','DifferentialD':'\u2146','digamma':'\u03DD','disin':'\u22F2','div':'\xF7','divide':'\xF7','divideontimes':'\u22C7','divonx':'\u22C7','djcy':'\u0452','DJcy':'\u0402','dlcorn':'\u231E','dlcrop':'\u230D','dollar':'$','dopf':'\uD835\uDD55','Dopf':'\uD835\uDD3B','dot':'\u02D9','Dot':'\xA8','DotDot':'\u20DC','doteq':'\u2250','doteqdot':'\u2251','DotEqual':'\u2250','dotminus':'\u2238','dotplus':'\u2214','dotsquare':'\u22A1','doublebarwedge':'\u2306','DoubleContourIntegral':'\u222F','DoubleDot':'\xA8','DoubleDownArrow':'\u21D3','DoubleLeftArrow':'\u21D0','DoubleLeftRightArrow':'\u21D4','DoubleLeftTee':'\u2AE4','DoubleLongLeftArrow':'\u27F8','DoubleLongLeftRightArrow':'\u27FA','DoubleLongRightArrow':'\u27F9','DoubleRightArrow':'\u21D2','DoubleRightTee':'\u22A8','DoubleUpArrow':'\u21D1','DoubleUpDownArrow':'\u21D5','DoubleVerticalBar':'\u2225','downarrow':'\u2193','Downarrow':'\u21D3','DownArrow':'\u2193','DownArrowBar':'\u2913','DownArrowUpArrow':'\u21F5','DownBreve':'\u0311','downdownarrows':'\u21CA','downharpoonleft':'\u21C3','downharpoonright':'\u21C2','DownLeftRightVector':'\u2950','DownLeftTeeVector':'\u295E','DownLeftVector':'\u21BD','DownLeftVectorBar':'\u2956','DownRightTeeVector':'\u295F','DownRightVector':'\u21C1','DownRightVectorBar':'\u2957','DownTee':'\u22A4','DownTeeArrow':'\u21A7','drbkarow':'\u2910','drcorn':'\u231F','drcrop':'\u230C','dscr':'\uD835\uDCB9','Dscr':'\uD835\uDC9F','dscy':'\u0455','DScy':'\u0405','dsol':'\u29F6','dstrok':'\u0111','Dstrok':'\u0110','dtdot':'\u22F1','dtri':'\u25BF','dtrif':'\u25BE','duarr':'\u21F5','duhar':'\u296F','dwangle':'\u29A6','dzcy':'\u045F','DZcy':'\u040F','dzigrarr':'\u27FF','eacute':'\xE9','Eacute':'\xC9','easter':'\u2A6E','ecaron':'\u011B','Ecaron':'\u011A','ecir':'\u2256','ecirc':'\xEA','Ecirc':'\xCA','ecolon':'\u2255','ecy':'\u044D','Ecy':'\u042D','eDDot':'\u2A77','edot':'\u0117','eDot':'\u2251','Edot':'\u0116','ee':'\u2147','efDot':'\u2252','efr':'\uD835\uDD22','Efr':'\uD835\uDD08','eg':'\u2A9A','egrave':'\xE8','Egrave':'\xC8','egs':'\u2A96','egsdot':'\u2A98','el':'\u2A99','Element':'\u2208','elinters':'\u23E7','ell':'\u2113','els':'\u2A95','elsdot':'\u2A97','emacr':'\u0113','Emacr':'\u0112','empty':'\u2205','emptyset':'\u2205','EmptySmallSquare':'\u25FB','emptyv':'\u2205','EmptyVerySmallSquare':'\u25AB','emsp':'\u2003','emsp13':'\u2004','emsp14':'\u2005','eng':'\u014B','ENG':'\u014A','ensp':'\u2002','eogon':'\u0119','Eogon':'\u0118','eopf':'\uD835\uDD56','Eopf':'\uD835\uDD3C','epar':'\u22D5','eparsl':'\u29E3','eplus':'\u2A71','epsi':'\u03B5','epsilon':'\u03B5','Epsilon':'\u0395','epsiv':'\u03F5','eqcirc':'\u2256','eqcolon':'\u2255','eqsim':'\u2242','eqslantgtr':'\u2A96','eqslantless':'\u2A95','Equal':'\u2A75','equals':'=','EqualTilde':'\u2242','equest':'\u225F','Equilibrium':'\u21CC','equiv':'\u2261','equivDD':'\u2A78','eqvparsl':'\u29E5','erarr':'\u2971','erDot':'\u2253','escr':'\u212F','Escr':'\u2130','esdot':'\u2250','esim':'\u2242','Esim':'\u2A73','eta':'\u03B7','Eta':'\u0397','eth':'\xF0','ETH':'\xD0','euml':'\xEB','Euml':'\xCB','euro':'\u20AC','excl':'!','exist':'\u2203','Exists':'\u2203','expectation':'\u2130','exponentiale':'\u2147','ExponentialE':'\u2147','fallingdotseq':'\u2252','fcy':'\u0444','Fcy':'\u0424','female':'\u2640','ffilig':'\uFB03','fflig':'\uFB00','ffllig':'\uFB04','ffr':'\uD835\uDD23','Ffr':'\uD835\uDD09','filig':'\uFB01','FilledSmallSquare':'\u25FC','FilledVerySmallSquare':'\u25AA','fjlig':'fj','flat':'\u266D','fllig':'\uFB02','fltns':'\u25B1','fnof':'\u0192','fopf':'\uD835\uDD57','Fopf':'\uD835\uDD3D','forall':'\u2200','ForAll':'\u2200','fork':'\u22D4','forkv':'\u2AD9','Fouriertrf':'\u2131','fpartint':'\u2A0D','frac12':'\xBD','frac13':'\u2153','frac14':'\xBC','frac15':'\u2155','frac16':'\u2159','frac18':'\u215B','frac23':'\u2154','frac25':'\u2156','frac34':'\xBE','frac35':'\u2157','frac38':'\u215C','frac45':'\u2158','frac56':'\u215A','frac58':'\u215D','frac78':'\u215E','frasl':'\u2044','frown':'\u2322','fscr':'\uD835\uDCBB','Fscr':'\u2131','gacute':'\u01F5','gamma':'\u03B3','Gamma':'\u0393','gammad':'\u03DD','Gammad':'\u03DC','gap':'\u2A86','gbreve':'\u011F','Gbreve':'\u011E','Gcedil':'\u0122','gcirc':'\u011D','Gcirc':'\u011C','gcy':'\u0433','Gcy':'\u0413','gdot':'\u0121','Gdot':'\u0120','ge':'\u2265','gE':'\u2267','gel':'\u22DB','gEl':'\u2A8C','geq':'\u2265','geqq':'\u2267','geqslant':'\u2A7E','ges':'\u2A7E','gescc':'\u2AA9','gesdot':'\u2A80','gesdoto':'\u2A82','gesdotol':'\u2A84','gesl':'\u22DB\uFE00','gesles':'\u2A94','gfr':'\uD835\uDD24','Gfr':'\uD835\uDD0A','gg':'\u226B','Gg':'\u22D9','ggg':'\u22D9','gimel':'\u2137','gjcy':'\u0453','GJcy':'\u0403','gl':'\u2277','gla':'\u2AA5','glE':'\u2A92','glj':'\u2AA4','gnap':'\u2A8A','gnapprox':'\u2A8A','gne':'\u2A88','gnE':'\u2269','gneq':'\u2A88','gneqq':'\u2269','gnsim':'\u22E7','gopf':'\uD835\uDD58','Gopf':'\uD835\uDD3E','grave':'`','GreaterEqual':'\u2265','GreaterEqualLess':'\u22DB','GreaterFullEqual':'\u2267','GreaterGreater':'\u2AA2','GreaterLess':'\u2277','GreaterSlantEqual':'\u2A7E','GreaterTilde':'\u2273','gscr':'\u210A','Gscr':'\uD835\uDCA2','gsim':'\u2273','gsime':'\u2A8E','gsiml':'\u2A90','gt':'>','Gt':'\u226B','GT':'>','gtcc':'\u2AA7','gtcir':'\u2A7A','gtdot':'\u22D7','gtlPar':'\u2995','gtquest':'\u2A7C','gtrapprox':'\u2A86','gtrarr':'\u2978','gtrdot':'\u22D7','gtreqless':'\u22DB','gtreqqless':'\u2A8C','gtrless':'\u2277','gtrsim':'\u2273','gvertneqq':'\u2269\uFE00','gvnE':'\u2269\uFE00','Hacek':'\u02C7','hairsp':'\u200A','half':'\xBD','hamilt':'\u210B','hardcy':'\u044A','HARDcy':'\u042A','harr':'\u2194','hArr':'\u21D4','harrcir':'\u2948','harrw':'\u21AD','Hat':'^','hbar':'\u210F','hcirc':'\u0125','Hcirc':'\u0124','hearts':'\u2665','heartsuit':'\u2665','hellip':'\u2026','hercon':'\u22B9','hfr':'\uD835\uDD25','Hfr':'\u210C','HilbertSpace':'\u210B','hksearow':'\u2925','hkswarow':'\u2926','hoarr':'\u21FF','homtht':'\u223B','hookleftarrow':'\u21A9','hookrightarrow':'\u21AA','hopf':'\uD835\uDD59','Hopf':'\u210D','horbar':'\u2015','HorizontalLine':'\u2500','hscr':'\uD835\uDCBD','Hscr':'\u210B','hslash':'\u210F','hstrok':'\u0127','Hstrok':'\u0126','HumpDownHump':'\u224E','HumpEqual':'\u224F','hybull':'\u2043','hyphen':'\u2010','iacute':'\xED','Iacute':'\xCD','ic':'\u2063','icirc':'\xEE','Icirc':'\xCE','icy':'\u0438','Icy':'\u0418','Idot':'\u0130','iecy':'\u0435','IEcy':'\u0415','iexcl':'\xA1','iff':'\u21D4','ifr':'\uD835\uDD26','Ifr':'\u2111','igrave':'\xEC','Igrave':'\xCC','ii':'\u2148','iiiint':'\u2A0C','iiint':'\u222D','iinfin':'\u29DC','iiota':'\u2129','ijlig':'\u0133','IJlig':'\u0132','Im':'\u2111','imacr':'\u012B','Imacr':'\u012A','image':'\u2111','ImaginaryI':'\u2148','imagline':'\u2110','imagpart':'\u2111','imath':'\u0131','imof':'\u22B7','imped':'\u01B5','Implies':'\u21D2','in':'\u2208','incare':'\u2105','infin':'\u221E','infintie':'\u29DD','inodot':'\u0131','int':'\u222B','Int':'\u222C','intcal':'\u22BA','integers':'\u2124','Integral':'\u222B','intercal':'\u22BA','Intersection':'\u22C2','intlarhk':'\u2A17','intprod':'\u2A3C','InvisibleComma':'\u2063','InvisibleTimes':'\u2062','iocy':'\u0451','IOcy':'\u0401','iogon':'\u012F','Iogon':'\u012E','iopf':'\uD835\uDD5A','Iopf':'\uD835\uDD40','iota':'\u03B9','Iota':'\u0399','iprod':'\u2A3C','iquest':'\xBF','iscr':'\uD835\uDCBE','Iscr':'\u2110','isin':'\u2208','isindot':'\u22F5','isinE':'\u22F9','isins':'\u22F4','isinsv':'\u22F3','isinv':'\u2208','it':'\u2062','itilde':'\u0129','Itilde':'\u0128','iukcy':'\u0456','Iukcy':'\u0406','iuml':'\xEF','Iuml':'\xCF','jcirc':'\u0135','Jcirc':'\u0134','jcy':'\u0439','Jcy':'\u0419','jfr':'\uD835\uDD27','Jfr':'\uD835\uDD0D','jmath':'\u0237','jopf':'\uD835\uDD5B','Jopf':'\uD835\uDD41','jscr':'\uD835\uDCBF','Jscr':'\uD835\uDCA5','jsercy':'\u0458','Jsercy':'\u0408','jukcy':'\u0454','Jukcy':'\u0404','kappa':'\u03BA','Kappa':'\u039A','kappav':'\u03F0','kcedil':'\u0137','Kcedil':'\u0136','kcy':'\u043A','Kcy':'\u041A','kfr':'\uD835\uDD28','Kfr':'\uD835\uDD0E','kgreen':'\u0138','khcy':'\u0445','KHcy':'\u0425','kjcy':'\u045C','KJcy':'\u040C','kopf':'\uD835\uDD5C','Kopf':'\uD835\uDD42','kscr':'\uD835\uDCC0','Kscr':'\uD835\uDCA6','lAarr':'\u21DA','lacute':'\u013A','Lacute':'\u0139','laemptyv':'\u29B4','lagran':'\u2112','lambda':'\u03BB','Lambda':'\u039B','lang':'\u27E8','Lang':'\u27EA','langd':'\u2991','langle':'\u27E8','lap':'\u2A85','Laplacetrf':'\u2112','laquo':'\xAB','larr':'\u2190','lArr':'\u21D0','Larr':'\u219E','larrb':'\u21E4','larrbfs':'\u291F','larrfs':'\u291D','larrhk':'\u21A9','larrlp':'\u21AB','larrpl':'\u2939','larrsim':'\u2973','larrtl':'\u21A2','lat':'\u2AAB','latail':'\u2919','lAtail':'\u291B','late':'\u2AAD','lates':'\u2AAD\uFE00','lbarr':'\u290C','lBarr':'\u290E','lbbrk':'\u2772','lbrace':'{','lbrack':'[','lbrke':'\u298B','lbrksld':'\u298F','lbrkslu':'\u298D','lcaron':'\u013E','Lcaron':'\u013D','lcedil':'\u013C','Lcedil':'\u013B','lceil':'\u2308','lcub':'{','lcy':'\u043B','Lcy':'\u041B','ldca':'\u2936','ldquo':'\u201C','ldquor':'\u201E','ldrdhar':'\u2967','ldrushar':'\u294B','ldsh':'\u21B2','le':'\u2264','lE':'\u2266','LeftAngleBracket':'\u27E8','leftarrow':'\u2190','Leftarrow':'\u21D0','LeftArrow':'\u2190','LeftArrowBar':'\u21E4','LeftArrowRightArrow':'\u21C6','leftarrowtail':'\u21A2','LeftCeiling':'\u2308','LeftDoubleBracket':'\u27E6','LeftDownTeeVector':'\u2961','LeftDownVector':'\u21C3','LeftDownVectorBar':'\u2959','LeftFloor':'\u230A','leftharpoondown':'\u21BD','leftharpoonup':'\u21BC','leftleftarrows':'\u21C7','leftrightarrow':'\u2194','Leftrightarrow':'\u21D4','LeftRightArrow':'\u2194','leftrightarrows':'\u21C6','leftrightharpoons':'\u21CB','leftrightsquigarrow':'\u21AD','LeftRightVector':'\u294E','LeftTee':'\u22A3','LeftTeeArrow':'\u21A4','LeftTeeVector':'\u295A','leftthreetimes':'\u22CB','LeftTriangle':'\u22B2','LeftTriangleBar':'\u29CF','LeftTriangleEqual':'\u22B4','LeftUpDownVector':'\u2951','LeftUpTeeVector':'\u2960','LeftUpVector':'\u21BF','LeftUpVectorBar':'\u2958','LeftVector':'\u21BC','LeftVectorBar':'\u2952','leg':'\u22DA','lEg':'\u2A8B','leq':'\u2264','leqq':'\u2266','leqslant':'\u2A7D','les':'\u2A7D','lescc':'\u2AA8','lesdot':'\u2A7F','lesdoto':'\u2A81','lesdotor':'\u2A83','lesg':'\u22DA\uFE00','lesges':'\u2A93','lessapprox':'\u2A85','lessdot':'\u22D6','lesseqgtr':'\u22DA','lesseqqgtr':'\u2A8B','LessEqualGreater':'\u22DA','LessFullEqual':'\u2266','LessGreater':'\u2276','lessgtr':'\u2276','LessLess':'\u2AA1','lesssim':'\u2272','LessSlantEqual':'\u2A7D','LessTilde':'\u2272','lfisht':'\u297C','lfloor':'\u230A','lfr':'\uD835\uDD29','Lfr':'\uD835\uDD0F','lg':'\u2276','lgE':'\u2A91','lHar':'\u2962','lhard':'\u21BD','lharu':'\u21BC','lharul':'\u296A','lhblk':'\u2584','ljcy':'\u0459','LJcy':'\u0409','ll':'\u226A','Ll':'\u22D8','llarr':'\u21C7','llcorner':'\u231E','Lleftarrow':'\u21DA','llhard':'\u296B','lltri':'\u25FA','lmidot':'\u0140','Lmidot':'\u013F','lmoust':'\u23B0','lmoustache':'\u23B0','lnap':'\u2A89','lnapprox':'\u2A89','lne':'\u2A87','lnE':'\u2268','lneq':'\u2A87','lneqq':'\u2268','lnsim':'\u22E6','loang':'\u27EC','loarr':'\u21FD','lobrk':'\u27E6','longleftarrow':'\u27F5','Longleftarrow':'\u27F8','LongLeftArrow':'\u27F5','longleftrightarrow':'\u27F7','Longleftrightarrow':'\u27FA','LongLeftRightArrow':'\u27F7','longmapsto':'\u27FC','longrightarrow':'\u27F6','Longrightarrow':'\u27F9','LongRightArrow':'\u27F6','looparrowleft':'\u21AB','looparrowright':'\u21AC','lopar':'\u2985','lopf':'\uD835\uDD5D','Lopf':'\uD835\uDD43','loplus':'\u2A2D','lotimes':'\u2A34','lowast':'\u2217','lowbar':'_','LowerLeftArrow':'\u2199','LowerRightArrow':'\u2198','loz':'\u25CA','lozenge':'\u25CA','lozf':'\u29EB','lpar':'(','lparlt':'\u2993','lrarr':'\u21C6','lrcorner':'\u231F','lrhar':'\u21CB','lrhard':'\u296D','lrm':'\u200E','lrtri':'\u22BF','lsaquo':'\u2039','lscr':'\uD835\uDCC1','Lscr':'\u2112','lsh':'\u21B0','Lsh':'\u21B0','lsim':'\u2272','lsime':'\u2A8D','lsimg':'\u2A8F','lsqb':'[','lsquo':'\u2018','lsquor':'\u201A','lstrok':'\u0142','Lstrok':'\u0141','lt':'<','Lt':'\u226A','LT':'<','ltcc':'\u2AA6','ltcir':'\u2A79','ltdot':'\u22D6','lthree':'\u22CB','ltimes':'\u22C9','ltlarr':'\u2976','ltquest':'\u2A7B','ltri':'\u25C3','ltrie':'\u22B4','ltrif':'\u25C2','ltrPar':'\u2996','lurdshar':'\u294A','luruhar':'\u2966','lvertneqq':'\u2268\uFE00','lvnE':'\u2268\uFE00','macr':'\xAF','male':'\u2642','malt':'\u2720','maltese':'\u2720','map':'\u21A6','Map':'\u2905','mapsto':'\u21A6','mapstodown':'\u21A7','mapstoleft':'\u21A4','mapstoup':'\u21A5','marker':'\u25AE','mcomma':'\u2A29','mcy':'\u043C','Mcy':'\u041C','mdash':'\u2014','mDDot':'\u223A','measuredangle':'\u2221','MediumSpace':'\u205F','Mellintrf':'\u2133','mfr':'\uD835\uDD2A','Mfr':'\uD835\uDD10','mho':'\u2127','micro':'\xB5','mid':'\u2223','midast':'*','midcir':'\u2AF0','middot':'\xB7','minus':'\u2212','minusb':'\u229F','minusd':'\u2238','minusdu':'\u2A2A','MinusPlus':'\u2213','mlcp':'\u2ADB','mldr':'\u2026','mnplus':'\u2213','models':'\u22A7','mopf':'\uD835\uDD5E','Mopf':'\uD835\uDD44','mp':'\u2213','mscr':'\uD835\uDCC2','Mscr':'\u2133','mstpos':'\u223E','mu':'\u03BC','Mu':'\u039C','multimap':'\u22B8','mumap':'\u22B8','nabla':'\u2207','nacute':'\u0144','Nacute':'\u0143','nang':'\u2220\u20D2','nap':'\u2249','napE':'\u2A70\u0338','napid':'\u224B\u0338','napos':'\u0149','napprox':'\u2249','natur':'\u266E','natural':'\u266E','naturals':'\u2115','nbsp':'\xA0','nbump':'\u224E\u0338','nbumpe':'\u224F\u0338','ncap':'\u2A43','ncaron':'\u0148','Ncaron':'\u0147','ncedil':'\u0146','Ncedil':'\u0145','ncong':'\u2247','ncongdot':'\u2A6D\u0338','ncup':'\u2A42','ncy':'\u043D','Ncy':'\u041D','ndash':'\u2013','ne':'\u2260','nearhk':'\u2924','nearr':'\u2197','neArr':'\u21D7','nearrow':'\u2197','nedot':'\u2250\u0338','NegativeMediumSpace':'\u200B','NegativeThickSpace':'\u200B','NegativeThinSpace':'\u200B','NegativeVeryThinSpace':'\u200B','nequiv':'\u2262','nesear':'\u2928','nesim':'\u2242\u0338','NestedGreaterGreater':'\u226B','NestedLessLess':'\u226A','NewLine':'\n','nexist':'\u2204','nexists':'\u2204','nfr':'\uD835\uDD2B','Nfr':'\uD835\uDD11','nge':'\u2271','ngE':'\u2267\u0338','ngeq':'\u2271','ngeqq':'\u2267\u0338','ngeqslant':'\u2A7E\u0338','nges':'\u2A7E\u0338','nGg':'\u22D9\u0338','ngsim':'\u2275','ngt':'\u226F','nGt':'\u226B\u20D2','ngtr':'\u226F','nGtv':'\u226B\u0338','nharr':'\u21AE','nhArr':'\u21CE','nhpar':'\u2AF2','ni':'\u220B','nis':'\u22FC','nisd':'\u22FA','niv':'\u220B','njcy':'\u045A','NJcy':'\u040A','nlarr':'\u219A','nlArr':'\u21CD','nldr':'\u2025','nle':'\u2270','nlE':'\u2266\u0338','nleftarrow':'\u219A','nLeftarrow':'\u21CD','nleftrightarrow':'\u21AE','nLeftrightarrow':'\u21CE','nleq':'\u2270','nleqq':'\u2266\u0338','nleqslant':'\u2A7D\u0338','nles':'\u2A7D\u0338','nless':'\u226E','nLl':'\u22D8\u0338','nlsim':'\u2274','nlt':'\u226E','nLt':'\u226A\u20D2','nltri':'\u22EA','nltrie':'\u22EC','nLtv':'\u226A\u0338','nmid':'\u2224','NoBreak':'\u2060','NonBreakingSpace':'\xA0','nopf':'\uD835\uDD5F','Nopf':'\u2115','not':'\xAC','Not':'\u2AEC','NotCongruent':'\u2262','NotCupCap':'\u226D','NotDoubleVerticalBar':'\u2226','NotElement':'\u2209','NotEqual':'\u2260','NotEqualTilde':'\u2242\u0338','NotExists':'\u2204','NotGreater':'\u226F','NotGreaterEqual':'\u2271','NotGreaterFullEqual':'\u2267\u0338','NotGreaterGreater':'\u226B\u0338','NotGreaterLess':'\u2279','NotGreaterSlantEqual':'\u2A7E\u0338','NotGreaterTilde':'\u2275','NotHumpDownHump':'\u224E\u0338','NotHumpEqual':'\u224F\u0338','notin':'\u2209','notindot':'\u22F5\u0338','notinE':'\u22F9\u0338','notinva':'\u2209','notinvb':'\u22F7','notinvc':'\u22F6','NotLeftTriangle':'\u22EA','NotLeftTriangleBar':'\u29CF\u0338','NotLeftTriangleEqual':'\u22EC','NotLess':'\u226E','NotLessEqual':'\u2270','NotLessGreater':'\u2278','NotLessLess':'\u226A\u0338','NotLessSlantEqual':'\u2A7D\u0338','NotLessTilde':'\u2274','NotNestedGreaterGreater':'\u2AA2\u0338','NotNestedLessLess':'\u2AA1\u0338','notni':'\u220C','notniva':'\u220C','notnivb':'\u22FE','notnivc':'\u22FD','NotPrecedes':'\u2280','NotPrecedesEqual':'\u2AAF\u0338','NotPrecedesSlantEqual':'\u22E0','NotReverseElement':'\u220C','NotRightTriangle':'\u22EB','NotRightTriangleBar':'\u29D0\u0338','NotRightTriangleEqual':'\u22ED','NotSquareSubset':'\u228F\u0338','NotSquareSubsetEqual':'\u22E2','NotSquareSuperset':'\u2290\u0338','NotSquareSupersetEqual':'\u22E3','NotSubset':'\u2282\u20D2','NotSubsetEqual':'\u2288','NotSucceeds':'\u2281','NotSucceedsEqual':'\u2AB0\u0338','NotSucceedsSlantEqual':'\u22E1','NotSucceedsTilde':'\u227F\u0338','NotSuperset':'\u2283\u20D2','NotSupersetEqual':'\u2289','NotTilde':'\u2241','NotTildeEqual':'\u2244','NotTildeFullEqual':'\u2247','NotTildeTilde':'\u2249','NotVerticalBar':'\u2224','npar':'\u2226','nparallel':'\u2226','nparsl':'\u2AFD\u20E5','npart':'\u2202\u0338','npolint':'\u2A14','npr':'\u2280','nprcue':'\u22E0','npre':'\u2AAF\u0338','nprec':'\u2280','npreceq':'\u2AAF\u0338','nrarr':'\u219B','nrArr':'\u21CF','nrarrc':'\u2933\u0338','nrarrw':'\u219D\u0338','nrightarrow':'\u219B','nRightarrow':'\u21CF','nrtri':'\u22EB','nrtrie':'\u22ED','nsc':'\u2281','nsccue':'\u22E1','nsce':'\u2AB0\u0338','nscr':'\uD835\uDCC3','Nscr':'\uD835\uDCA9','nshortmid':'\u2224','nshortparallel':'\u2226','nsim':'\u2241','nsime':'\u2244','nsimeq':'\u2244','nsmid':'\u2224','nspar':'\u2226','nsqsube':'\u22E2','nsqsupe':'\u22E3','nsub':'\u2284','nsube':'\u2288','nsubE':'\u2AC5\u0338','nsubset':'\u2282\u20D2','nsubseteq':'\u2288','nsubseteqq':'\u2AC5\u0338','nsucc':'\u2281','nsucceq':'\u2AB0\u0338','nsup':'\u2285','nsupe':'\u2289','nsupE':'\u2AC6\u0338','nsupset':'\u2283\u20D2','nsupseteq':'\u2289','nsupseteqq':'\u2AC6\u0338','ntgl':'\u2279','ntilde':'\xF1','Ntilde':'\xD1','ntlg':'\u2278','ntriangleleft':'\u22EA','ntrianglelefteq':'\u22EC','ntriangleright':'\u22EB','ntrianglerighteq':'\u22ED','nu':'\u03BD','Nu':'\u039D','num':'#','numero':'\u2116','numsp':'\u2007','nvap':'\u224D\u20D2','nvdash':'\u22AC','nvDash':'\u22AD','nVdash':'\u22AE','nVDash':'\u22AF','nvge':'\u2265\u20D2','nvgt':'>\u20D2','nvHarr':'\u2904','nvinfin':'\u29DE','nvlArr':'\u2902','nvle':'\u2264\u20D2','nvlt':'<\u20D2','nvltrie':'\u22B4\u20D2','nvrArr':'\u2903','nvrtrie':'\u22B5\u20D2','nvsim':'\u223C\u20D2','nwarhk':'\u2923','nwarr':'\u2196','nwArr':'\u21D6','nwarrow':'\u2196','nwnear':'\u2927','oacute':'\xF3','Oacute':'\xD3','oast':'\u229B','ocir':'\u229A','ocirc':'\xF4','Ocirc':'\xD4','ocy':'\u043E','Ocy':'\u041E','odash':'\u229D','odblac':'\u0151','Odblac':'\u0150','odiv':'\u2A38','odot':'\u2299','odsold':'\u29BC','oelig':'\u0153','OElig':'\u0152','ofcir':'\u29BF','ofr':'\uD835\uDD2C','Ofr':'\uD835\uDD12','ogon':'\u02DB','ograve':'\xF2','Ograve':'\xD2','ogt':'\u29C1','ohbar':'\u29B5','ohm':'\u03A9','oint':'\u222E','olarr':'\u21BA','olcir':'\u29BE','olcross':'\u29BB','oline':'\u203E','olt':'\u29C0','omacr':'\u014D','Omacr':'\u014C','omega':'\u03C9','Omega':'\u03A9','omicron':'\u03BF','Omicron':'\u039F','omid':'\u29B6','ominus':'\u2296','oopf':'\uD835\uDD60','Oopf':'\uD835\uDD46','opar':'\u29B7','OpenCurlyDoubleQuote':'\u201C','OpenCurlyQuote':'\u2018','operp':'\u29B9','oplus':'\u2295','or':'\u2228','Or':'\u2A54','orarr':'\u21BB','ord':'\u2A5D','order':'\u2134','orderof':'\u2134','ordf':'\xAA','ordm':'\xBA','origof':'\u22B6','oror':'\u2A56','orslope':'\u2A57','orv':'\u2A5B','oS':'\u24C8','oscr':'\u2134','Oscr':'\uD835\uDCAA','oslash':'\xF8','Oslash':'\xD8','osol':'\u2298','otilde':'\xF5','Otilde':'\xD5','otimes':'\u2297','Otimes':'\u2A37','otimesas':'\u2A36','ouml':'\xF6','Ouml':'\xD6','ovbar':'\u233D','OverBar':'\u203E','OverBrace':'\u23DE','OverBracket':'\u23B4','OverParenthesis':'\u23DC','par':'\u2225','para':'\xB6','parallel':'\u2225','parsim':'\u2AF3','parsl':'\u2AFD','part':'\u2202','PartialD':'\u2202','pcy':'\u043F','Pcy':'\u041F','percnt':'%','period':'.','permil':'\u2030','perp':'\u22A5','pertenk':'\u2031','pfr':'\uD835\uDD2D','Pfr':'\uD835\uDD13','phi':'\u03C6','Phi':'\u03A6','phiv':'\u03D5','phmmat':'\u2133','phone':'\u260E','pi':'\u03C0','Pi':'\u03A0','pitchfork':'\u22D4','piv':'\u03D6','planck':'\u210F','planckh':'\u210E','plankv':'\u210F','plus':'+','plusacir':'\u2A23','plusb':'\u229E','pluscir':'\u2A22','plusdo':'\u2214','plusdu':'\u2A25','pluse':'\u2A72','PlusMinus':'\xB1','plusmn':'\xB1','plussim':'\u2A26','plustwo':'\u2A27','pm':'\xB1','Poincareplane':'\u210C','pointint':'\u2A15','popf':'\uD835\uDD61','Popf':'\u2119','pound':'\xA3','pr':'\u227A','Pr':'\u2ABB','prap':'\u2AB7','prcue':'\u227C','pre':'\u2AAF','prE':'\u2AB3','prec':'\u227A','precapprox':'\u2AB7','preccurlyeq':'\u227C','Precedes':'\u227A','PrecedesEqual':'\u2AAF','PrecedesSlantEqual':'\u227C','PrecedesTilde':'\u227E','preceq':'\u2AAF','precnapprox':'\u2AB9','precneqq':'\u2AB5','precnsim':'\u22E8','precsim':'\u227E','prime':'\u2032','Prime':'\u2033','primes':'\u2119','prnap':'\u2AB9','prnE':'\u2AB5','prnsim':'\u22E8','prod':'\u220F','Product':'\u220F','profalar':'\u232E','profline':'\u2312','profsurf':'\u2313','prop':'\u221D','Proportion':'\u2237','Proportional':'\u221D','propto':'\u221D','prsim':'\u227E','prurel':'\u22B0','pscr':'\uD835\uDCC5','Pscr':'\uD835\uDCAB','psi':'\u03C8','Psi':'\u03A8','puncsp':'\u2008','qfr':'\uD835\uDD2E','Qfr':'\uD835\uDD14','qint':'\u2A0C','qopf':'\uD835\uDD62','Qopf':'\u211A','qprime':'\u2057','qscr':'\uD835\uDCC6','Qscr':'\uD835\uDCAC','quaternions':'\u210D','quatint':'\u2A16','quest':'?','questeq':'\u225F','quot':'"','QUOT':'"','rAarr':'\u21DB','race':'\u223D\u0331','racute':'\u0155','Racute':'\u0154','radic':'\u221A','raemptyv':'\u29B3','rang':'\u27E9','Rang':'\u27EB','rangd':'\u2992','range':'\u29A5','rangle':'\u27E9','raquo':'\xBB','rarr':'\u2192','rArr':'\u21D2','Rarr':'\u21A0','rarrap':'\u2975','rarrb':'\u21E5','rarrbfs':'\u2920','rarrc':'\u2933','rarrfs':'\u291E','rarrhk':'\u21AA','rarrlp':'\u21AC','rarrpl':'\u2945','rarrsim':'\u2974','rarrtl':'\u21A3','Rarrtl':'\u2916','rarrw':'\u219D','ratail':'\u291A','rAtail':'\u291C','ratio':'\u2236','rationals':'\u211A','rbarr':'\u290D','rBarr':'\u290F','RBarr':'\u2910','rbbrk':'\u2773','rbrace':'}','rbrack':']','rbrke':'\u298C','rbrksld':'\u298E','rbrkslu':'\u2990','rcaron':'\u0159','Rcaron':'\u0158','rcedil':'\u0157','Rcedil':'\u0156','rceil':'\u2309','rcub':'}','rcy':'\u0440','Rcy':'\u0420','rdca':'\u2937','rdldhar':'\u2969','rdquo':'\u201D','rdquor':'\u201D','rdsh':'\u21B3','Re':'\u211C','real':'\u211C','realine':'\u211B','realpart':'\u211C','reals':'\u211D','rect':'\u25AD','reg':'\xAE','REG':'\xAE','ReverseElement':'\u220B','ReverseEquilibrium':'\u21CB','ReverseUpEquilibrium':'\u296F','rfisht':'\u297D','rfloor':'\u230B','rfr':'\uD835\uDD2F','Rfr':'\u211C','rHar':'\u2964','rhard':'\u21C1','rharu':'\u21C0','rharul':'\u296C','rho':'\u03C1','Rho':'\u03A1','rhov':'\u03F1','RightAngleBracket':'\u27E9','rightarrow':'\u2192','Rightarrow':'\u21D2','RightArrow':'\u2192','RightArrowBar':'\u21E5','RightArrowLeftArrow':'\u21C4','rightarrowtail':'\u21A3','RightCeiling':'\u2309','RightDoubleBracket':'\u27E7','RightDownTeeVector':'\u295D','RightDownVector':'\u21C2','RightDownVectorBar':'\u2955','RightFloor':'\u230B','rightharpoondown':'\u21C1','rightharpoonup':'\u21C0','rightleftarrows':'\u21C4','rightleftharpoons':'\u21CC','rightrightarrows':'\u21C9','rightsquigarrow':'\u219D','RightTee':'\u22A2','RightTeeArrow':'\u21A6','RightTeeVector':'\u295B','rightthreetimes':'\u22CC','RightTriangle':'\u22B3','RightTriangleBar':'\u29D0','RightTriangleEqual':'\u22B5','RightUpDownVector':'\u294F','RightUpTeeVector':'\u295C','RightUpVector':'\u21BE','RightUpVectorBar':'\u2954','RightVector':'\u21C0','RightVectorBar':'\u2953','ring':'\u02DA','risingdotseq':'\u2253','rlarr':'\u21C4','rlhar':'\u21CC','rlm':'\u200F','rmoust':'\u23B1','rmoustache':'\u23B1','rnmid':'\u2AEE','roang':'\u27ED','roarr':'\u21FE','robrk':'\u27E7','ropar':'\u2986','ropf':'\uD835\uDD63','Ropf':'\u211D','roplus':'\u2A2E','rotimes':'\u2A35','RoundImplies':'\u2970','rpar':')','rpargt':'\u2994','rppolint':'\u2A12','rrarr':'\u21C9','Rrightarrow':'\u21DB','rsaquo':'\u203A','rscr':'\uD835\uDCC7','Rscr':'\u211B','rsh':'\u21B1','Rsh':'\u21B1','rsqb':']','rsquo':'\u2019','rsquor':'\u2019','rthree':'\u22CC','rtimes':'\u22CA','rtri':'\u25B9','rtrie':'\u22B5','rtrif':'\u25B8','rtriltri':'\u29CE','RuleDelayed':'\u29F4','ruluhar':'\u2968','rx':'\u211E','sacute':'\u015B','Sacute':'\u015A','sbquo':'\u201A','sc':'\u227B','Sc':'\u2ABC','scap':'\u2AB8','scaron':'\u0161','Scaron':'\u0160','sccue':'\u227D','sce':'\u2AB0','scE':'\u2AB4','scedil':'\u015F','Scedil':'\u015E','scirc':'\u015D','Scirc':'\u015C','scnap':'\u2ABA','scnE':'\u2AB6','scnsim':'\u22E9','scpolint':'\u2A13','scsim':'\u227F','scy':'\u0441','Scy':'\u0421','sdot':'\u22C5','sdotb':'\u22A1','sdote':'\u2A66','searhk':'\u2925','searr':'\u2198','seArr':'\u21D8','searrow':'\u2198','sect':'\xA7','semi':';','seswar':'\u2929','setminus':'\u2216','setmn':'\u2216','sext':'\u2736','sfr':'\uD835\uDD30','Sfr':'\uD835\uDD16','sfrown':'\u2322','sharp':'\u266F','shchcy':'\u0449','SHCHcy':'\u0429','shcy':'\u0448','SHcy':'\u0428','ShortDownArrow':'\u2193','ShortLeftArrow':'\u2190','shortmid':'\u2223','shortparallel':'\u2225','ShortRightArrow':'\u2192','ShortUpArrow':'\u2191','shy':'\xAD','sigma':'\u03C3','Sigma':'\u03A3','sigmaf':'\u03C2','sigmav':'\u03C2','sim':'\u223C','simdot':'\u2A6A','sime':'\u2243','simeq':'\u2243','simg':'\u2A9E','simgE':'\u2AA0','siml':'\u2A9D','simlE':'\u2A9F','simne':'\u2246','simplus':'\u2A24','simrarr':'\u2972','slarr':'\u2190','SmallCircle':'\u2218','smallsetminus':'\u2216','smashp':'\u2A33','smeparsl':'\u29E4','smid':'\u2223','smile':'\u2323','smt':'\u2AAA','smte':'\u2AAC','smtes':'\u2AAC\uFE00','softcy':'\u044C','SOFTcy':'\u042C','sol':'/','solb':'\u29C4','solbar':'\u233F','sopf':'\uD835\uDD64','Sopf':'\uD835\uDD4A','spades':'\u2660','spadesuit':'\u2660','spar':'\u2225','sqcap':'\u2293','sqcaps':'\u2293\uFE00','sqcup':'\u2294','sqcups':'\u2294\uFE00','Sqrt':'\u221A','sqsub':'\u228F','sqsube':'\u2291','sqsubset':'\u228F','sqsubseteq':'\u2291','sqsup':'\u2290','sqsupe':'\u2292','sqsupset':'\u2290','sqsupseteq':'\u2292','squ':'\u25A1','square':'\u25A1','Square':'\u25A1','SquareIntersection':'\u2293','SquareSubset':'\u228F','SquareSubsetEqual':'\u2291','SquareSuperset':'\u2290','SquareSupersetEqual':'\u2292','SquareUnion':'\u2294','squarf':'\u25AA','squf':'\u25AA','srarr':'\u2192','sscr':'\uD835\uDCC8','Sscr':'\uD835\uDCAE','ssetmn':'\u2216','ssmile':'\u2323','sstarf':'\u22C6','star':'\u2606','Star':'\u22C6','starf':'\u2605','straightepsilon':'\u03F5','straightphi':'\u03D5','strns':'\xAF','sub':'\u2282','Sub':'\u22D0','subdot':'\u2ABD','sube':'\u2286','subE':'\u2AC5','subedot':'\u2AC3','submult':'\u2AC1','subne':'\u228A','subnE':'\u2ACB','subplus':'\u2ABF','subrarr':'\u2979','subset':'\u2282','Subset':'\u22D0','subseteq':'\u2286','subseteqq':'\u2AC5','SubsetEqual':'\u2286','subsetneq':'\u228A','subsetneqq':'\u2ACB','subsim':'\u2AC7','subsub':'\u2AD5','subsup':'\u2AD3','succ':'\u227B','succapprox':'\u2AB8','succcurlyeq':'\u227D','Succeeds':'\u227B','SucceedsEqual':'\u2AB0','SucceedsSlantEqual':'\u227D','SucceedsTilde':'\u227F','succeq':'\u2AB0','succnapprox':'\u2ABA','succneqq':'\u2AB6','succnsim':'\u22E9','succsim':'\u227F','SuchThat':'\u220B','sum':'\u2211','Sum':'\u2211','sung':'\u266A','sup':'\u2283','Sup':'\u22D1','sup1':'\xB9','sup2':'\xB2','sup3':'\xB3','supdot':'\u2ABE','supdsub':'\u2AD8','supe':'\u2287','supE':'\u2AC6','supedot':'\u2AC4','Superset':'\u2283','SupersetEqual':'\u2287','suphsol':'\u27C9','suphsub':'\u2AD7','suplarr':'\u297B','supmult':'\u2AC2','supne':'\u228B','supnE':'\u2ACC','supplus':'\u2AC0','supset':'\u2283','Supset':'\u22D1','supseteq':'\u2287','supseteqq':'\u2AC6','supsetneq':'\u228B','supsetneqq':'\u2ACC','supsim':'\u2AC8','supsub':'\u2AD4','supsup':'\u2AD6','swarhk':'\u2926','swarr':'\u2199','swArr':'\u21D9','swarrow':'\u2199','swnwar':'\u292A','szlig':'\xDF','Tab':'\t','target':'\u2316','tau':'\u03C4','Tau':'\u03A4','tbrk':'\u23B4','tcaron':'\u0165','Tcaron':'\u0164','tcedil':'\u0163','Tcedil':'\u0162','tcy':'\u0442','Tcy':'\u0422','tdot':'\u20DB','telrec':'\u2315','tfr':'\uD835\uDD31','Tfr':'\uD835\uDD17','there4':'\u2234','therefore':'\u2234','Therefore':'\u2234','theta':'\u03B8','Theta':'\u0398','thetasym':'\u03D1','thetav':'\u03D1','thickapprox':'\u2248','thicksim':'\u223C','ThickSpace':'\u205F\u200A','thinsp':'\u2009','ThinSpace':'\u2009','thkap':'\u2248','thksim':'\u223C','thorn':'\xFE','THORN':'\xDE','tilde':'\u02DC','Tilde':'\u223C','TildeEqual':'\u2243','TildeFullEqual':'\u2245','TildeTilde':'\u2248','times':'\xD7','timesb':'\u22A0','timesbar':'\u2A31','timesd':'\u2A30','tint':'\u222D','toea':'\u2928','top':'\u22A4','topbot':'\u2336','topcir':'\u2AF1','topf':'\uD835\uDD65','Topf':'\uD835\uDD4B','topfork':'\u2ADA','tosa':'\u2929','tprime':'\u2034','trade':'\u2122','TRADE':'\u2122','triangle':'\u25B5','triangledown':'\u25BF','triangleleft':'\u25C3','trianglelefteq':'\u22B4','triangleq':'\u225C','triangleright':'\u25B9','trianglerighteq':'\u22B5','tridot':'\u25EC','trie':'\u225C','triminus':'\u2A3A','TripleDot':'\u20DB','triplus':'\u2A39','trisb':'\u29CD','tritime':'\u2A3B','trpezium':'\u23E2','tscr':'\uD835\uDCC9','Tscr':'\uD835\uDCAF','tscy':'\u0446','TScy':'\u0426','tshcy':'\u045B','TSHcy':'\u040B','tstrok':'\u0167','Tstrok':'\u0166','twixt':'\u226C','twoheadleftarrow':'\u219E','twoheadrightarrow':'\u21A0','uacute':'\xFA','Uacute':'\xDA','uarr':'\u2191','uArr':'\u21D1','Uarr':'\u219F','Uarrocir':'\u2949','ubrcy':'\u045E','Ubrcy':'\u040E','ubreve':'\u016D','Ubreve':'\u016C','ucirc':'\xFB','Ucirc':'\xDB','ucy':'\u0443','Ucy':'\u0423','udarr':'\u21C5','udblac':'\u0171','Udblac':'\u0170','udhar':'\u296E','ufisht':'\u297E','ufr':'\uD835\uDD32','Ufr':'\uD835\uDD18','ugrave':'\xF9','Ugrave':'\xD9','uHar':'\u2963','uharl':'\u21BF','uharr':'\u21BE','uhblk':'\u2580','ulcorn':'\u231C','ulcorner':'\u231C','ulcrop':'\u230F','ultri':'\u25F8','umacr':'\u016B','Umacr':'\u016A','uml':'\xA8','UnderBar':'_','UnderBrace':'\u23DF','UnderBracket':'\u23B5','UnderParenthesis':'\u23DD','Union':'\u22C3','UnionPlus':'\u228E','uogon':'\u0173','Uogon':'\u0172','uopf':'\uD835\uDD66','Uopf':'\uD835\uDD4C','uparrow':'\u2191','Uparrow':'\u21D1','UpArrow':'\u2191','UpArrowBar':'\u2912','UpArrowDownArrow':'\u21C5','updownarrow':'\u2195','Updownarrow':'\u21D5','UpDownArrow':'\u2195','UpEquilibrium':'\u296E','upharpoonleft':'\u21BF','upharpoonright':'\u21BE','uplus':'\u228E','UpperLeftArrow':'\u2196','UpperRightArrow':'\u2197','upsi':'\u03C5','Upsi':'\u03D2','upsih':'\u03D2','upsilon':'\u03C5','Upsilon':'\u03A5','UpTee':'\u22A5','UpTeeArrow':'\u21A5','upuparrows':'\u21C8','urcorn':'\u231D','urcorner':'\u231D','urcrop':'\u230E','uring':'\u016F','Uring':'\u016E','urtri':'\u25F9','uscr':'\uD835\uDCCA','Uscr':'\uD835\uDCB0','utdot':'\u22F0','utilde':'\u0169','Utilde':'\u0168','utri':'\u25B5','utrif':'\u25B4','uuarr':'\u21C8','uuml':'\xFC','Uuml':'\xDC','uwangle':'\u29A7','vangrt':'\u299C','varepsilon':'\u03F5','varkappa':'\u03F0','varnothing':'\u2205','varphi':'\u03D5','varpi':'\u03D6','varpropto':'\u221D','varr':'\u2195','vArr':'\u21D5','varrho':'\u03F1','varsigma':'\u03C2','varsubsetneq':'\u228A\uFE00','varsubsetneqq':'\u2ACB\uFE00','varsupsetneq':'\u228B\uFE00','varsupsetneqq':'\u2ACC\uFE00','vartheta':'\u03D1','vartriangleleft':'\u22B2','vartriangleright':'\u22B3','vBar':'\u2AE8','Vbar':'\u2AEB','vBarv':'\u2AE9','vcy':'\u0432','Vcy':'\u0412','vdash':'\u22A2','vDash':'\u22A8','Vdash':'\u22A9','VDash':'\u22AB','Vdashl':'\u2AE6','vee':'\u2228','Vee':'\u22C1','veebar':'\u22BB','veeeq':'\u225A','vellip':'\u22EE','verbar':'|','Verbar':'\u2016','vert':'|','Vert':'\u2016','VerticalBar':'\u2223','VerticalLine':'|','VerticalSeparator':'\u2758','VerticalTilde':'\u2240','VeryThinSpace':'\u200A','vfr':'\uD835\uDD33','Vfr':'\uD835\uDD19','vltri':'\u22B2','vnsub':'\u2282\u20D2','vnsup':'\u2283\u20D2','vopf':'\uD835\uDD67','Vopf':'\uD835\uDD4D','vprop':'\u221D','vrtri':'\u22B3','vscr':'\uD835\uDCCB','Vscr':'\uD835\uDCB1','vsubne':'\u228A\uFE00','vsubnE':'\u2ACB\uFE00','vsupne':'\u228B\uFE00','vsupnE':'\u2ACC\uFE00','Vvdash':'\u22AA','vzigzag':'\u299A','wcirc':'\u0175','Wcirc':'\u0174','wedbar':'\u2A5F','wedge':'\u2227','Wedge':'\u22C0','wedgeq':'\u2259','weierp':'\u2118','wfr':'\uD835\uDD34','Wfr':'\uD835\uDD1A','wopf':'\uD835\uDD68','Wopf':'\uD835\uDD4E','wp':'\u2118','wr':'\u2240','wreath':'\u2240','wscr':'\uD835\uDCCC','Wscr':'\uD835\uDCB2','xcap':'\u22C2','xcirc':'\u25EF','xcup':'\u22C3','xdtri':'\u25BD','xfr':'\uD835\uDD35','Xfr':'\uD835\uDD1B','xharr':'\u27F7','xhArr':'\u27FA','xi':'\u03BE','Xi':'\u039E','xlarr':'\u27F5','xlArr':'\u27F8','xmap':'\u27FC','xnis':'\u22FB','xodot':'\u2A00','xopf':'\uD835\uDD69','Xopf':'\uD835\uDD4F','xoplus':'\u2A01','xotime':'\u2A02','xrarr':'\u27F6','xrArr':'\u27F9','xscr':'\uD835\uDCCD','Xscr':'\uD835\uDCB3','xsqcup':'\u2A06','xuplus':'\u2A04','xutri':'\u25B3','xvee':'\u22C1','xwedge':'\u22C0','yacute':'\xFD','Yacute':'\xDD','yacy':'\u044F','YAcy':'\u042F','ycirc':'\u0177','Ycirc':'\u0176','ycy':'\u044B','Ycy':'\u042B','yen':'\xA5','yfr':'\uD835\uDD36','Yfr':'\uD835\uDD1C','yicy':'\u0457','YIcy':'\u0407','yopf':'\uD835\uDD6A','Yopf':'\uD835\uDD50','yscr':'\uD835\uDCCE','Yscr':'\uD835\uDCB4','yucy':'\u044E','YUcy':'\u042E','yuml':'\xFF','Yuml':'\u0178','zacute':'\u017A','Zacute':'\u0179','zcaron':'\u017E','Zcaron':'\u017D','zcy':'\u0437','Zcy':'\u0417','zdot':'\u017C','Zdot':'\u017B','zeetrf':'\u2128','ZeroWidthSpace':'\u200B','zeta':'\u03B6','Zeta':'\u0396','zfr':'\uD835\uDD37','Zfr':'\u2128','zhcy':'\u0436','ZHcy':'\u0416','zigrarr':'\u21DD','zopf':'\uD835\uDD6B','Zopf':'\u2124','zscr':'\uD835\uDCCF','Zscr':'\uD835\uDCB5','zwj':'\u200D','zwnj':'\u200C'};
- var decodeMapLegacy = {'aacute':'\xE1','Aacute':'\xC1','acirc':'\xE2','Acirc':'\xC2','acute':'\xB4','aelig':'\xE6','AElig':'\xC6','agrave':'\xE0','Agrave':'\xC0','amp':'&','AMP':'&','aring':'\xE5','Aring':'\xC5','atilde':'\xE3','Atilde':'\xC3','auml':'\xE4','Auml':'\xC4','brvbar':'\xA6','ccedil':'\xE7','Ccedil':'\xC7','cedil':'\xB8','cent':'\xA2','copy':'\xA9','COPY':'\xA9','curren':'\xA4','deg':'\xB0','divide':'\xF7','eacute':'\xE9','Eacute':'\xC9','ecirc':'\xEA','Ecirc':'\xCA','egrave':'\xE8','Egrave':'\xC8','eth':'\xF0','ETH':'\xD0','euml':'\xEB','Euml':'\xCB','frac12':'\xBD','frac14':'\xBC','frac34':'\xBE','gt':'>','GT':'>','iacute':'\xED','Iacute':'\xCD','icirc':'\xEE','Icirc':'\xCE','iexcl':'\xA1','igrave':'\xEC','Igrave':'\xCC','iquest':'\xBF','iuml':'\xEF','Iuml':'\xCF','laquo':'\xAB','lt':'<','LT':'<','macr':'\xAF','micro':'\xB5','middot':'\xB7','nbsp':'\xA0','not':'\xAC','ntilde':'\xF1','Ntilde':'\xD1','oacute':'\xF3','Oacute':'\xD3','ocirc':'\xF4','Ocirc':'\xD4','ograve':'\xF2','Ograve':'\xD2','ordf':'\xAA','ordm':'\xBA','oslash':'\xF8','Oslash':'\xD8','otilde':'\xF5','Otilde':'\xD5','ouml':'\xF6','Ouml':'\xD6','para':'\xB6','plusmn':'\xB1','pound':'\xA3','quot':'"','QUOT':'"','raquo':'\xBB','reg':'\xAE','REG':'\xAE','sect':'\xA7','shy':'\xAD','sup1':'\xB9','sup2':'\xB2','sup3':'\xB3','szlig':'\xDF','thorn':'\xFE','THORN':'\xDE','times':'\xD7','uacute':'\xFA','Uacute':'\xDA','ucirc':'\xFB','Ucirc':'\xDB','ugrave':'\xF9','Ugrave':'\xD9','uml':'\xA8','uuml':'\xFC','Uuml':'\xDC','yacute':'\xFD','Yacute':'\xDD','yen':'\xA5','yuml':'\xFF'};
- var decodeMapNumeric = {'0':'\uFFFD','128':'\u20AC','130':'\u201A','131':'\u0192','132':'\u201E','133':'\u2026','134':'\u2020','135':'\u2021','136':'\u02C6','137':'\u2030','138':'\u0160','139':'\u2039','140':'\u0152','142':'\u017D','145':'\u2018','146':'\u2019','147':'\u201C','148':'\u201D','149':'\u2022','150':'\u2013','151':'\u2014','152':'\u02DC','153':'\u2122','154':'\u0161','155':'\u203A','156':'\u0153','158':'\u017E','159':'\u0178'};
- var invalidReferenceCodePoints = [1,2,3,4,5,6,7,8,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,64976,64977,64978,64979,64980,64981,64982,64983,64984,64985,64986,64987,64988,64989,64990,64991,64992,64993,64994,64995,64996,64997,64998,64999,65000,65001,65002,65003,65004,65005,65006,65007,65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111];
-
- /*--------------------------------------------------------------------------*/
-
- var stringFromCharCode = String.fromCharCode;
-
- var object = {};
- var hasOwnProperty = object.hasOwnProperty;
- var has = function(object, propertyName) {
- return hasOwnProperty.call(object, propertyName);
- };
-
- var contains = function(array, value) {
- var index = -1;
- var length = array.length;
- while (++index < length) {
- if (array[index] == value) {
- return true;
- }
- }
- return false;
- };
-
- var merge = function(options, defaults) {
- if (!options) {
- return defaults;
- }
- var result = {};
- var key;
- for (key in defaults) {
- // A `hasOwnProperty` check is not needed here, since only recognized
- // option names are used anyway. Any others are ignored.
- result[key] = has(options, key) ? options[key] : defaults[key];
- }
- return result;
- };
-
- // Modified version of `ucs2encode`; see https://mths.be/punycode.
- var codePointToSymbol = function(codePoint, strict) {
- var output = '';
- if ((codePoint >= 0xD800 && codePoint <= 0xDFFF) || codePoint > 0x10FFFF) {
- // See issue #4:
- // “Otherwise, if the number is in the range 0xD800 to 0xDFFF or is
- // greater than 0x10FFFF, then this is a parse error. Return a U+FFFD
- // REPLACEMENT CHARACTER.”
- if (strict) {
- parseError('character reference outside the permissible Unicode range');
- }
- return '\uFFFD';
- }
- if (has(decodeMapNumeric, codePoint)) {
- if (strict) {
- parseError('disallowed character reference');
- }
- return decodeMapNumeric[codePoint];
- }
- if (strict && contains(invalidReferenceCodePoints, codePoint)) {
- parseError('disallowed character reference');
- }
- if (codePoint > 0xFFFF) {
- codePoint -= 0x10000;
- output += stringFromCharCode(codePoint >>> 10 & 0x3FF | 0xD800);
- codePoint = 0xDC00 | codePoint & 0x3FF;
- }
- output += stringFromCharCode(codePoint);
- return output;
- };
-
- var hexEscape = function(codePoint) {
- return '' + codePoint.toString(16).toUpperCase() + ';';
- };
-
- var decEscape = function(codePoint) {
- return '' + codePoint + ';';
- };
-
- var parseError = function(message) {
- throw Error('Parse error: ' + message);
- };
-
- /*--------------------------------------------------------------------------*/
-
- var encode = function(string, options) {
- options = merge(options, encode.options);
- var strict = options.strict;
- if (strict && regexInvalidRawCodePoint.test(string)) {
- parseError('forbidden code point');
- }
- var encodeEverything = options.encodeEverything;
- var useNamedReferences = options.useNamedReferences;
- var allowUnsafeSymbols = options.allowUnsafeSymbols;
- var escapeCodePoint = options.decimal ? decEscape : hexEscape;
-
- var escapeBmpSymbol = function(symbol) {
- return escapeCodePoint(symbol.charCodeAt(0));
- };
-
- if (encodeEverything) {
- // Encode ASCII symbols.
- string = string.replace(regexAsciiWhitelist, function(symbol) {
- // Use named references if requested & possible.
- if (useNamedReferences && has(encodeMap, symbol)) {
- return '&' + encodeMap[symbol] + ';';
- }
- return escapeBmpSymbol(symbol);
- });
- // Shorten a few escapes that represent two symbols, of which at least one
- // is within the ASCII range.
- if (useNamedReferences) {
- string = string
- .replace(/>\u20D2/g, '>⃒')
- .replace(/<\u20D2/g, '<⃒')
- .replace(/fj/g, 'fj');
- }
- // Encode non-ASCII symbols.
- if (useNamedReferences) {
- // Encode non-ASCII symbols that can be replaced with a named reference.
- string = string.replace(regexEncodeNonAscii, function(string) {
- // Note: there is no need to check `has(encodeMap, string)` here.
- return '&' + encodeMap[string] + ';';
- });
- }
- // Note: any remaining non-ASCII symbols are handled outside of the `if`.
- } else if (useNamedReferences) {
- // Apply named character references.
- // Encode `<>"'&` using named character references.
- if (!allowUnsafeSymbols) {
- string = string.replace(regexEscape, function(string) {
- return '&' + encodeMap[string] + ';'; // no need to check `has()` here
- });
- }
- // Shorten escapes that represent two symbols, of which at least one is
- // `<>"'&`.
- string = string
- .replace(/>\u20D2/g, '>⃒')
- .replace(/<\u20D2/g, '<⃒');
- // Encode non-ASCII symbols that can be replaced with a named reference.
- string = string.replace(regexEncodeNonAscii, function(string) {
- // Note: there is no need to check `has(encodeMap, string)` here.
- return '&' + encodeMap[string] + ';';
- });
- } else if (!allowUnsafeSymbols) {
- // Encode `<>"'&` using hexadecimal escapes, now that they’re not handled
- // using named character references.
- string = string.replace(regexEscape, escapeBmpSymbol);
- }
- return string
- // Encode astral symbols.
- .replace(regexAstralSymbols, function($0) {
- // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
- var high = $0.charCodeAt(0);
- var low = $0.charCodeAt(1);
- var codePoint = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000;
- return escapeCodePoint(codePoint);
- })
- // Encode any remaining BMP symbols that are not printable ASCII symbols
- // using a hexadecimal escape.
- .replace(regexBmpWhitelist, escapeBmpSymbol);
- };
- // Expose default options (so they can be overridden globally).
- encode.options = {
- 'allowUnsafeSymbols': false,
- 'encodeEverything': false,
- 'strict': false,
- 'useNamedReferences': false,
- 'decimal' : false
- };
-
- var decode = function(html, options) {
- options = merge(options, decode.options);
- var strict = options.strict;
- if (strict && regexInvalidEntity.test(html)) {
- parseError('malformed character reference');
- }
- return html.replace(regexDecode, function($0, $1, $2, $3, $4, $5, $6, $7, $8) {
- var codePoint;
- var semicolon;
- var decDigits;
- var hexDigits;
- var reference;
- var next;
-
- if ($1) {
- reference = $1;
- // Note: there is no need to check `has(decodeMap, reference)`.
- return decodeMap[reference];
- }
-
- if ($2) {
- // Decode named character references without trailing `;`, e.g. `&`.
- // This is only a parse error if it gets converted to `&`, or if it is
- // followed by `=` in an attribute context.
- reference = $2;
- next = $3;
- if (next && options.isAttributeValue) {
- if (strict && next == '=') {
- parseError('`&` did not start a character reference');
- }
- return $0;
- } else {
- if (strict) {
- parseError(
- 'named character reference was not terminated by a semicolon'
- );
- }
- // Note: there is no need to check `has(decodeMapLegacy, reference)`.
- return decodeMapLegacy[reference] + (next || '');
- }
- }
-
- if ($4) {
- // Decode decimal escapes, e.g. `𝌆`.
- decDigits = $4;
- semicolon = $5;
- if (strict && !semicolon) {
- parseError('character reference was not terminated by a semicolon');
- }
- codePoint = parseInt(decDigits, 10);
- return codePointToSymbol(codePoint, strict);
- }
-
- if ($6) {
- // Decode hexadecimal escapes, e.g. `𝌆`.
- hexDigits = $6;
- semicolon = $7;
- if (strict && !semicolon) {
- parseError('character reference was not terminated by a semicolon');
- }
- codePoint = parseInt(hexDigits, 16);
- return codePointToSymbol(codePoint, strict);
- }
-
- // If we’re still here, `if ($7)` is implied; it’s an ambiguous
- // ampersand for sure. https://mths.be/notes/ambiguous-ampersands
- if (strict) {
- parseError(
- 'named character reference was not terminated by a semicolon'
- );
- }
- return $0;
- });
- };
- // Expose default options (so they can be overridden globally).
- decode.options = {
- 'isAttributeValue': false,
- 'strict': false
- };
-
- var escape = function(string) {
- return string.replace(regexEscape, function($0) {
- // Note: there is no need to check `has(escapeMap, $0)` here.
- return escapeMap[$0];
- });
- };
-
- /*--------------------------------------------------------------------------*/
-
- var he = {
- 'version': '1.2.0',
- 'encode': encode,
- 'decode': decode,
- 'escape': escape,
- 'unescape': decode
- };
-
- // Some AMD build optimizers, like r.js, check for specific condition patterns
- // like the following:
- if (
- false
- ) {
- define(function() {
- return he;
- });
- } else if (freeExports && !freeExports.nodeType) {
- if (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+
- freeModule.exports = he;
- } else { // in Narwhal or RingoJS v0.7.0-
- for (var key in he) {
- has(he, key) && (freeExports[key] = he[key]);
- }
- }
- } else { // in Rhino or a web browser
- root.he = he;
- }
-
-}(this));
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],55:[function(require,module,exports){
-exports.read = function (buffer, offset, isLE, mLen, nBytes) {
- var e, m
- var eLen = (nBytes * 8) - mLen - 1
- var eMax = (1 << eLen) - 1
- var eBias = eMax >> 1
- var nBits = -7
- var i = isLE ? (nBytes - 1) : 0
- var d = isLE ? -1 : 1
- var s = buffer[offset + i]
-
- i += d
-
- e = s & ((1 << (-nBits)) - 1)
- s >>= (-nBits)
- nBits += eLen
- for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
-
- m = e & ((1 << (-nBits)) - 1)
- e >>= (-nBits)
- nBits += mLen
- for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
-
- if (e === 0) {
- e = 1 - eBias
- } else if (e === eMax) {
- return m ? NaN : ((s ? -1 : 1) * Infinity)
- } else {
- m = m + Math.pow(2, mLen)
- e = e - eBias
- }
- return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
-}
-
-exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
- var e, m, c
- var eLen = (nBytes * 8) - mLen - 1
- var eMax = (1 << eLen) - 1
- var eBias = eMax >> 1
- var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
- var i = isLE ? 0 : (nBytes - 1)
- var d = isLE ? 1 : -1
- var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
-
- value = Math.abs(value)
-
- if (isNaN(value) || value === Infinity) {
- m = isNaN(value) ? 1 : 0
- e = eMax
- } else {
- e = Math.floor(Math.log(value) / Math.LN2)
- if (value * (c = Math.pow(2, -e)) < 1) {
- e--
- c *= 2
- }
- if (e + eBias >= 1) {
- value += rt / c
- } else {
- value += rt * Math.pow(2, 1 - eBias)
- }
- if (value * c >= 2) {
- e++
- c /= 2
- }
-
- if (e + eBias >= eMax) {
- m = 0
- e = eMax
- } else if (e + eBias >= 1) {
- m = ((value * c) - 1) * Math.pow(2, mLen)
- e = e + eBias
- } else {
- m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
- e = 0
- }
- }
-
- for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
-
- e = (e << mLen) | m
- eLen += mLen
- for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
-
- buffer[offset + i - d] |= s * 128
-}
-
-},{}],56:[function(require,module,exports){
-if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- };
-} else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
- }
-}
-
-},{}],57:[function(require,module,exports){
-/*!
- * Determine if an object is a Buffer
- *
- * @author Feross Aboukhadijeh
- * @license MIT
- */
-
-// The _isBuffer check is for Safari 5-7 support, because it's missing
-// Object.prototype.constructor. Remove this eventually
-module.exports = function (obj) {
- return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
-}
-
-function isBuffer (obj) {
- return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
-}
-
-// For Node v0.10 support. Remove this eventually.
-function isSlowBuffer (obj) {
- return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
-}
-
-},{}],58:[function(require,module,exports){
-var toString = {}.toString;
-
-module.exports = Array.isArray || function (arr) {
- return toString.call(arr) == '[object Array]';
-};
-
-},{}],59:[function(require,module,exports){
-(function (process){
-var path = require('path');
-var fs = require('fs');
-var _0777 = parseInt('0777', 8);
-
-module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
-
-function mkdirP (p, opts, f, made) {
- if (typeof opts === 'function') {
- f = opts;
- opts = {};
- }
- else if (!opts || typeof opts !== 'object') {
- opts = { mode: opts };
- }
-
- var mode = opts.mode;
- var xfs = opts.fs || fs;
-
- if (mode === undefined) {
- mode = _0777 & (~process.umask());
- }
- if (!made) made = null;
-
- var cb = f || function () {};
- p = path.resolve(p);
-
- xfs.mkdir(p, mode, function (er) {
- if (!er) {
- made = made || p;
- return cb(null, made);
- }
- switch (er.code) {
- case 'ENOENT':
- mkdirP(path.dirname(p), opts, function (er, made) {
- if (er) cb(er, made);
- else mkdirP(p, opts, cb, made);
- });
- break;
-
- // In the case of any other error, just see if there's a dir
- // there already. If so, then hooray! If not, then something
- // is borked.
- default:
- xfs.stat(p, function (er2, stat) {
- // if the stat fails, then that's super weird.
- // let the original error be the failure reason.
- if (er2 || !stat.isDirectory()) cb(er, made)
- else cb(null, made);
- });
- break;
- }
- });
-}
-
-mkdirP.sync = function sync (p, opts, made) {
- if (!opts || typeof opts !== 'object') {
- opts = { mode: opts };
- }
-
- var mode = opts.mode;
- var xfs = opts.fs || fs;
-
- if (mode === undefined) {
- mode = _0777 & (~process.umask());
- }
- if (!made) made = null;
-
- p = path.resolve(p);
-
- try {
- xfs.mkdirSync(p, mode);
- made = made || p;
- }
- catch (err0) {
- switch (err0.code) {
- case 'ENOENT' :
- made = sync(path.dirname(p), opts, made);
- sync(p, opts, made);
- break;
-
- // In the case of any other error, just see if there's a dir
- // there already. If so, then hooray! If not, then something
- // is borked.
- default:
- var stat;
- try {
- stat = xfs.statSync(p);
- }
- catch (err1) {
- throw err0;
- }
- if (!stat.isDirectory()) throw err0;
- break;
- }
- }
-
- return made;
-};
-
-}).call(this,require('_process'))
-},{"_process":69,"fs":42,"path":42}],60:[function(require,module,exports){
-/**
- * Helpers.
- */
-
-var s = 1000;
-var m = s * 60;
-var h = m * 60;
-var d = h * 24;
-var w = d * 7;
-var y = d * 365.25;
-
-/**
- * Parse or format the given `val`.
- *
- * Options:
- *
- * - `long` verbose formatting [false]
- *
- * @param {String|Number} val
- * @param {Object} [options]
- * @throws {Error} throw an error if val is not a non-empty string or a number
- * @return {String|Number}
- * @api public
- */
-
-module.exports = function(val, options) {
- options = options || {};
- var type = typeof val;
- if (type === 'string' && val.length > 0) {
- return parse(val);
- } else if (type === 'number' && isNaN(val) === false) {
- return options.long ? fmtLong(val) : fmtShort(val);
- }
- throw new Error(
- 'val is not a non-empty string or a valid number. val=' +
- JSON.stringify(val)
- );
-};
-
-/**
- * Parse the given `str` and return milliseconds.
- *
- * @param {String} str
- * @return {Number}
- * @api private
- */
-
-function parse(str) {
- str = String(str);
- if (str.length > 100) {
- return;
- }
- var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
- str
- );
- if (!match) {
- return;
- }
- var n = parseFloat(match[1]);
- var type = (match[2] || 'ms').toLowerCase();
- switch (type) {
- case 'years':
- case 'year':
- case 'yrs':
- case 'yr':
- case 'y':
- return n * y;
- case 'weeks':
- case 'week':
- case 'w':
- return n * w;
- case 'days':
- case 'day':
- case 'd':
- return n * d;
- case 'hours':
- case 'hour':
- case 'hrs':
- case 'hr':
- case 'h':
- return n * h;
- case 'minutes':
- case 'minute':
- case 'mins':
- case 'min':
- case 'm':
- return n * m;
- case 'seconds':
- case 'second':
- case 'secs':
- case 'sec':
- case 's':
- return n * s;
- case 'milliseconds':
- case 'millisecond':
- case 'msecs':
- case 'msec':
- case 'ms':
- return n;
- default:
- return undefined;
- }
-}
-
-/**
- * Short format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
-
-function fmtShort(ms) {
- var msAbs = Math.abs(ms);
- if (msAbs >= d) {
- return Math.round(ms / d) + 'd';
- }
- if (msAbs >= h) {
- return Math.round(ms / h) + 'h';
- }
- if (msAbs >= m) {
- return Math.round(ms / m) + 'm';
- }
- if (msAbs >= s) {
- return Math.round(ms / s) + 's';
- }
- return ms + 'ms';
-}
-
-/**
- * Long format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
-
-function fmtLong(ms) {
- var msAbs = Math.abs(ms);
- if (msAbs >= d) {
- return plural(ms, msAbs, d, 'day');
- }
- if (msAbs >= h) {
- return plural(ms, msAbs, h, 'hour');
- }
- if (msAbs >= m) {
- return plural(ms, msAbs, m, 'minute');
- }
- if (msAbs >= s) {
- return plural(ms, msAbs, s, 'second');
- }
- return ms + ' ms';
-}
-
-/**
- * Pluralization helper.
- */
-
-function plural(ms, msAbs, n, name) {
- var isPlural = msAbs >= n * 1.5;
- return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
-}
-
-},{}],61:[function(require,module,exports){
-'use strict';
-
-var keysShim;
-if (!Object.keys) {
- // modified from https://github.com/es-shims/es5-shim
- var has = Object.prototype.hasOwnProperty;
- var toStr = Object.prototype.toString;
- var isArgs = require('./isArguments'); // eslint-disable-line global-require
- var isEnumerable = Object.prototype.propertyIsEnumerable;
- var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
- var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
- var dontEnums = [
- 'toString',
- 'toLocaleString',
- 'valueOf',
- 'hasOwnProperty',
- 'isPrototypeOf',
- 'propertyIsEnumerable',
- 'constructor'
- ];
- var equalsConstructorPrototype = function (o) {
- var ctor = o.constructor;
- return ctor && ctor.prototype === o;
- };
- var excludedKeys = {
- $applicationCache: true,
- $console: true,
- $external: true,
- $frame: true,
- $frameElement: true,
- $frames: true,
- $innerHeight: true,
- $innerWidth: true,
- $outerHeight: true,
- $outerWidth: true,
- $pageXOffset: true,
- $pageYOffset: true,
- $parent: true,
- $scrollLeft: true,
- $scrollTop: true,
- $scrollX: true,
- $scrollY: true,
- $self: true,
- $webkitIndexedDB: true,
- $webkitStorageInfo: true,
- $window: true
- };
- var hasAutomationEqualityBug = (function () {
- /* global window */
- if (typeof window === 'undefined') { return false; }
- for (var k in window) {
- try {
- if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
- try {
- equalsConstructorPrototype(window[k]);
- } catch (e) {
- return true;
- }
- }
- } catch (e) {
- return true;
- }
- }
- return false;
- }());
- var equalsConstructorPrototypeIfNotBuggy = function (o) {
- /* global window */
- if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
- return equalsConstructorPrototype(o);
- }
- try {
- return equalsConstructorPrototype(o);
- } catch (e) {
- return false;
- }
- };
-
- keysShim = function keys(object) {
- var isObject = object !== null && typeof object === 'object';
- var isFunction = toStr.call(object) === '[object Function]';
- var isArguments = isArgs(object);
- var isString = isObject && toStr.call(object) === '[object String]';
- var theKeys = [];
-
- if (!isObject && !isFunction && !isArguments) {
- throw new TypeError('Object.keys called on a non-object');
- }
-
- var skipProto = hasProtoEnumBug && isFunction;
- if (isString && object.length > 0 && !has.call(object, 0)) {
- for (var i = 0; i < object.length; ++i) {
- theKeys.push(String(i));
- }
- }
-
- if (isArguments && object.length > 0) {
- for (var j = 0; j < object.length; ++j) {
- theKeys.push(String(j));
- }
- } else {
- for (var name in object) {
- if (!(skipProto && name === 'prototype') && has.call(object, name)) {
- theKeys.push(String(name));
- }
- }
- }
-
- if (hasDontEnumBug) {
- var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
-
- for (var k = 0; k < dontEnums.length; ++k) {
- if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
- theKeys.push(dontEnums[k]);
- }
- }
- }
- return theKeys;
- };
-}
-module.exports = keysShim;
-
-},{"./isArguments":63}],62:[function(require,module,exports){
-'use strict';
-
-var slice = Array.prototype.slice;
-var isArgs = require('./isArguments');
-
-var origKeys = Object.keys;
-var keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./implementation');
-
-var originalKeys = Object.keys;
-
-keysShim.shim = function shimObjectKeys() {
- if (Object.keys) {
- var keysWorksWithArguments = (function () {
- // Safari 5.0 bug
- var args = Object.keys(arguments);
- return args && args.length === arguments.length;
- }(1, 2));
- if (!keysWorksWithArguments) {
- Object.keys = function keys(object) { // eslint-disable-line func-name-matching
- if (isArgs(object)) {
- return originalKeys(slice.call(object));
- }
- return originalKeys(object);
- };
- }
- } else {
- Object.keys = keysShim;
- }
- return Object.keys || keysShim;
-};
-
-module.exports = keysShim;
-
-},{"./implementation":61,"./isArguments":63}],63:[function(require,module,exports){
-'use strict';
-
-var toStr = Object.prototype.toString;
-
-module.exports = function isArguments(value) {
- var str = toStr.call(value);
- var isArgs = str === '[object Arguments]';
- if (!isArgs) {
- isArgs = str !== '[object Array]' &&
- value !== null &&
- typeof value === 'object' &&
- typeof value.length === 'number' &&
- value.length >= 0 &&
- toStr.call(value.callee) === '[object Function]';
- }
- return isArgs;
-};
-
-},{}],64:[function(require,module,exports){
-'use strict';
-
-// modified from https://github.com/es-shims/es6-shim
-var keys = require('object-keys');
-var bind = require('function-bind');
-var canBeObject = function (obj) {
- return typeof obj !== 'undefined' && obj !== null;
-};
-var hasSymbols = require('has-symbols/shams')();
-var toObject = Object;
-var push = bind.call(Function.call, Array.prototype.push);
-var propIsEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable);
-var originalGetSymbols = hasSymbols ? Object.getOwnPropertySymbols : null;
-
-module.exports = function assign(target, source1) {
- if (!canBeObject(target)) { throw new TypeError('target must be an object'); }
- var objTarget = toObject(target);
- var s, source, i, props, syms, value, key;
- for (s = 1; s < arguments.length; ++s) {
- source = toObject(arguments[s]);
- props = keys(source);
- var getSymbols = hasSymbols && (Object.getOwnPropertySymbols || originalGetSymbols);
- if (getSymbols) {
- syms = getSymbols(source);
- for (i = 0; i < syms.length; ++i) {
- key = syms[i];
- if (propIsEnumerable(source, key)) {
- push(props, key);
- }
- }
- }
- for (i = 0; i < props.length; ++i) {
- key = props[i];
- value = source[key];
- if (propIsEnumerable(source, key)) {
- objTarget[key] = value;
- }
- }
- }
- return objTarget;
-};
-
-},{"function-bind":52,"has-symbols/shams":53,"object-keys":62}],65:[function(require,module,exports){
-'use strict';
-
-var defineProperties = require('define-properties');
-
-var implementation = require('./implementation');
-var getPolyfill = require('./polyfill');
-var shim = require('./shim');
-
-var polyfill = getPolyfill();
-
-defineProperties(polyfill, {
- getPolyfill: getPolyfill,
- implementation: implementation,
- shim: shim
-});
-
-module.exports = polyfill;
-
-},{"./implementation":64,"./polyfill":66,"./shim":67,"define-properties":47}],66:[function(require,module,exports){
-'use strict';
-
-var implementation = require('./implementation');
-
-var lacksProperEnumerationOrder = function () {
- if (!Object.assign) {
- return false;
- }
- // v8, specifically in node 4.x, has a bug with incorrect property enumeration order
- // note: this does not detect the bug unless there's 20 characters
- var str = 'abcdefghijklmnopqrst';
- var letters = str.split('');
- var map = {};
- for (var i = 0; i < letters.length; ++i) {
- map[letters[i]] = letters[i];
- }
- var obj = Object.assign({}, map);
- var actual = '';
- for (var k in obj) {
- actual += k;
- }
- return str !== actual;
-};
-
-var assignHasPendingExceptions = function () {
- if (!Object.assign || !Object.preventExtensions) {
- return false;
- }
- // Firefox 37 still has "pending exception" logic in its Object.assign implementation,
- // which is 72% slower than our shim, and Firefox 40's native implementation.
- var thrower = Object.preventExtensions({ 1: 2 });
- try {
- Object.assign(thrower, 'xy');
- } catch (e) {
- return thrower[1] === 'y';
- }
- return false;
-};
-
-module.exports = function getPolyfill() {
- if (!Object.assign) {
- return implementation;
- }
- if (lacksProperEnumerationOrder()) {
- return implementation;
- }
- if (assignHasPendingExceptions()) {
- return implementation;
- }
- return Object.assign;
-};
-
-},{"./implementation":64}],67:[function(require,module,exports){
-'use strict';
-
-var define = require('define-properties');
-var getPolyfill = require('./polyfill');
-
-module.exports = function shimAssign() {
- var polyfill = getPolyfill();
- define(
- Object,
- { assign: polyfill },
- { assign: function () { return Object.assign !== polyfill; } }
- );
- return polyfill;
-};
-
-},{"./polyfill":66,"define-properties":47}],68:[function(require,module,exports){
-(function (process){
-'use strict';
-
-if (!process.version ||
- process.version.indexOf('v0.') === 0 ||
- process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
- module.exports = { nextTick: nextTick };
-} else {
- module.exports = process
-}
-
-function nextTick(fn, arg1, arg2, arg3) {
- if (typeof fn !== 'function') {
- throw new TypeError('"callback" argument must be a function');
- }
- var len = arguments.length;
- var args, i;
- switch (len) {
- case 0:
- case 1:
- return process.nextTick(fn);
- case 2:
- return process.nextTick(function afterTickOne() {
- fn.call(null, arg1);
- });
- case 3:
- return process.nextTick(function afterTickTwo() {
- fn.call(null, arg1, arg2);
- });
- case 4:
- return process.nextTick(function afterTickThree() {
- fn.call(null, arg1, arg2, arg3);
- });
- default:
- args = new Array(len - 1);
- i = 0;
- while (i < args.length) {
- args[i++] = arguments[i];
- }
- return process.nextTick(function afterTick() {
- fn.apply(null, args);
- });
- }
-}
-
-
-}).call(this,require('_process'))
-},{"_process":69}],69:[function(require,module,exports){
-// shim for using process in browser
-var process = module.exports = {};
-
-// cached from whatever global is present so that test runners that stub it
-// don't break things. But we need to wrap it in a try catch in case it is
-// wrapped in strict mode code which doesn't define any globals. It's inside a
-// function because try/catches deoptimize in certain engines.
-
-var cachedSetTimeout;
-var cachedClearTimeout;
-
-function defaultSetTimout() {
- throw new Error('setTimeout has not been defined');
-}
-function defaultClearTimeout () {
- throw new Error('clearTimeout has not been defined');
-}
-(function () {
- try {
- if (typeof setTimeout === 'function') {
- cachedSetTimeout = setTimeout;
- } else {
- cachedSetTimeout = defaultSetTimout;
- }
- } catch (e) {
- cachedSetTimeout = defaultSetTimout;
- }
- try {
- if (typeof clearTimeout === 'function') {
- cachedClearTimeout = clearTimeout;
- } else {
- cachedClearTimeout = defaultClearTimeout;
- }
- } catch (e) {
- cachedClearTimeout = defaultClearTimeout;
- }
-} ())
-function runTimeout(fun) {
- if (cachedSetTimeout === setTimeout) {
- //normal enviroments in sane situations
- return setTimeout(fun, 0);
- }
- // if setTimeout wasn't available but was latter defined
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
- cachedSetTimeout = setTimeout;
- return setTimeout(fun, 0);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedSetTimeout(fun, 0);
- } catch(e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedSetTimeout.call(null, fun, 0);
- } catch(e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
- return cachedSetTimeout.call(this, fun, 0);
- }
- }
-
-
-}
-function runClearTimeout(marker) {
- if (cachedClearTimeout === clearTimeout) {
- //normal enviroments in sane situations
- return clearTimeout(marker);
- }
- // if clearTimeout wasn't available but was latter defined
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
- cachedClearTimeout = clearTimeout;
- return clearTimeout(marker);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedClearTimeout(marker);
- } catch (e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedClearTimeout.call(null, marker);
- } catch (e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
- return cachedClearTimeout.call(this, marker);
- }
- }
-
-
-
-}
-var queue = [];
-var draining = false;
-var currentQueue;
-var queueIndex = -1;
-
-function cleanUpNextTick() {
- if (!draining || !currentQueue) {
- return;
- }
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
-}
-
-function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = runTimeout(cleanUpNextTick);
- draining = true;
-
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- runClearTimeout(timeout);
-}
-
-process.nextTick = function (fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
-};
-
-// v8 likes predictible objects
-function Item(fun, array) {
- this.fun = fun;
- this.array = array;
-}
-Item.prototype.run = function () {
- this.fun.apply(null, this.array);
-};
-process.title = 'browser';
-process.browser = true;
-process.env = {};
-process.argv = [];
-process.version = ''; // empty string to avoid regexp issues
-process.versions = {};
-
-function noop() {}
-
-process.on = noop;
-process.addListener = noop;
-process.once = noop;
-process.off = noop;
-process.removeListener = noop;
-process.removeAllListeners = noop;
-process.emit = noop;
-process.prependListener = noop;
-process.prependOnceListener = noop;
-
-process.listeners = function (name) { return [] }
-
-process.binding = function (name) {
- throw new Error('process.binding is not supported');
-};
-
-process.cwd = function () { return '/' };
-process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
-};
-process.umask = function() { return 0; };
-
-},{}],70:[function(require,module,exports){
-module.exports = require('./lib/_stream_duplex.js');
-
-},{"./lib/_stream_duplex.js":71}],71:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node 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.
-
-// a duplex stream is just a stream that is both readable and writable.
-// Since JS doesn't have multiple prototypal inheritance, this class
-// prototypally inherits from Readable, and then parasitically from
-// Writable.
-
-'use strict';
-
-/**/
-
-var pna = require('process-nextick-args');
-/* */
-
-/**/
-var objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) {
- keys.push(key);
- }return keys;
-};
-/* */
-
-module.exports = Duplex;
-
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/* */
-
-var Readable = require('./_stream_readable');
-var Writable = require('./_stream_writable');
-
-util.inherits(Duplex, Readable);
-
-{
- // avoid scope creep, the keys array can then be collected
- var keys = objectKeys(Writable.prototype);
- for (var v = 0; v < keys.length; v++) {
- var method = keys[v];
- if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
- }
-}
-
-function Duplex(options) {
- if (!(this instanceof Duplex)) return new Duplex(options);
-
- Readable.call(this, options);
- Writable.call(this, options);
-
- if (options && options.readable === false) this.readable = false;
-
- if (options && options.writable === false) this.writable = false;
-
- this.allowHalfOpen = true;
- if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
-
- this.once('end', onend);
-}
-
-Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function () {
- return this._writableState.highWaterMark;
- }
-});
-
-// the no-half-open enforcer
-function onend() {
- // if we allow half-open state, or if the writable side ended,
- // then we're ok.
- if (this.allowHalfOpen || this._writableState.ended) return;
-
- // no more data can be written.
- // But allow more writes to happen in this tick.
- pna.nextTick(onEndNT, this);
-}
-
-function onEndNT(self) {
- self.end();
-}
-
-Object.defineProperty(Duplex.prototype, 'destroyed', {
- get: function () {
- if (this._readableState === undefined || this._writableState === undefined) {
- return false;
- }
- return this._readableState.destroyed && this._writableState.destroyed;
- },
- set: function (value) {
- // we ignore the value if the stream
- // has not been initialized yet
- if (this._readableState === undefined || this._writableState === undefined) {
- return;
- }
-
- // backward compatibility, the user is explicitly
- // managing destroyed
- this._readableState.destroyed = value;
- this._writableState.destroyed = value;
- }
-});
-
-Duplex.prototype._destroy = function (err, cb) {
- this.push(null);
- this.end();
-
- pna.nextTick(cb, err);
-};
-},{"./_stream_readable":73,"./_stream_writable":75,"core-util-is":44,"inherits":56,"process-nextick-args":68}],72:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node 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.
-
-// a passthrough stream.
-// basically just the most minimal sort of Transform stream.
-// Every written chunk gets output as-is.
-
-'use strict';
-
-module.exports = PassThrough;
-
-var Transform = require('./_stream_transform');
-
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/* */
-
-util.inherits(PassThrough, Transform);
-
-function PassThrough(options) {
- if (!(this instanceof PassThrough)) return new PassThrough(options);
-
- Transform.call(this, options);
-}
-
-PassThrough.prototype._transform = function (chunk, encoding, cb) {
- cb(null, chunk);
-};
-},{"./_stream_transform":74,"core-util-is":44,"inherits":56}],73:[function(require,module,exports){
-(function (process,global){
-// Copyright Joyent, Inc. and other Node 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.
-
-'use strict';
-
-/**/
-
-var pna = require('process-nextick-args');
-/* */
-
-module.exports = Readable;
-
-/**/
-var isArray = require('isarray');
-/* */
-
-/**/
-var Duplex;
-/* */
-
-Readable.ReadableState = ReadableState;
-
-/**/
-var EE = require('events').EventEmitter;
-
-var EElistenerCount = function (emitter, type) {
- return emitter.listeners(type).length;
-};
-/* */
-
-/**/
-var Stream = require('./internal/streams/stream');
-/* */
-
-/**/
-
-var Buffer = require('safe-buffer').Buffer;
-var OurUint8Array = global.Uint8Array || function () {};
-function _uint8ArrayToBuffer(chunk) {
- return Buffer.from(chunk);
-}
-function _isUint8Array(obj) {
- return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
-}
-
-/* */
-
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/* */
-
-/**/
-var debugUtil = require('util');
-var debug = void 0;
-if (debugUtil && debugUtil.debuglog) {
- debug = debugUtil.debuglog('stream');
-} else {
- debug = function () {};
-}
-/* */
-
-var BufferList = require('./internal/streams/BufferList');
-var destroyImpl = require('./internal/streams/destroy');
-var StringDecoder;
-
-util.inherits(Readable, Stream);
-
-var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
-
-function prependListener(emitter, event, fn) {
- // Sadly this is not cacheable as some libraries bundle their own
- // event emitter implementation with them.
- if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
-
- // This is a hack to make sure that our error handler is attached before any
- // userland ones. NEVER DO THIS. This is here only because this code needs
- // to continue to work with older versions of Node.js that do not include
- // the prependListener() method. The goal is to eventually remove this hack.
- if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
-}
-
-function ReadableState(options, stream) {
- Duplex = Duplex || require('./_stream_duplex');
-
- options = options || {};
-
- // Duplex streams are both readable and writable, but share
- // the same options object.
- // However, some cases require setting options to different
- // values for the readable and the writable sides of the duplex stream.
- // These options can be provided separately as readableXXX and writableXXX.
- var isDuplex = stream instanceof Duplex;
-
- // object stream flag. Used to make read(n) ignore n and to
- // make all the buffer merging and length checks go away
- this.objectMode = !!options.objectMode;
-
- if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
-
- // the point at which it stops calling _read() to fill the buffer
- // Note: 0 is a valid value, means "don't call _read preemptively ever"
- var hwm = options.highWaterMark;
- var readableHwm = options.readableHighWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
-
- if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
-
- // cast to ints.
- this.highWaterMark = Math.floor(this.highWaterMark);
-
- // A linked list is used to store data chunks instead of an array because the
- // linked list can remove elements from the beginning faster than
- // array.shift()
- this.buffer = new BufferList();
- this.length = 0;
- this.pipes = null;
- this.pipesCount = 0;
- this.flowing = null;
- this.ended = false;
- this.endEmitted = false;
- this.reading = false;
-
- // a flag to be able to tell if the event 'readable'/'data' is emitted
- // immediately, or on a later tick. We set this to true at first, because
- // any actions that shouldn't happen until "later" should generally also
- // not happen before the first read call.
- this.sync = true;
-
- // whenever we return null, then we set a flag to say
- // that we're awaiting a 'readable' event emission.
- this.needReadable = false;
- this.emittedReadable = false;
- this.readableListening = false;
- this.resumeScheduled = false;
-
- // has it been destroyed
- this.destroyed = false;
-
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
-
- // the number of writers that are awaiting a drain event in .pipe()s
- this.awaitDrain = 0;
-
- // if true, a maybeReadMore has been scheduled
- this.readingMore = false;
-
- this.decoder = null;
- this.encoding = null;
- if (options.encoding) {
- if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
- this.decoder = new StringDecoder(options.encoding);
- this.encoding = options.encoding;
- }
-}
-
-function Readable(options) {
- Duplex = Duplex || require('./_stream_duplex');
-
- if (!(this instanceof Readable)) return new Readable(options);
-
- this._readableState = new ReadableState(options, this);
-
- // legacy
- this.readable = true;
-
- if (options) {
- if (typeof options.read === 'function') this._read = options.read;
-
- if (typeof options.destroy === 'function') this._destroy = options.destroy;
- }
-
- Stream.call(this);
-}
-
-Object.defineProperty(Readable.prototype, 'destroyed', {
- get: function () {
- if (this._readableState === undefined) {
- return false;
- }
- return this._readableState.destroyed;
- },
- set: function (value) {
- // we ignore the value if the stream
- // has not been initialized yet
- if (!this._readableState) {
- return;
- }
-
- // backward compatibility, the user is explicitly
- // managing destroyed
- this._readableState.destroyed = value;
- }
-});
-
-Readable.prototype.destroy = destroyImpl.destroy;
-Readable.prototype._undestroy = destroyImpl.undestroy;
-Readable.prototype._destroy = function (err, cb) {
- this.push(null);
- cb(err);
-};
-
-// Manually shove something into the read() buffer.
-// This returns true if the highWaterMark has not been hit yet,
-// similar to how Writable.write() returns true if you should
-// write() some more.
-Readable.prototype.push = function (chunk, encoding) {
- var state = this._readableState;
- var skipChunkCheck;
-
- if (!state.objectMode) {
- if (typeof chunk === 'string') {
- encoding = encoding || state.defaultEncoding;
- if (encoding !== state.encoding) {
- chunk = Buffer.from(chunk, encoding);
- encoding = '';
- }
- skipChunkCheck = true;
- }
- } else {
- skipChunkCheck = true;
- }
-
- return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
-};
-
-// Unshift should *always* be something directly out of read()
-Readable.prototype.unshift = function (chunk) {
- return readableAddChunk(this, chunk, null, true, false);
-};
-
-function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
- var state = stream._readableState;
- if (chunk === null) {
- state.reading = false;
- onEofChunk(stream, state);
- } else {
- var er;
- if (!skipChunkCheck) er = chunkInvalid(state, chunk);
- if (er) {
- stream.emit('error', er);
- } else if (state.objectMode || chunk && chunk.length > 0) {
- if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
- chunk = _uint8ArrayToBuffer(chunk);
- }
-
- if (addToFront) {
- if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
- } else if (state.ended) {
- stream.emit('error', new Error('stream.push() after EOF'));
- } else {
- state.reading = false;
- if (state.decoder && !encoding) {
- chunk = state.decoder.write(chunk);
- if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
- } else {
- addChunk(stream, state, chunk, false);
- }
- }
- } else if (!addToFront) {
- state.reading = false;
- }
- }
-
- return needMoreData(state);
-}
-
-function addChunk(stream, state, chunk, addToFront) {
- if (state.flowing && state.length === 0 && !state.sync) {
- stream.emit('data', chunk);
- stream.read(0);
- } else {
- // update the buffer info.
- state.length += state.objectMode ? 1 : chunk.length;
- if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
-
- if (state.needReadable) emitReadable(stream);
- }
- maybeReadMore(stream, state);
-}
-
-function chunkInvalid(state, chunk) {
- var er;
- if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
- er = new TypeError('Invalid non-string/buffer chunk');
- }
- return er;
-}
-
-// if it's past the high water mark, we can push in some more.
-// Also, if we have no data yet, we can stand some
-// more bytes. This is to work around cases where hwm=0,
-// such as the repl. Also, if the push() triggered a
-// readable event, and the user called read(largeNumber) such that
-// needReadable was set, then we ought to push more, so that another
-// 'readable' event will be triggered.
-function needMoreData(state) {
- return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
-}
-
-Readable.prototype.isPaused = function () {
- return this._readableState.flowing === false;
-};
-
-// backwards compatibility.
-Readable.prototype.setEncoding = function (enc) {
- if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
- this._readableState.decoder = new StringDecoder(enc);
- this._readableState.encoding = enc;
- return this;
-};
-
-// Don't raise the hwm > 8MB
-var MAX_HWM = 0x800000;
-function computeNewHighWaterMark(n) {
- if (n >= MAX_HWM) {
- n = MAX_HWM;
- } else {
- // Get the next highest power of 2 to prevent increasing hwm excessively in
- // tiny amounts
- n--;
- n |= n >>> 1;
- n |= n >>> 2;
- n |= n >>> 4;
- n |= n >>> 8;
- n |= n >>> 16;
- n++;
- }
- return n;
-}
-
-// This function is designed to be inlinable, so please take care when making
-// changes to the function body.
-function howMuchToRead(n, state) {
- if (n <= 0 || state.length === 0 && state.ended) return 0;
- if (state.objectMode) return 1;
- if (n !== n) {
- // Only flow one buffer at a time
- if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
- }
- // If we're asking for more than the current hwm, then raise the hwm.
- if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
- if (n <= state.length) return n;
- // Don't have enough
- if (!state.ended) {
- state.needReadable = true;
- return 0;
- }
- return state.length;
-}
-
-// you can override either this method, or the async _read(n) below.
-Readable.prototype.read = function (n) {
- debug('read', n);
- n = parseInt(n, 10);
- var state = this._readableState;
- var nOrig = n;
-
- if (n !== 0) state.emittedReadable = false;
-
- // if we're doing read(0) to trigger a readable event, but we
- // already have a bunch of data in the buffer, then just trigger
- // the 'readable' event and move on.
- if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
- debug('read: emitReadable', state.length, state.ended);
- if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
- return null;
- }
-
- n = howMuchToRead(n, state);
-
- // if we've ended, and we're now clear, then finish it up.
- if (n === 0 && state.ended) {
- if (state.length === 0) endReadable(this);
- return null;
- }
-
- // All the actual chunk generation logic needs to be
- // *below* the call to _read. The reason is that in certain
- // synthetic stream cases, such as passthrough streams, _read
- // may be a completely synchronous operation which may change
- // the state of the read buffer, providing enough data when
- // before there was *not* enough.
- //
- // So, the steps are:
- // 1. Figure out what the state of things will be after we do
- // a read from the buffer.
- //
- // 2. If that resulting state will trigger a _read, then call _read.
- // Note that this may be asynchronous, or synchronous. Yes, it is
- // deeply ugly to write APIs this way, but that still doesn't mean
- // that the Readable class should behave improperly, as streams are
- // designed to be sync/async agnostic.
- // Take note if the _read call is sync or async (ie, if the read call
- // has returned yet), so that we know whether or not it's safe to emit
- // 'readable' etc.
- //
- // 3. Actually pull the requested chunks out of the buffer and return.
-
- // if we need a readable event, then we need to do some reading.
- var doRead = state.needReadable;
- debug('need readable', doRead);
-
- // if we currently have less than the highWaterMark, then also read some
- if (state.length === 0 || state.length - n < state.highWaterMark) {
- doRead = true;
- debug('length less than watermark', doRead);
- }
-
- // however, if we've ended, then there's no point, and if we're already
- // reading, then it's unnecessary.
- if (state.ended || state.reading) {
- doRead = false;
- debug('reading or ended', doRead);
- } else if (doRead) {
- debug('do read');
- state.reading = true;
- state.sync = true;
- // if the length is currently zero, then we *need* a readable event.
- if (state.length === 0) state.needReadable = true;
- // call internal read method
- this._read(state.highWaterMark);
- state.sync = false;
- // If _read pushed data synchronously, then `reading` will be false,
- // and we need to re-evaluate how much data we can return to the user.
- if (!state.reading) n = howMuchToRead(nOrig, state);
- }
-
- var ret;
- if (n > 0) ret = fromList(n, state);else ret = null;
-
- if (ret === null) {
- state.needReadable = true;
- n = 0;
- } else {
- state.length -= n;
- }
-
- if (state.length === 0) {
- // If we have nothing in the buffer, then we want to know
- // as soon as we *do* get something into the buffer.
- if (!state.ended) state.needReadable = true;
-
- // If we tried to read() past the EOF, then emit end on the next tick.
- if (nOrig !== n && state.ended) endReadable(this);
- }
-
- if (ret !== null) this.emit('data', ret);
-
- return ret;
-};
-
-function onEofChunk(stream, state) {
- if (state.ended) return;
- if (state.decoder) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length) {
- state.buffer.push(chunk);
- state.length += state.objectMode ? 1 : chunk.length;
- }
- }
- state.ended = true;
-
- // emit 'readable' now to make sure it gets picked up.
- emitReadable(stream);
-}
-
-// Don't emit readable right away in sync mode, because this can trigger
-// another read() call => stack overflow. This way, it might trigger
-// a nextTick recursion warning, but that's not so bad.
-function emitReadable(stream) {
- var state = stream._readableState;
- state.needReadable = false;
- if (!state.emittedReadable) {
- debug('emitReadable', state.flowing);
- state.emittedReadable = true;
- if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
- }
-}
-
-function emitReadable_(stream) {
- debug('emit readable');
- stream.emit('readable');
- flow(stream);
-}
-
-// at this point, the user has presumably seen the 'readable' event,
-// and called read() to consume some data. that may have triggered
-// in turn another _read(n) call, in which case reading = true if
-// it's in progress.
-// However, if we're not ended, or reading, and the length < hwm,
-// then go ahead and try to read some more preemptively.
-function maybeReadMore(stream, state) {
- if (!state.readingMore) {
- state.readingMore = true;
- pna.nextTick(maybeReadMore_, stream, state);
- }
-}
-
-function maybeReadMore_(stream, state) {
- var len = state.length;
- while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
- debug('maybeReadMore read 0');
- stream.read(0);
- if (len === state.length)
- // didn't get any data, stop spinning.
- break;else len = state.length;
- }
- state.readingMore = false;
-}
-
-// abstract method. to be overridden in specific implementation classes.
-// call cb(er, data) where data is <= n in length.
-// for virtual (non-string, non-buffer) streams, "length" is somewhat
-// arbitrary, and perhaps not very meaningful.
-Readable.prototype._read = function (n) {
- this.emit('error', new Error('_read() is not implemented'));
-};
-
-Readable.prototype.pipe = function (dest, pipeOpts) {
- var src = this;
- var state = this._readableState;
-
- switch (state.pipesCount) {
- case 0:
- state.pipes = dest;
- break;
- case 1:
- state.pipes = [state.pipes, dest];
- break;
- default:
- state.pipes.push(dest);
- break;
- }
- state.pipesCount += 1;
- debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
-
- var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
-
- var endFn = doEnd ? onend : unpipe;
- if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
-
- dest.on('unpipe', onunpipe);
- function onunpipe(readable, unpipeInfo) {
- debug('onunpipe');
- if (readable === src) {
- if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
- unpipeInfo.hasUnpiped = true;
- cleanup();
- }
- }
- }
-
- function onend() {
- debug('onend');
- dest.end();
- }
-
- // when the dest drains, it reduces the awaitDrain counter
- // on the source. This would be more elegant with a .once()
- // handler in flow(), but adding and removing repeatedly is
- // too slow.
- var ondrain = pipeOnDrain(src);
- dest.on('drain', ondrain);
-
- var cleanedUp = false;
- function cleanup() {
- debug('cleanup');
- // cleanup event handlers once the pipe is broken
- dest.removeListener('close', onclose);
- dest.removeListener('finish', onfinish);
- dest.removeListener('drain', ondrain);
- dest.removeListener('error', onerror);
- dest.removeListener('unpipe', onunpipe);
- src.removeListener('end', onend);
- src.removeListener('end', unpipe);
- src.removeListener('data', ondata);
-
- cleanedUp = true;
-
- // if the reader is waiting for a drain event from this
- // specific writer, then it would cause it to never start
- // flowing again.
- // So, if this is awaiting a drain, then we just call it now.
- // If we don't know, then assume that we are waiting for one.
- if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
- }
-
- // If the user pushes more data while we're writing to dest then we'll end up
- // in ondata again. However, we only want to increase awaitDrain once because
- // dest will only emit one 'drain' event for the multiple writes.
- // => Introduce a guard on increasing awaitDrain.
- var increasedAwaitDrain = false;
- src.on('data', ondata);
- function ondata(chunk) {
- debug('ondata');
- increasedAwaitDrain = false;
- var ret = dest.write(chunk);
- if (false === ret && !increasedAwaitDrain) {
- // If the user unpiped during `dest.write()`, it is possible
- // to get stuck in a permanently paused state if that write
- // also returned false.
- // => Check whether `dest` is still a piping destination.
- if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
- debug('false write response, pause', src._readableState.awaitDrain);
- src._readableState.awaitDrain++;
- increasedAwaitDrain = true;
- }
- src.pause();
- }
- }
-
- // if the dest has an error, then stop piping into it.
- // however, don't suppress the throwing behavior for this.
- function onerror(er) {
- debug('onerror', er);
- unpipe();
- dest.removeListener('error', onerror);
- if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
- }
-
- // Make sure our error handler is attached before userland ones.
- prependListener(dest, 'error', onerror);
-
- // Both close and finish should trigger unpipe, but only once.
- function onclose() {
- dest.removeListener('finish', onfinish);
- unpipe();
- }
- dest.once('close', onclose);
- function onfinish() {
- debug('onfinish');
- dest.removeListener('close', onclose);
- unpipe();
- }
- dest.once('finish', onfinish);
-
- function unpipe() {
- debug('unpipe');
- src.unpipe(dest);
- }
-
- // tell the dest that it's being piped to
- dest.emit('pipe', src);
-
- // start the flow if it hasn't been started already.
- if (!state.flowing) {
- debug('pipe resume');
- src.resume();
- }
-
- return dest;
-};
-
-function pipeOnDrain(src) {
- return function () {
- var state = src._readableState;
- debug('pipeOnDrain', state.awaitDrain);
- if (state.awaitDrain) state.awaitDrain--;
- if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
- state.flowing = true;
- flow(src);
- }
- };
-}
-
-Readable.prototype.unpipe = function (dest) {
- var state = this._readableState;
- var unpipeInfo = { hasUnpiped: false };
-
- // if we're not piping anywhere, then do nothing.
- if (state.pipesCount === 0) return this;
-
- // just one destination. most common case.
- if (state.pipesCount === 1) {
- // passed in one, but it's not the right one.
- if (dest && dest !== state.pipes) return this;
-
- if (!dest) dest = state.pipes;
-
- // got a match.
- state.pipes = null;
- state.pipesCount = 0;
- state.flowing = false;
- if (dest) dest.emit('unpipe', this, unpipeInfo);
- return this;
- }
-
- // slow case. multiple pipe destinations.
-
- if (!dest) {
- // remove all.
- var dests = state.pipes;
- var len = state.pipesCount;
- state.pipes = null;
- state.pipesCount = 0;
- state.flowing = false;
-
- for (var i = 0; i < len; i++) {
- dests[i].emit('unpipe', this, unpipeInfo);
- }return this;
- }
-
- // try to find the right one.
- var index = indexOf(state.pipes, dest);
- if (index === -1) return this;
-
- state.pipes.splice(index, 1);
- state.pipesCount -= 1;
- if (state.pipesCount === 1) state.pipes = state.pipes[0];
-
- dest.emit('unpipe', this, unpipeInfo);
-
- return this;
-};
-
-// set up data events if they are asked for
-// Ensure readable listeners eventually get something
-Readable.prototype.on = function (ev, fn) {
- var res = Stream.prototype.on.call(this, ev, fn);
-
- if (ev === 'data') {
- // Start flowing on next tick if stream isn't explicitly paused
- if (this._readableState.flowing !== false) this.resume();
- } else if (ev === 'readable') {
- var state = this._readableState;
- if (!state.endEmitted && !state.readableListening) {
- state.readableListening = state.needReadable = true;
- state.emittedReadable = false;
- if (!state.reading) {
- pna.nextTick(nReadingNextTick, this);
- } else if (state.length) {
- emitReadable(this);
- }
- }
- }
-
- return res;
-};
-Readable.prototype.addListener = Readable.prototype.on;
-
-function nReadingNextTick(self) {
- debug('readable nexttick read 0');
- self.read(0);
-}
-
-// pause() and resume() are remnants of the legacy readable stream API
-// If the user uses them, then switch into old mode.
-Readable.prototype.resume = function () {
- var state = this._readableState;
- if (!state.flowing) {
- debug('resume');
- state.flowing = true;
- resume(this, state);
- }
- return this;
-};
-
-function resume(stream, state) {
- if (!state.resumeScheduled) {
- state.resumeScheduled = true;
- pna.nextTick(resume_, stream, state);
- }
-}
-
-function resume_(stream, state) {
- if (!state.reading) {
- debug('resume read 0');
- stream.read(0);
- }
-
- state.resumeScheduled = false;
- state.awaitDrain = 0;
- stream.emit('resume');
- flow(stream);
- if (state.flowing && !state.reading) stream.read(0);
-}
-
-Readable.prototype.pause = function () {
- debug('call pause flowing=%j', this._readableState.flowing);
- if (false !== this._readableState.flowing) {
- debug('pause');
- this._readableState.flowing = false;
- this.emit('pause');
- }
- return this;
-};
-
-function flow(stream) {
- var state = stream._readableState;
- debug('flow', state.flowing);
- while (state.flowing && stream.read() !== null) {}
-}
-
-// wrap an old-style stream as the async data source.
-// This is *not* part of the readable stream interface.
-// It is an ugly unfortunate mess of history.
-Readable.prototype.wrap = function (stream) {
- var _this = this;
-
- var state = this._readableState;
- var paused = false;
-
- stream.on('end', function () {
- debug('wrapped end');
- if (state.decoder && !state.ended) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length) _this.push(chunk);
- }
-
- _this.push(null);
- });
-
- stream.on('data', function (chunk) {
- debug('wrapped data');
- if (state.decoder) chunk = state.decoder.write(chunk);
-
- // don't skip over falsy values in objectMode
- if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
-
- var ret = _this.push(chunk);
- if (!ret) {
- paused = true;
- stream.pause();
- }
- });
-
- // proxy all the other methods.
- // important when wrapping filters and duplexes.
- for (var i in stream) {
- if (this[i] === undefined && typeof stream[i] === 'function') {
- this[i] = function (method) {
- return function () {
- return stream[method].apply(stream, arguments);
- };
- }(i);
- }
- }
-
- // proxy certain important events.
- for (var n = 0; n < kProxyEvents.length; n++) {
- stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
- }
-
- // when we try to consume some more bytes, simply unpause the
- // underlying stream.
- this._read = function (n) {
- debug('wrapped _read', n);
- if (paused) {
- paused = false;
- stream.resume();
- }
- };
-
- return this;
-};
-
-Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function () {
- return this._readableState.highWaterMark;
- }
-});
-
-// exposed for testing purposes only.
-Readable._fromList = fromList;
-
-// Pluck off n bytes from an array of buffers.
-// Length is the combined lengths of all the buffers in the list.
-// This function is designed to be inlinable, so please take care when making
-// changes to the function body.
-function fromList(n, state) {
- // nothing buffered
- if (state.length === 0) return null;
-
- var ret;
- if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
- // read it all, truncate the list
- if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
- state.buffer.clear();
- } else {
- // read part of list
- ret = fromListPartial(n, state.buffer, state.decoder);
- }
-
- return ret;
-}
-
-// Extracts only enough buffered data to satisfy the amount requested.
-// This function is designed to be inlinable, so please take care when making
-// changes to the function body.
-function fromListPartial(n, list, hasStrings) {
- var ret;
- if (n < list.head.data.length) {
- // slice is the same for buffers and strings
- ret = list.head.data.slice(0, n);
- list.head.data = list.head.data.slice(n);
- } else if (n === list.head.data.length) {
- // first chunk is a perfect match
- ret = list.shift();
- } else {
- // result spans more than one buffer
- ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
- }
- return ret;
-}
-
-// Copies a specified amount of characters from the list of buffered data
-// chunks.
-// This function is designed to be inlinable, so please take care when making
-// changes to the function body.
-function copyFromBufferString(n, list) {
- var p = list.head;
- var c = 1;
- var ret = p.data;
- n -= ret.length;
- while (p = p.next) {
- var str = p.data;
- var nb = n > str.length ? str.length : n;
- if (nb === str.length) ret += str;else ret += str.slice(0, n);
- n -= nb;
- if (n === 0) {
- if (nb === str.length) {
- ++c;
- if (p.next) list.head = p.next;else list.head = list.tail = null;
- } else {
- list.head = p;
- p.data = str.slice(nb);
- }
- break;
- }
- ++c;
- }
- list.length -= c;
- return ret;
-}
-
-// Copies a specified amount of bytes from the list of buffered data chunks.
-// This function is designed to be inlinable, so please take care when making
-// changes to the function body.
-function copyFromBuffer(n, list) {
- var ret = Buffer.allocUnsafe(n);
- var p = list.head;
- var c = 1;
- p.data.copy(ret);
- n -= p.data.length;
- while (p = p.next) {
- var buf = p.data;
- var nb = n > buf.length ? buf.length : n;
- buf.copy(ret, ret.length - n, 0, nb);
- n -= nb;
- if (n === 0) {
- if (nb === buf.length) {
- ++c;
- if (p.next) list.head = p.next;else list.head = list.tail = null;
- } else {
- list.head = p;
- p.data = buf.slice(nb);
- }
- break;
- }
- ++c;
- }
- list.length -= c;
- return ret;
-}
-
-function endReadable(stream) {
- var state = stream._readableState;
-
- // If we get here before consuming all the bytes, then that is a
- // bug in node. Should never happen.
- if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
-
- if (!state.endEmitted) {
- state.ended = true;
- pna.nextTick(endReadableNT, state, stream);
- }
-}
-
-function endReadableNT(state, stream) {
- // Check that we didn't get one last unshift.
- if (!state.endEmitted && state.length === 0) {
- state.endEmitted = true;
- stream.readable = false;
- stream.emit('end');
- }
-}
-
-function indexOf(xs, x) {
- for (var i = 0, l = xs.length; i < l; i++) {
- if (xs[i] === x) return i;
- }
- return -1;
-}
-}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"./_stream_duplex":71,"./internal/streams/BufferList":76,"./internal/streams/destroy":77,"./internal/streams/stream":78,"_process":69,"core-util-is":44,"events":50,"inherits":56,"isarray":58,"process-nextick-args":68,"safe-buffer":83,"string_decoder/":85,"util":40}],74:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node 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.
-
-// a transform stream is a readable/writable stream where you do
-// something with the data. Sometimes it's called a "filter",
-// but that's not a great name for it, since that implies a thing where
-// some bits pass through, and others are simply ignored. (That would
-// be a valid example of a transform, of course.)
-//
-// While the output is causally related to the input, it's not a
-// necessarily symmetric or synchronous transformation. For example,
-// a zlib stream might take multiple plain-text writes(), and then
-// emit a single compressed chunk some time in the future.
-//
-// Here's how this works:
-//
-// The Transform stream has all the aspects of the readable and writable
-// stream classes. When you write(chunk), that calls _write(chunk,cb)
-// internally, and returns false if there's a lot of pending writes
-// buffered up. When you call read(), that calls _read(n) until
-// there's enough pending readable data buffered up.
-//
-// In a transform stream, the written data is placed in a buffer. When
-// _read(n) is called, it transforms the queued up data, calling the
-// buffered _write cb's as it consumes chunks. If consuming a single
-// written chunk would result in multiple output chunks, then the first
-// outputted bit calls the readcb, and subsequent chunks just go into
-// the read buffer, and will cause it to emit 'readable' if necessary.
-//
-// This way, back-pressure is actually determined by the reading side,
-// since _read has to be called to start processing a new chunk. However,
-// a pathological inflate type of transform can cause excessive buffering
-// here. For example, imagine a stream where every byte of input is
-// interpreted as an integer from 0-255, and then results in that many
-// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
-// 1kb of data being output. In this case, you could write a very small
-// amount of input, and end up with a very large amount of output. In
-// such a pathological inflating mechanism, there'd be no way to tell
-// the system to stop doing the transform. A single 4MB write could
-// cause the system to run out of memory.
-//
-// However, even in such a pathological case, only a single written chunk
-// would be consumed, and then the rest would wait (un-transformed) until
-// the results of the previous transformed chunk were consumed.
-
-'use strict';
-
-module.exports = Transform;
-
-var Duplex = require('./_stream_duplex');
-
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/* */
-
-util.inherits(Transform, Duplex);
-
-function afterTransform(er, data) {
- var ts = this._transformState;
- ts.transforming = false;
-
- var cb = ts.writecb;
-
- if (!cb) {
- return this.emit('error', new Error('write callback called multiple times'));
- }
-
- ts.writechunk = null;
- ts.writecb = null;
-
- if (data != null) // single equals check for both `null` and `undefined`
- this.push(data);
-
- cb(er);
-
- var rs = this._readableState;
- rs.reading = false;
- if (rs.needReadable || rs.length < rs.highWaterMark) {
- this._read(rs.highWaterMark);
- }
-}
-
-function Transform(options) {
- if (!(this instanceof Transform)) return new Transform(options);
-
- Duplex.call(this, options);
-
- this._transformState = {
- afterTransform: afterTransform.bind(this),
- needTransform: false,
- transforming: false,
- writecb: null,
- writechunk: null,
- writeencoding: null
- };
-
- // start out asking for a readable event once data is transformed.
- this._readableState.needReadable = true;
-
- // we have implemented the _read method, and done the other things
- // that Readable wants before the first _read call, so unset the
- // sync guard flag.
- this._readableState.sync = false;
-
- if (options) {
- if (typeof options.transform === 'function') this._transform = options.transform;
-
- if (typeof options.flush === 'function') this._flush = options.flush;
- }
-
- // When the writable side finishes, then flush out anything remaining.
- this.on('prefinish', prefinish);
-}
-
-function prefinish() {
- var _this = this;
-
- if (typeof this._flush === 'function') {
- this._flush(function (er, data) {
- done(_this, er, data);
- });
- } else {
- done(this, null, null);
- }
-}
-
-Transform.prototype.push = function (chunk, encoding) {
- this._transformState.needTransform = false;
- return Duplex.prototype.push.call(this, chunk, encoding);
-};
-
-// This is the part where you do stuff!
-// override this function in implementation classes.
-// 'chunk' is an input chunk.
-//
-// Call `push(newChunk)` to pass along transformed output
-// to the readable side. You may call 'push' zero or more times.
-//
-// Call `cb(err)` when you are done with this chunk. If you pass
-// an error, then that'll put the hurt on the whole operation. If you
-// never call cb(), then you'll never get another chunk.
-Transform.prototype._transform = function (chunk, encoding, cb) {
- throw new Error('_transform() is not implemented');
-};
-
-Transform.prototype._write = function (chunk, encoding, cb) {
- var ts = this._transformState;
- ts.writecb = cb;
- ts.writechunk = chunk;
- ts.writeencoding = encoding;
- if (!ts.transforming) {
- var rs = this._readableState;
- if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
- }
-};
-
-// Doesn't matter what the args are here.
-// _transform does all the work.
-// That we got here means that the readable side wants more data.
-Transform.prototype._read = function (n) {
- var ts = this._transformState;
-
- if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
- ts.transforming = true;
- this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
- } else {
- // mark that we need a transform, so that any data that comes in
- // will get processed, now that we've asked for it.
- ts.needTransform = true;
- }
-};
-
-Transform.prototype._destroy = function (err, cb) {
- var _this2 = this;
-
- Duplex.prototype._destroy.call(this, err, function (err2) {
- cb(err2);
- _this2.emit('close');
- });
-};
-
-function done(stream, er, data) {
- if (er) return stream.emit('error', er);
-
- if (data != null) // single equals check for both `null` and `undefined`
- stream.push(data);
-
- // if there's nothing in the write buffer, then that means
- // that nothing more will ever be provided
- if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
-
- if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
-
- return stream.push(null);
-}
-},{"./_stream_duplex":71,"core-util-is":44,"inherits":56}],75:[function(require,module,exports){
-(function (process,global,setImmediate){
-// Copyright Joyent, Inc. and other Node 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.
-
-// A bit simpler than readable streams.
-// Implement an async ._write(chunk, encoding, cb), and it'll handle all
-// the drain event emission and buffering.
-
-'use strict';
-
-/**/
-
-var pna = require('process-nextick-args');
-/* */
-
-module.exports = Writable;
-
-/* */
-function WriteReq(chunk, encoding, cb) {
- this.chunk = chunk;
- this.encoding = encoding;
- this.callback = cb;
- this.next = null;
-}
-
-// It seems a linked list but it is not
-// there will be only 2 of these for each stream
-function CorkedRequest(state) {
- var _this = this;
-
- this.next = null;
- this.entry = null;
- this.finish = function () {
- onCorkedFinish(_this, state);
- };
-}
-/* */
-
-/**/
-var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
-/* */
-
-/**/
-var Duplex;
-/* */
-
-Writable.WritableState = WritableState;
-
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/* */
-
-/**/
-var internalUtil = {
- deprecate: require('util-deprecate')
-};
-/* */
-
-/**/
-var Stream = require('./internal/streams/stream');
-/* */
-
-/**/
-
-var Buffer = require('safe-buffer').Buffer;
-var OurUint8Array = global.Uint8Array || function () {};
-function _uint8ArrayToBuffer(chunk) {
- return Buffer.from(chunk);
-}
-function _isUint8Array(obj) {
- return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
-}
-
-/* */
-
-var destroyImpl = require('./internal/streams/destroy');
-
-util.inherits(Writable, Stream);
-
-function nop() {}
-
-function WritableState(options, stream) {
- Duplex = Duplex || require('./_stream_duplex');
-
- options = options || {};
-
- // Duplex streams are both readable and writable, but share
- // the same options object.
- // However, some cases require setting options to different
- // values for the readable and the writable sides of the duplex stream.
- // These options can be provided separately as readableXXX and writableXXX.
- var isDuplex = stream instanceof Duplex;
-
- // object stream flag to indicate whether or not this stream
- // contains buffers or objects.
- this.objectMode = !!options.objectMode;
-
- if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
-
- // the point at which write() starts returning false
- // Note: 0 is a valid value, means that we always return false if
- // the entire buffer is not flushed immediately on write()
- var hwm = options.highWaterMark;
- var writableHwm = options.writableHighWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
-
- if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
-
- // cast to ints.
- this.highWaterMark = Math.floor(this.highWaterMark);
-
- // if _final has been called
- this.finalCalled = false;
-
- // drain event flag.
- this.needDrain = false;
- // at the start of calling end()
- this.ending = false;
- // when end() has been called, and returned
- this.ended = false;
- // when 'finish' is emitted
- this.finished = false;
-
- // has it been destroyed
- this.destroyed = false;
-
- // should we decode strings into buffers before passing to _write?
- // this is here so that some node-core streams can optimize string
- // handling at a lower level.
- var noDecode = options.decodeStrings === false;
- this.decodeStrings = !noDecode;
-
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
-
- // not an actual buffer we keep track of, but a measurement
- // of how much we're waiting to get pushed to some underlying
- // socket or file.
- this.length = 0;
-
- // a flag to see when we're in the middle of a write.
- this.writing = false;
-
- // when true all writes will be buffered until .uncork() call
- this.corked = 0;
-
- // a flag to be able to tell if the onwrite cb is called immediately,
- // or on a later tick. We set this to true at first, because any
- // actions that shouldn't happen until "later" should generally also
- // not happen before the first write call.
- this.sync = true;
-
- // a flag to know if we're processing previously buffered items, which
- // may call the _write() callback in the same tick, so that we don't
- // end up in an overlapped onwrite situation.
- this.bufferProcessing = false;
-
- // the callback that's passed to _write(chunk,cb)
- this.onwrite = function (er) {
- onwrite(stream, er);
- };
-
- // the callback that the user supplies to write(chunk,encoding,cb)
- this.writecb = null;
-
- // the amount that is being written when _write is called.
- this.writelen = 0;
-
- this.bufferedRequest = null;
- this.lastBufferedRequest = null;
-
- // number of pending user-supplied write callbacks
- // this must be 0 before 'finish' can be emitted
- this.pendingcb = 0;
-
- // emit prefinish if the only thing we're waiting for is _write cbs
- // This is relevant for synchronous Transform streams
- this.prefinished = false;
-
- // True if the error was already emitted and should not be thrown again
- this.errorEmitted = false;
-
- // count buffered requests
- this.bufferedRequestCount = 0;
-
- // allocate the first CorkedRequest, there is always
- // one allocated and free to use, and we maintain at most two
- this.corkedRequestsFree = new CorkedRequest(this);
-}
-
-WritableState.prototype.getBuffer = function getBuffer() {
- var current = this.bufferedRequest;
- var out = [];
- while (current) {
- out.push(current);
- current = current.next;
- }
- return out;
-};
-
-(function () {
- try {
- Object.defineProperty(WritableState.prototype, 'buffer', {
- get: internalUtil.deprecate(function () {
- return this.getBuffer();
- }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
- });
- } catch (_) {}
-})();
-
-// Test _writableState for inheritance to account for Duplex streams,
-// whose prototype chain only points to Readable.
-var realHasInstance;
-if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
- realHasInstance = Function.prototype[Symbol.hasInstance];
- Object.defineProperty(Writable, Symbol.hasInstance, {
- value: function (object) {
- if (realHasInstance.call(this, object)) return true;
- if (this !== Writable) return false;
-
- return object && object._writableState instanceof WritableState;
- }
- });
-} else {
- realHasInstance = function (object) {
- return object instanceof this;
- };
-}
-
-function Writable(options) {
- Duplex = Duplex || require('./_stream_duplex');
-
- // Writable ctor is applied to Duplexes, too.
- // `realHasInstance` is necessary because using plain `instanceof`
- // would return false, as no `_writableState` property is attached.
-
- // Trying to use the custom `instanceof` for Writable here will also break the
- // Node.js LazyTransform implementation, which has a non-trivial getter for
- // `_writableState` that would lead to infinite recursion.
- if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
- return new Writable(options);
- }
-
- this._writableState = new WritableState(options, this);
-
- // legacy.
- this.writable = true;
-
- if (options) {
- if (typeof options.write === 'function') this._write = options.write;
-
- if (typeof options.writev === 'function') this._writev = options.writev;
-
- if (typeof options.destroy === 'function') this._destroy = options.destroy;
-
- if (typeof options.final === 'function') this._final = options.final;
- }
-
- Stream.call(this);
-}
-
-// Otherwise people can pipe Writable streams, which is just wrong.
-Writable.prototype.pipe = function () {
- this.emit('error', new Error('Cannot pipe, not readable'));
-};
-
-function writeAfterEnd(stream, cb) {
- var er = new Error('write after end');
- // TODO: defer error events consistently everywhere, not just the cb
- stream.emit('error', er);
- pna.nextTick(cb, er);
-}
-
-// Checks that a user-supplied chunk is valid, especially for the particular
-// mode the stream is in. Currently this means that `null` is never accepted
-// and undefined/non-string values are only allowed in object mode.
-function validChunk(stream, state, chunk, cb) {
- var valid = true;
- var er = false;
-
- if (chunk === null) {
- er = new TypeError('May not write null values to stream');
- } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
- er = new TypeError('Invalid non-string/buffer chunk');
- }
- if (er) {
- stream.emit('error', er);
- pna.nextTick(cb, er);
- valid = false;
- }
- return valid;
-}
-
-Writable.prototype.write = function (chunk, encoding, cb) {
- var state = this._writableState;
- var ret = false;
- var isBuf = !state.objectMode && _isUint8Array(chunk);
-
- if (isBuf && !Buffer.isBuffer(chunk)) {
- chunk = _uint8ArrayToBuffer(chunk);
- }
-
- if (typeof encoding === 'function') {
- cb = encoding;
- encoding = null;
- }
-
- if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
-
- if (typeof cb !== 'function') cb = nop;
-
- if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
- state.pendingcb++;
- ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
- }
-
- return ret;
-};
-
-Writable.prototype.cork = function () {
- var state = this._writableState;
-
- state.corked++;
-};
-
-Writable.prototype.uncork = function () {
- var state = this._writableState;
-
- if (state.corked) {
- state.corked--;
-
- if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
- }
-};
-
-Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
- // node::ParseEncoding() requires lower case.
- if (typeof encoding === 'string') encoding = encoding.toLowerCase();
- if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
- this._writableState.defaultEncoding = encoding;
- return this;
-};
-
-function decodeChunk(state, chunk, encoding) {
- if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
- chunk = Buffer.from(chunk, encoding);
- }
- return chunk;
-}
-
-Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function () {
- return this._writableState.highWaterMark;
- }
-});
-
-// if we're already writing something, then just put this
-// in the queue, and wait our turn. Otherwise, call _write
-// If we return false, then we need a drain event, so set that flag.
-function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
- if (!isBuf) {
- var newChunk = decodeChunk(state, chunk, encoding);
- if (chunk !== newChunk) {
- isBuf = true;
- encoding = 'buffer';
- chunk = newChunk;
- }
- }
- var len = state.objectMode ? 1 : chunk.length;
-
- state.length += len;
-
- var ret = state.length < state.highWaterMark;
- // we must ensure that previous needDrain will not be reset to false.
- if (!ret) state.needDrain = true;
-
- if (state.writing || state.corked) {
- var last = state.lastBufferedRequest;
- state.lastBufferedRequest = {
- chunk: chunk,
- encoding: encoding,
- isBuf: isBuf,
- callback: cb,
- next: null
- };
- if (last) {
- last.next = state.lastBufferedRequest;
- } else {
- state.bufferedRequest = state.lastBufferedRequest;
- }
- state.bufferedRequestCount += 1;
- } else {
- doWrite(stream, state, false, len, chunk, encoding, cb);
- }
-
- return ret;
-}
-
-function doWrite(stream, state, writev, len, chunk, encoding, cb) {
- state.writelen = len;
- state.writecb = cb;
- state.writing = true;
- state.sync = true;
- if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
- state.sync = false;
-}
-
-function onwriteError(stream, state, sync, er, cb) {
- --state.pendingcb;
-
- if (sync) {
- // defer the callback if we are being called synchronously
- // to avoid piling up things on the stack
- pna.nextTick(cb, er);
- // this can emit finish, and it will always happen
- // after error
- pna.nextTick(finishMaybe, stream, state);
- stream._writableState.errorEmitted = true;
- stream.emit('error', er);
- } else {
- // the caller expect this to happen before if
- // it is async
- cb(er);
- stream._writableState.errorEmitted = true;
- stream.emit('error', er);
- // this can emit finish, but finish must
- // always follow error
- finishMaybe(stream, state);
- }
-}
-
-function onwriteStateUpdate(state) {
- state.writing = false;
- state.writecb = null;
- state.length -= state.writelen;
- state.writelen = 0;
-}
-
-function onwrite(stream, er) {
- var state = stream._writableState;
- var sync = state.sync;
- var cb = state.writecb;
-
- onwriteStateUpdate(state);
-
- if (er) onwriteError(stream, state, sync, er, cb);else {
- // Check if we're actually ready to finish, but don't emit yet
- var finished = needFinish(state);
-
- if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
- clearBuffer(stream, state);
- }
-
- if (sync) {
- /**/
- asyncWrite(afterWrite, stream, state, finished, cb);
- /* */
- } else {
- afterWrite(stream, state, finished, cb);
- }
- }
-}
-
-function afterWrite(stream, state, finished, cb) {
- if (!finished) onwriteDrain(stream, state);
- state.pendingcb--;
- cb();
- finishMaybe(stream, state);
-}
-
-// Must force callback to be called on nextTick, so that we don't
-// emit 'drain' before the write() consumer gets the 'false' return
-// value, and has a chance to attach a 'drain' listener.
-function onwriteDrain(stream, state) {
- if (state.length === 0 && state.needDrain) {
- state.needDrain = false;
- stream.emit('drain');
- }
-}
-
-// if there's something in the buffer waiting, then process it
-function clearBuffer(stream, state) {
- state.bufferProcessing = true;
- var entry = state.bufferedRequest;
-
- if (stream._writev && entry && entry.next) {
- // Fast case, write everything using _writev()
- var l = state.bufferedRequestCount;
- var buffer = new Array(l);
- var holder = state.corkedRequestsFree;
- holder.entry = entry;
-
- var count = 0;
- var allBuffers = true;
- while (entry) {
- buffer[count] = entry;
- if (!entry.isBuf) allBuffers = false;
- entry = entry.next;
- count += 1;
- }
- buffer.allBuffers = allBuffers;
-
- doWrite(stream, state, true, state.length, buffer, '', holder.finish);
-
- // doWrite is almost always async, defer these to save a bit of time
- // as the hot path ends with doWrite
- state.pendingcb++;
- state.lastBufferedRequest = null;
- if (holder.next) {
- state.corkedRequestsFree = holder.next;
- holder.next = null;
- } else {
- state.corkedRequestsFree = new CorkedRequest(state);
- }
- state.bufferedRequestCount = 0;
- } else {
- // Slow case, write chunks one-by-one
- while (entry) {
- var chunk = entry.chunk;
- var encoding = entry.encoding;
- var cb = entry.callback;
- var len = state.objectMode ? 1 : chunk.length;
-
- doWrite(stream, state, false, len, chunk, encoding, cb);
- entry = entry.next;
- state.bufferedRequestCount--;
- // if we didn't call the onwrite immediately, then
- // it means that we need to wait until it does.
- // also, that means that the chunk and cb are currently
- // being processed, so move the buffer counter past them.
- if (state.writing) {
- break;
- }
- }
-
- if (entry === null) state.lastBufferedRequest = null;
- }
-
- state.bufferedRequest = entry;
- state.bufferProcessing = false;
-}
-
-Writable.prototype._write = function (chunk, encoding, cb) {
- cb(new Error('_write() is not implemented'));
-};
-
-Writable.prototype._writev = null;
-
-Writable.prototype.end = function (chunk, encoding, cb) {
- var state = this._writableState;
-
- if (typeof chunk === 'function') {
- cb = chunk;
- chunk = null;
- encoding = null;
- } else if (typeof encoding === 'function') {
- cb = encoding;
- encoding = null;
- }
-
- if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
-
- // .end() fully uncorks
- if (state.corked) {
- state.corked = 1;
- this.uncork();
- }
-
- // ignore unnecessary end() calls.
- if (!state.ending && !state.finished) endWritable(this, state, cb);
-};
-
-function needFinish(state) {
- return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
-}
-function callFinal(stream, state) {
- stream._final(function (err) {
- state.pendingcb--;
- if (err) {
- stream.emit('error', err);
- }
- state.prefinished = true;
- stream.emit('prefinish');
- finishMaybe(stream, state);
- });
-}
-function prefinish(stream, state) {
- if (!state.prefinished && !state.finalCalled) {
- if (typeof stream._final === 'function') {
- state.pendingcb++;
- state.finalCalled = true;
- pna.nextTick(callFinal, stream, state);
- } else {
- state.prefinished = true;
- stream.emit('prefinish');
- }
- }
-}
-
-function finishMaybe(stream, state) {
- var need = needFinish(state);
- if (need) {
- prefinish(stream, state);
- if (state.pendingcb === 0) {
- state.finished = true;
- stream.emit('finish');
- }
- }
- return need;
-}
-
-function endWritable(stream, state, cb) {
- state.ending = true;
- finishMaybe(stream, state);
- if (cb) {
- if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
- }
- state.ended = true;
- stream.writable = false;
-}
-
-function onCorkedFinish(corkReq, state, err) {
- var entry = corkReq.entry;
- corkReq.entry = null;
- while (entry) {
- var cb = entry.callback;
- state.pendingcb--;
- cb(err);
- entry = entry.next;
- }
- if (state.corkedRequestsFree) {
- state.corkedRequestsFree.next = corkReq;
- } else {
- state.corkedRequestsFree = corkReq;
- }
-}
-
-Object.defineProperty(Writable.prototype, 'destroyed', {
- get: function () {
- if (this._writableState === undefined) {
- return false;
- }
- return this._writableState.destroyed;
- },
- set: function (value) {
- // we ignore the value if the stream
- // has not been initialized yet
- if (!this._writableState) {
- return;
- }
-
- // backward compatibility, the user is explicitly
- // managing destroyed
- this._writableState.destroyed = value;
- }
-});
-
-Writable.prototype.destroy = destroyImpl.destroy;
-Writable.prototype._undestroy = destroyImpl.undestroy;
-Writable.prototype._destroy = function (err, cb) {
- this.end();
- cb(err);
-};
-}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
-},{"./_stream_duplex":71,"./internal/streams/destroy":77,"./internal/streams/stream":78,"_process":69,"core-util-is":44,"inherits":56,"process-nextick-args":68,"safe-buffer":83,"timers":86,"util-deprecate":87}],76:[function(require,module,exports){
-'use strict';
-
-function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-var Buffer = require('safe-buffer').Buffer;
-var util = require('util');
-
-function copyBuffer(src, target, offset) {
- src.copy(target, offset);
-}
-
-module.exports = function () {
- function BufferList() {
- _classCallCheck(this, BufferList);
-
- this.head = null;
- this.tail = null;
- this.length = 0;
- }
-
- BufferList.prototype.push = function push(v) {
- var entry = { data: v, next: null };
- if (this.length > 0) this.tail.next = entry;else this.head = entry;
- this.tail = entry;
- ++this.length;
- };
-
- BufferList.prototype.unshift = function unshift(v) {
- var entry = { data: v, next: this.head };
- if (this.length === 0) this.tail = entry;
- this.head = entry;
- ++this.length;
- };
-
- BufferList.prototype.shift = function shift() {
- if (this.length === 0) return;
- var ret = this.head.data;
- if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
- --this.length;
- return ret;
- };
-
- BufferList.prototype.clear = function clear() {
- this.head = this.tail = null;
- this.length = 0;
- };
-
- BufferList.prototype.join = function join(s) {
- if (this.length === 0) return '';
- var p = this.head;
- var ret = '' + p.data;
- while (p = p.next) {
- ret += s + p.data;
- }return ret;
- };
-
- BufferList.prototype.concat = function concat(n) {
- if (this.length === 0) return Buffer.alloc(0);
- if (this.length === 1) return this.head.data;
- var ret = Buffer.allocUnsafe(n >>> 0);
- var p = this.head;
- var i = 0;
- while (p) {
- copyBuffer(p.data, ret, i);
- i += p.data.length;
- p = p.next;
- }
- return ret;
- };
-
- return BufferList;
-}();
-
-if (util && util.inspect && util.inspect.custom) {
- module.exports.prototype[util.inspect.custom] = function () {
- var obj = util.inspect({ length: this.length });
- return this.constructor.name + ' ' + obj;
- };
-}
-},{"safe-buffer":83,"util":40}],77:[function(require,module,exports){
-'use strict';
-
-/**/
-
-var pna = require('process-nextick-args');
-/* */
-
-// undocumented cb() API, needed for core, not for public API
-function destroy(err, cb) {
- var _this = this;
-
- var readableDestroyed = this._readableState && this._readableState.destroyed;
- var writableDestroyed = this._writableState && this._writableState.destroyed;
-
- if (readableDestroyed || writableDestroyed) {
- if (cb) {
- cb(err);
- } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
- pna.nextTick(emitErrorNT, this, err);
- }
- return this;
- }
-
- // we set destroyed to true before firing error callbacks in order
- // to make it re-entrance safe in case destroy() is called within callbacks
-
- if (this._readableState) {
- this._readableState.destroyed = true;
- }
-
- // if this is a duplex stream mark the writable part as destroyed as well
- if (this._writableState) {
- this._writableState.destroyed = true;
- }
-
- this._destroy(err || null, function (err) {
- if (!cb && err) {
- pna.nextTick(emitErrorNT, _this, err);
- if (_this._writableState) {
- _this._writableState.errorEmitted = true;
- }
- } else if (cb) {
- cb(err);
- }
- });
-
- return this;
-}
-
-function undestroy() {
- if (this._readableState) {
- this._readableState.destroyed = false;
- this._readableState.reading = false;
- this._readableState.ended = false;
- this._readableState.endEmitted = false;
- }
-
- if (this._writableState) {
- this._writableState.destroyed = false;
- this._writableState.ended = false;
- this._writableState.ending = false;
- this._writableState.finished = false;
- this._writableState.errorEmitted = false;
- }
-}
-
-function emitErrorNT(self, err) {
- self.emit('error', err);
-}
-
-module.exports = {
- destroy: destroy,
- undestroy: undestroy
-};
-},{"process-nextick-args":68}],78:[function(require,module,exports){
-module.exports = require('events').EventEmitter;
-
-},{"events":50}],79:[function(require,module,exports){
-module.exports = require('./readable').PassThrough
-
-},{"./readable":80}],80:[function(require,module,exports){
-exports = module.exports = require('./lib/_stream_readable.js');
-exports.Stream = exports;
-exports.Readable = exports;
-exports.Writable = require('./lib/_stream_writable.js');
-exports.Duplex = require('./lib/_stream_duplex.js');
-exports.Transform = require('./lib/_stream_transform.js');
-exports.PassThrough = require('./lib/_stream_passthrough.js');
-
-},{"./lib/_stream_duplex.js":71,"./lib/_stream_passthrough.js":72,"./lib/_stream_readable.js":73,"./lib/_stream_transform.js":74,"./lib/_stream_writable.js":75}],81:[function(require,module,exports){
-module.exports = require('./readable').Transform
-
-},{"./readable":80}],82:[function(require,module,exports){
-module.exports = require('./lib/_stream_writable.js');
-
-},{"./lib/_stream_writable.js":75}],83:[function(require,module,exports){
-/* eslint-disable node/no-deprecated-api */
-var buffer = require('buffer')
-var Buffer = buffer.Buffer
-
-// alternative to using Object.keys for old browsers
-function copyProps (src, dst) {
- for (var key in src) {
- dst[key] = src[key]
- }
-}
-if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
- module.exports = buffer
-} else {
- // Copy properties from require('buffer')
- copyProps(buffer, exports)
- exports.Buffer = SafeBuffer
-}
-
-function SafeBuffer (arg, encodingOrOffset, length) {
- return Buffer(arg, encodingOrOffset, length)
-}
-
-// Copy static methods from Buffer
-copyProps(Buffer, SafeBuffer)
-
-SafeBuffer.from = function (arg, encodingOrOffset, length) {
- if (typeof arg === 'number') {
- throw new TypeError('Argument must not be a number')
- }
- return Buffer(arg, encodingOrOffset, length)
-}
-
-SafeBuffer.alloc = function (size, fill, encoding) {
- if (typeof size !== 'number') {
- throw new TypeError('Argument must be a number')
- }
- var buf = Buffer(size)
- if (fill !== undefined) {
- if (typeof encoding === 'string') {
- buf.fill(fill, encoding)
- } else {
- buf.fill(fill)
- }
- } else {
- buf.fill(0)
- }
- return buf
-}
-
-SafeBuffer.allocUnsafe = function (size) {
- if (typeof size !== 'number') {
- throw new TypeError('Argument must be a number')
- }
- return Buffer(size)
-}
-
-SafeBuffer.allocUnsafeSlow = function (size) {
- if (typeof size !== 'number') {
- throw new TypeError('Argument must be a number')
- }
- return buffer.SlowBuffer(size)
-}
-
-},{"buffer":43}],84:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node 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.
-
-module.exports = Stream;
-
-var EE = require('events').EventEmitter;
-var inherits = require('inherits');
-
-inherits(Stream, EE);
-Stream.Readable = require('readable-stream/readable.js');
-Stream.Writable = require('readable-stream/writable.js');
-Stream.Duplex = require('readable-stream/duplex.js');
-Stream.Transform = require('readable-stream/transform.js');
-Stream.PassThrough = require('readable-stream/passthrough.js');
-
-// Backwards-compat with node 0.4.x
-Stream.Stream = Stream;
-
-
-
-// old-style streams. Note that the pipe method (the only relevant
-// part of this class) is overridden in the Readable class.
-
-function Stream() {
- EE.call(this);
-}
-
-Stream.prototype.pipe = function(dest, options) {
- var source = this;
-
- function ondata(chunk) {
- if (dest.writable) {
- if (false === dest.write(chunk) && source.pause) {
- source.pause();
- }
- }
- }
-
- source.on('data', ondata);
-
- function ondrain() {
- if (source.readable && source.resume) {
- source.resume();
- }
- }
-
- dest.on('drain', ondrain);
-
- // If the 'end' option is not supplied, dest.end() will be called when
- // source gets the 'end' or 'close' events. Only dest.end() once.
- if (!dest._isStdio && (!options || options.end !== false)) {
- source.on('end', onend);
- source.on('close', onclose);
- }
-
- var didOnEnd = false;
- function onend() {
- if (didOnEnd) return;
- didOnEnd = true;
-
- dest.end();
- }
-
-
- function onclose() {
- if (didOnEnd) return;
- didOnEnd = true;
-
- if (typeof dest.destroy === 'function') dest.destroy();
- }
-
- // don't leave dangling pipes when there are errors.
- function onerror(er) {
- cleanup();
- if (EE.listenerCount(this, 'error') === 0) {
- throw er; // Unhandled stream error in pipe.
- }
- }
-
- source.on('error', onerror);
- dest.on('error', onerror);
-
- // remove all the event listeners that were added.
- function cleanup() {
- source.removeListener('data', ondata);
- dest.removeListener('drain', ondrain);
-
- source.removeListener('end', onend);
- source.removeListener('close', onclose);
-
- source.removeListener('error', onerror);
- dest.removeListener('error', onerror);
-
- source.removeListener('end', cleanup);
- source.removeListener('close', cleanup);
-
- dest.removeListener('close', cleanup);
- }
-
- source.on('end', cleanup);
- source.on('close', cleanup);
-
- dest.on('close', cleanup);
-
- dest.emit('pipe', source);
-
- // Allow for unix-like usage: A.pipe(B).pipe(C)
- return dest;
-};
-
-},{"events":50,"inherits":56,"readable-stream/duplex.js":70,"readable-stream/passthrough.js":79,"readable-stream/readable.js":80,"readable-stream/transform.js":81,"readable-stream/writable.js":82}],85:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node 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.
-
-'use strict';
-
-/**/
-
-var Buffer = require('safe-buffer').Buffer;
-/* */
-
-var isEncoding = Buffer.isEncoding || function (encoding) {
- encoding = '' + encoding;
- switch (encoding && encoding.toLowerCase()) {
- case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
- return true;
- default:
- return false;
- }
-};
-
-function _normalizeEncoding(enc) {
- if (!enc) return 'utf8';
- var retried;
- while (true) {
- switch (enc) {
- case 'utf8':
- case 'utf-8':
- return 'utf8';
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return 'utf16le';
- case 'latin1':
- case 'binary':
- return 'latin1';
- case 'base64':
- case 'ascii':
- case 'hex':
- return enc;
- default:
- if (retried) return; // undefined
- enc = ('' + enc).toLowerCase();
- retried = true;
- }
- }
-};
-
-// Do not cache `Buffer.isEncoding` when checking encoding names as some
-// modules monkey-patch it to support additional encodings
-function normalizeEncoding(enc) {
- var nenc = _normalizeEncoding(enc);
- if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
- return nenc || enc;
-}
-
-// StringDecoder provides an interface for efficiently splitting a series of
-// buffers into a series of JS strings without breaking apart multi-byte
-// characters.
-exports.StringDecoder = StringDecoder;
-function StringDecoder(encoding) {
- this.encoding = normalizeEncoding(encoding);
- var nb;
- switch (this.encoding) {
- case 'utf16le':
- this.text = utf16Text;
- this.end = utf16End;
- nb = 4;
- break;
- case 'utf8':
- this.fillLast = utf8FillLast;
- nb = 4;
- break;
- case 'base64':
- this.text = base64Text;
- this.end = base64End;
- nb = 3;
- break;
- default:
- this.write = simpleWrite;
- this.end = simpleEnd;
- return;
- }
- this.lastNeed = 0;
- this.lastTotal = 0;
- this.lastChar = Buffer.allocUnsafe(nb);
-}
-
-StringDecoder.prototype.write = function (buf) {
- if (buf.length === 0) return '';
- var r;
- var i;
- if (this.lastNeed) {
- r = this.fillLast(buf);
- if (r === undefined) return '';
- i = this.lastNeed;
- this.lastNeed = 0;
- } else {
- i = 0;
- }
- if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
- return r || '';
-};
-
-StringDecoder.prototype.end = utf8End;
-
-// Returns only complete characters in a Buffer
-StringDecoder.prototype.text = utf8Text;
-
-// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
-StringDecoder.prototype.fillLast = function (buf) {
- if (this.lastNeed <= buf.length) {
- buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
- return this.lastChar.toString(this.encoding, 0, this.lastTotal);
- }
- buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
- this.lastNeed -= buf.length;
-};
-
-// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
-// continuation byte. If an invalid byte is detected, -2 is returned.
-function utf8CheckByte(byte) {
- if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
- return byte >> 6 === 0x02 ? -1 : -2;
-}
-
-// Checks at most 3 bytes at the end of a Buffer in order to detect an
-// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
-// needed to complete the UTF-8 character (if applicable) are returned.
-function utf8CheckIncomplete(self, buf, i) {
- var j = buf.length - 1;
- if (j < i) return 0;
- var nb = utf8CheckByte(buf[j]);
- if (nb >= 0) {
- if (nb > 0) self.lastNeed = nb - 1;
- return nb;
- }
- if (--j < i || nb === -2) return 0;
- nb = utf8CheckByte(buf[j]);
- if (nb >= 0) {
- if (nb > 0) self.lastNeed = nb - 2;
- return nb;
- }
- if (--j < i || nb === -2) return 0;
- nb = utf8CheckByte(buf[j]);
- if (nb >= 0) {
- if (nb > 0) {
- if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
- }
- return nb;
- }
- return 0;
-}
-
-// Validates as many continuation bytes for a multi-byte UTF-8 character as
-// needed or are available. If we see a non-continuation byte where we expect
-// one, we "replace" the validated continuation bytes we've seen so far with
-// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
-// behavior. The continuation byte check is included three times in the case
-// where all of the continuation bytes for a character exist in the same buffer.
-// It is also done this way as a slight performance increase instead of using a
-// loop.
-function utf8CheckExtraBytes(self, buf, p) {
- if ((buf[0] & 0xC0) !== 0x80) {
- self.lastNeed = 0;
- return '\ufffd';
- }
- if (self.lastNeed > 1 && buf.length > 1) {
- if ((buf[1] & 0xC0) !== 0x80) {
- self.lastNeed = 1;
- return '\ufffd';
- }
- if (self.lastNeed > 2 && buf.length > 2) {
- if ((buf[2] & 0xC0) !== 0x80) {
- self.lastNeed = 2;
- return '\ufffd';
- }
- }
- }
-}
-
-// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
-function utf8FillLast(buf) {
- var p = this.lastTotal - this.lastNeed;
- var r = utf8CheckExtraBytes(this, buf, p);
- if (r !== undefined) return r;
- if (this.lastNeed <= buf.length) {
- buf.copy(this.lastChar, p, 0, this.lastNeed);
- return this.lastChar.toString(this.encoding, 0, this.lastTotal);
- }
- buf.copy(this.lastChar, p, 0, buf.length);
- this.lastNeed -= buf.length;
-}
-
-// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
-// partial character, the character's bytes are buffered until the required
-// number of bytes are available.
-function utf8Text(buf, i) {
- var total = utf8CheckIncomplete(this, buf, i);
- if (!this.lastNeed) return buf.toString('utf8', i);
- this.lastTotal = total;
- var end = buf.length - (total - this.lastNeed);
- buf.copy(this.lastChar, 0, end);
- return buf.toString('utf8', i, end);
-}
-
-// For UTF-8, a replacement character is added when ending on a partial
-// character.
-function utf8End(buf) {
- var r = buf && buf.length ? this.write(buf) : '';
- if (this.lastNeed) return r + '\ufffd';
- return r;
-}
-
-// UTF-16LE typically needs two bytes per character, but even if we have an even
-// number of bytes available, we need to check if we end on a leading/high
-// surrogate. In that case, we need to wait for the next two bytes in order to
-// decode the last character properly.
-function utf16Text(buf, i) {
- if ((buf.length - i) % 2 === 0) {
- var r = buf.toString('utf16le', i);
- if (r) {
- var c = r.charCodeAt(r.length - 1);
- if (c >= 0xD800 && c <= 0xDBFF) {
- this.lastNeed = 2;
- this.lastTotal = 4;
- this.lastChar[0] = buf[buf.length - 2];
- this.lastChar[1] = buf[buf.length - 1];
- return r.slice(0, -1);
- }
- }
- return r;
- }
- this.lastNeed = 1;
- this.lastTotal = 2;
- this.lastChar[0] = buf[buf.length - 1];
- return buf.toString('utf16le', i, buf.length - 1);
-}
-
-// For UTF-16LE we do not explicitly append special replacement characters if we
-// end on a partial character, we simply let v8 handle that.
-function utf16End(buf) {
- var r = buf && buf.length ? this.write(buf) : '';
- if (this.lastNeed) {
- var end = this.lastTotal - this.lastNeed;
- return r + this.lastChar.toString('utf16le', 0, end);
- }
- return r;
-}
-
-function base64Text(buf, i) {
- var n = (buf.length - i) % 3;
- if (n === 0) return buf.toString('base64', i);
- this.lastNeed = 3 - n;
- this.lastTotal = 3;
- if (n === 1) {
- this.lastChar[0] = buf[buf.length - 1];
- } else {
- this.lastChar[0] = buf[buf.length - 2];
- this.lastChar[1] = buf[buf.length - 1];
- }
- return buf.toString('base64', i, buf.length - n);
-}
-
-function base64End(buf) {
- var r = buf && buf.length ? this.write(buf) : '';
- if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
- return r;
-}
-
-// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
-function simpleWrite(buf) {
- return buf.toString(this.encoding);
-}
-
-function simpleEnd(buf) {
- return buf && buf.length ? this.write(buf) : '';
-}
-},{"safe-buffer":83}],86:[function(require,module,exports){
-(function (setImmediate,clearImmediate){
-var nextTick = require('process/browser.js').nextTick;
-var apply = Function.prototype.apply;
-var slice = Array.prototype.slice;
-var immediateIds = {};
-var nextImmediateId = 0;
-
-// DOM APIs, for completeness
-
-exports.setTimeout = function() {
- return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
-};
-exports.setInterval = function() {
- return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
-};
-exports.clearTimeout =
-exports.clearInterval = function(timeout) { timeout.close(); };
-
-function Timeout(id, clearFn) {
- this._id = id;
- this._clearFn = clearFn;
-}
-Timeout.prototype.unref = Timeout.prototype.ref = function() {};
-Timeout.prototype.close = function() {
- this._clearFn.call(window, this._id);
-};
-
-// Does not start the time, just sets up the members needed.
-exports.enroll = function(item, msecs) {
- clearTimeout(item._idleTimeoutId);
- item._idleTimeout = msecs;
-};
-
-exports.unenroll = function(item) {
- clearTimeout(item._idleTimeoutId);
- item._idleTimeout = -1;
-};
-
-exports._unrefActive = exports.active = function(item) {
- clearTimeout(item._idleTimeoutId);
-
- var msecs = item._idleTimeout;
- if (msecs >= 0) {
- item._idleTimeoutId = setTimeout(function onTimeout() {
- if (item._onTimeout)
- item._onTimeout();
- }, msecs);
- }
-};
-
-// That's not how node.js implements it but the exposed api is the same.
-exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
- var id = nextImmediateId++;
- var args = arguments.length < 2 ? false : slice.call(arguments, 1);
-
- immediateIds[id] = true;
-
- nextTick(function onNextTick() {
- if (immediateIds[id]) {
- // fn.call() is faster so we optimize for the common use-case
- // @see http://jsperf.com/call-apply-segu
- if (args) {
- fn.apply(null, args);
- } else {
- fn.call(null);
- }
- // Prevent ids from leaking
- exports.clearImmediate(id);
- }
- });
-
- return id;
-};
-
-exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
- delete immediateIds[id];
-};
-}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
-},{"process/browser.js":69,"timers":86}],87:[function(require,module,exports){
-(function (global){
-
-/**
- * Module exports.
- */
-
-module.exports = deprecate;
-
-/**
- * Mark that a method should not be used.
- * Returns a modified function which warns once by default.
- *
- * If `localStorage.noDeprecation = true` is set, then it is a no-op.
- *
- * If `localStorage.throwDeprecation = true` is set, then deprecated functions
- * will throw an Error when invoked.
- *
- * If `localStorage.traceDeprecation = true` is set, then deprecated functions
- * will invoke `console.trace()` instead of `console.error()`.
- *
- * @param {Function} fn - the function to deprecate
- * @param {String} msg - the string to print to the console when `fn` is invoked
- * @returns {Function} a new "deprecated" version of `fn`
- * @api public
- */
-
-function deprecate (fn, msg) {
- if (config('noDeprecation')) {
- return fn;
- }
-
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (config('throwDeprecation')) {
- throw new Error(msg);
- } else if (config('traceDeprecation')) {
- console.trace(msg);
- } else {
- console.warn(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
- }
-
- return deprecated;
-}
-
-/**
- * Checks `localStorage` for boolean values for the given `name`.
- *
- * @param {String} name
- * @returns {Boolean}
- * @api private
- */
-
-function config (name) {
- // accessing global.localStorage can trigger a DOMException in sandboxed iframes
- try {
- if (!global.localStorage) return false;
- } catch (_) {
- return false;
- }
- var val = global.localStorage[name];
- if (null == val) return false;
- return String(val).toLowerCase() === 'true';
-}
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],88:[function(require,module,exports){
-module.exports = function isBuffer(arg) {
- return arg && typeof arg === 'object'
- && typeof arg.copy === 'function'
- && typeof arg.fill === 'function'
- && typeof arg.readUInt8 === 'function';
-}
-},{}],89:[function(require,module,exports){
-(function (process,global){
-// Copyright Joyent, Inc. and other Node 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.
-
-var formatRegExp = /%[sdj%]/g;
-exports.format = function(f) {
- if (!isString(f)) {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(inspect(arguments[i]));
- }
- return objects.join(' ');
- }
-
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j':
- try {
- return JSON.stringify(args[i++]);
- } catch (_) {
- return '[Circular]';
- }
- default:
- return x;
- }
- });
- for (var x = args[i]; i < len; x = args[++i]) {
- if (isNull(x) || !isObject(x)) {
- str += ' ' + x;
- } else {
- str += ' ' + inspect(x);
- }
- }
- return str;
-};
-
-
-// Mark that a method should not be used.
-// Returns a modified function which warns once by default.
-// If --no-deprecation is set, then it is a no-op.
-exports.deprecate = function(fn, msg) {
- // Allow for deprecating things in the process of starting up.
- if (isUndefined(global.process)) {
- return function() {
- return exports.deprecate(fn, msg).apply(this, arguments);
- };
- }
-
- if (process.noDeprecation === true) {
- return fn;
- }
-
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (process.throwDeprecation) {
- throw new Error(msg);
- } else if (process.traceDeprecation) {
- console.trace(msg);
- } else {
- console.error(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
- }
-
- return deprecated;
-};
-
-
-var debugs = {};
-var debugEnviron;
-exports.debuglog = function(set) {
- if (isUndefined(debugEnviron))
- debugEnviron = process.env.NODE_DEBUG || '';
- set = set.toUpperCase();
- if (!debugs[set]) {
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
- var pid = process.pid;
- debugs[set] = function() {
- var msg = exports.format.apply(exports, arguments);
- console.error('%s %d: %s', set, pid, msg);
- };
- } else {
- debugs[set] = function() {};
- }
- }
- return debugs[set];
-};
-
-
-/**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Object} opts Optional options object that alters the output.
- */
-/* legacy: obj, showHidden, depth, colors*/
-function inspect(obj, opts) {
- // default options
- var ctx = {
- seen: [],
- stylize: stylizeNoColor
- };
- // legacy...
- if (arguments.length >= 3) ctx.depth = arguments[2];
- if (arguments.length >= 4) ctx.colors = arguments[3];
- if (isBoolean(opts)) {
- // legacy...
- ctx.showHidden = opts;
- } else if (opts) {
- // got an "options" object
- exports._extend(ctx, opts);
- }
- // set default options
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
- if (isUndefined(ctx.depth)) ctx.depth = 2;
- if (isUndefined(ctx.colors)) ctx.colors = false;
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
- if (ctx.colors) ctx.stylize = stylizeWithColor;
- return formatValue(ctx, obj, ctx.depth);
-}
-exports.inspect = inspect;
-
-
-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
-inspect.colors = {
- 'bold' : [1, 22],
- 'italic' : [3, 23],
- 'underline' : [4, 24],
- 'inverse' : [7, 27],
- 'white' : [37, 39],
- 'grey' : [90, 39],
- 'black' : [30, 39],
- 'blue' : [34, 39],
- 'cyan' : [36, 39],
- 'green' : [32, 39],
- 'magenta' : [35, 39],
- 'red' : [31, 39],
- 'yellow' : [33, 39]
-};
-
-// Don't use 'blue' not visible on cmd.exe
-inspect.styles = {
- 'special': 'cyan',
- 'number': 'yellow',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red'
-};
-
-
-function stylizeWithColor(str, styleType) {
- var style = inspect.styles[styleType];
-
- if (style) {
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
- '\u001b[' + inspect.colors[style][1] + 'm';
- } else {
- return str;
- }
-}
-
-
-function stylizeNoColor(str, styleType) {
- return str;
-}
-
-
-function arrayToHash(array) {
- var hash = {};
-
- array.forEach(function(val, idx) {
- hash[val] = true;
- });
-
- return hash;
-}
-
-
-function formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (ctx.customInspect &&
- value &&
- isFunction(value.inspect) &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes, ctx);
- if (!isString(ret)) {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
- }
-
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
- }
-
- // Look up the keys of the object.
- var keys = Object.keys(value);
- var visibleKeys = arrayToHash(keys);
-
- if (ctx.showHidden) {
- keys = Object.getOwnPropertyNames(value);
- }
-
- // IE doesn't make error fields non-enumerable
- // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
- if (isError(value)
- && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
- return formatError(value);
- }
-
- // Some type of object without properties can be shortcutted.
- if (keys.length === 0) {
- if (isFunction(value)) {
- var name = value.name ? ': ' + value.name : '';
- return ctx.stylize('[Function' + name + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
- }
- }
-
- var base = '', array = false, braces = ['{', '}'];
-
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
- }
-
- // Make functions say that they are functions
- if (isFunction(value)) {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
- }
-
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
- }
-
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
-
- // Make error with message first say the error
- if (isError(value)) {
- base = ' ' + formatError(value);
- }
-
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
-
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
- }
- }
-
- ctx.seen.push(value);
-
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
-
- ctx.seen.pop();
-
- return reduceToSingleString(output, base, braces);
-}
-
-
-function formatPrimitive(ctx, value) {
- if (isUndefined(value))
- return ctx.stylize('undefined', 'undefined');
- if (isString(value)) {
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
- }
- if (isNumber(value))
- return ctx.stylize('' + value, 'number');
- if (isBoolean(value))
- return ctx.stylize('' + value, 'boolean');
- // For some reason typeof null is "object", so special case here.
- if (isNull(value))
- return ctx.stylize('null', 'null');
-}
-
-
-function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
-}
-
-
-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (hasOwnProperty(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
-}
-
-
-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str, desc;
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
- if (desc.get) {
- if (desc.set) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (desc.set) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- if (!hasOwnProperty(visibleKeys, key)) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(desc.value) < 0) {
- if (isNull(recurseTimes)) {
- str = formatValue(ctx, desc.value, null);
- } else {
- str = formatValue(ctx, desc.value, recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
- }
- if (isUndefined(name)) {
- if (array && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
- }
- }
-
- return name + ': ' + str;
-}
-
-
-function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
- }, 0);
-
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
- }
-
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
-}
-
-
-// NOTE: These type checking functions intentionally don't use `instanceof`
-// because it is fragile and can be easily faked with `Object.create()`.
-function isArray(ar) {
- return Array.isArray(ar);
-}
-exports.isArray = isArray;
-
-function isBoolean(arg) {
- return typeof arg === 'boolean';
-}
-exports.isBoolean = isBoolean;
-
-function isNull(arg) {
- return arg === null;
-}
-exports.isNull = isNull;
-
-function isNullOrUndefined(arg) {
- return arg == null;
-}
-exports.isNullOrUndefined = isNullOrUndefined;
-
-function isNumber(arg) {
- return typeof arg === 'number';
-}
-exports.isNumber = isNumber;
-
-function isString(arg) {
- return typeof arg === 'string';
-}
-exports.isString = isString;
-
-function isSymbol(arg) {
- return typeof arg === 'symbol';
-}
-exports.isSymbol = isSymbol;
-
-function isUndefined(arg) {
- return arg === void 0;
-}
-exports.isUndefined = isUndefined;
-
-function isRegExp(re) {
- return isObject(re) && objectToString(re) === '[object RegExp]';
-}
-exports.isRegExp = isRegExp;
-
-function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
-}
-exports.isObject = isObject;
-
-function isDate(d) {
- return isObject(d) && objectToString(d) === '[object Date]';
-}
-exports.isDate = isDate;
-
-function isError(e) {
- return isObject(e) &&
- (objectToString(e) === '[object Error]' || e instanceof Error);
-}
-exports.isError = isError;
-
-function isFunction(arg) {
- return typeof arg === 'function';
-}
-exports.isFunction = isFunction;
-
-function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
-}
-exports.isPrimitive = isPrimitive;
-
-exports.isBuffer = require('./support/isBuffer');
-
-function objectToString(o) {
- return Object.prototype.toString.call(o);
-}
-
-
-function pad(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
-}
-
-
-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
-
-// 26 Feb 16:19:34
-function timestamp() {
- var d = new Date();
- var time = [pad(d.getHours()),
- pad(d.getMinutes()),
- pad(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
-}
-
-
-// log is just a thin wrapper to console.log that prepends a timestamp
-exports.log = function() {
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
-};
-
-
-/**
- * Inherit the prototype methods from one constructor into another.
- *
- * The Function.prototype.inherits from lang.js rewritten as a standalone
- * function (not on Function.prototype). NOTE: If this file is to be loaded
- * during bootstrapping this function needs to be rewritten using some native
- * functions as prototype setup using normal JavaScript does not work as
- * expected during bootstrapping (see mirror.js in r114903).
- *
- * @param {function} ctor Constructor function which needs to inherit the
- * prototype.
- * @param {function} superCtor Constructor function to inherit prototype from.
- */
-exports.inherits = require('inherits');
-
-exports._extend = function(origin, add) {
- // Don't do anything if add isn't an object
- if (!add || !isObject(add)) return origin;
-
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
- }
- return origin;
-};
-
-function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
-}
-
-}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"./support/isBuffer":88,"_process":69,"inherits":56}],90:[function(require,module,exports){
-module.exports={
- "name": "mocha",
- "version": "6.1.4",
- "homepage": "https://mochajs.org/",
- "notifyLogo": "https://ibin.co/4QuRuGjXvl36.png"
-}
-},{}]},{},[1]);
+ if (!immediateTimeout) {
+ immediateTimeout = setTimeout$1(timeslice, 0);
+ }
+ };
+ /**
+ * Function to allow assertion libraries to throw errors directly into mocha.
+ * This is useful when running tests in a browser because window.onerror will
+ * only receive the 'message' attribute of the Error.
+ */
+
+
+ mocha.throwError = function (err) {
+ uncaughtExceptionHandlers.forEach(function (fn) {
+ fn(err);
+ });
+ throw err;
+ };
+ /**
+ * Override ui to ensure that the ui functions are initialized.
+ * Normally this would happen in Mocha.prototype.loadFiles.
+ */
+
+
+ mocha.ui = function (ui) {
+ mocha$1.prototype.ui.call(this, ui);
+ this.suite.emit('pre-require', commonjsGlobal, null, this);
+ return this;
+ };
+ /**
+ * Setup mocha with the given setting options.
+ */
+
+
+ mocha.setup = function (opts) {
+ if (typeof opts === 'string') {
+ opts = {
+ ui: opts
+ };
+ }
+
+ if (opts.delay === true) {
+ this.delay();
+ }
+
+ var self = this;
+ Object.keys(opts).filter(function (opt) {
+ return opt !== 'delay';
+ }).forEach(function (opt) {
+ if (Object.prototype.hasOwnProperty.call(opts, opt)) {
+ self[opt](opts[opt]);
+ }
+ });
+ return this;
+ };
+ /**
+ * Run mocha, returning the Runner.
+ */
+
+
+ mocha.run = function (fn) {
+ var options = mocha.options;
+ mocha.globals('location');
+ var query = parseQuery(commonjsGlobal.location.search || '');
+
+ if (query.grep) {
+ mocha.grep(query.grep);
+ }
+
+ if (query.fgrep) {
+ mocha.fgrep(query.fgrep);
+ }
+
+ if (query.invert) {
+ mocha.invert();
+ }
+
+ return mocha$1.prototype.run.call(mocha, function (err) {
+ // The DOM Document is not available in Web Workers.
+ var document = commonjsGlobal.document;
+
+ if (document && document.getElementById('mocha') && options.noHighlighting !== true) {
+ highlightTags('code');
+ }
+
+ if (fn) {
+ fn(err);
+ }
+ });
+ };
+ /**
+ * Expose the process shim.
+ * https://github.com/mochajs/mocha/pull/916
+ */
+
+
+ mocha$1.process = process$4;
+ /**
+ * Expose mocha.
+ */
+
+ commonjsGlobal.Mocha = mocha$1;
+ commonjsGlobal.mocha = mocha;
+ var browserEntry = mocha;
+
+ return browserEntry;
+
+}));
+//# sourceMappingURL=mocha.js.map