commit 12b22bd1b2870cfa9afb999cea5c9be45f49b192 Author: Fred Boniface Date: Fri Apr 26 18:37:00 2024 +0100 Initial diff --git a/deploy.sh b/deploy.sh new file mode 100644 index 0000000..e69de29 diff --git a/dockerfile b/dockerfile new file mode 100644 index 0000000..7401d72 --- /dev/null +++ b/dockerfile @@ -0,0 +1,6 @@ +FROM node:latest +WORKDIR /app +COPY package* ./ +RUN npm i +COPY process.js ./process.js +CMD [ "echo", "This container is meant to be run as part of a build pipeline. Copy input files to /deploy/in, run 'node process.js', output files will be available in /deploy/out" ] diff --git a/node_modules/.bin/minify-html b/node_modules/.bin/minify-html new file mode 120000 index 0000000..5045aaa --- /dev/null +++ b/node_modules/.bin/minify-html @@ -0,0 +1 @@ +../@minify-html/node/cli.js \ No newline at end of file diff --git a/node_modules/.bin/uglifyjs b/node_modules/.bin/uglifyjs new file mode 120000 index 0000000..fef3468 --- /dev/null +++ b/node_modules/.bin/uglifyjs @@ -0,0 +1 @@ +../uglify-js/bin/uglifyjs \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..287eb83 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,85 @@ +{ + "name": "web-deploy", + "version": "0.0.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@minify-html/node": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@minify-html/node/-/node-0.15.0.tgz", + "integrity": "sha512-ANzt6ZBiqtwrepVXRfa0Qn/woCkINFBjQEKiXyBmg7+51mIFQHVAUbAm6UHRrT0L3xoPG0BX0/XI3NqtjK8Vyg==", + "bin": { + "minify-html": "cli.js" + }, + "engines": { + "node": ">= 8.6.0" + }, + "optionalDependencies": { + "@minify-html/node-darwin-arm64": "0.15.0", + "@minify-html/node-darwin-x64": "0.15.0", + "@minify-html/node-linux-arm64": "0.15.0", + "@minify-html/node-linux-x64": "0.15.0", + "@minify-html/node-win32-x64": "0.15.0" + } + }, + "node_modules/@minify-html/node-linux-x64": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@minify-html/node-linux-x64/-/node-linux-x64-0.15.0.tgz", + "integrity": "sha512-cO893EV6O9ZHUFX+2Yge546OCo/eCiatjzJDmUmrPP56fQ7pzTRquHs4ko3t8Rg6tMKG7RT49mBuF09JWPnrgg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@putout/minify": { + "version": "3.8.5", + "resolved": "https://registry.npmjs.org/@putout/minify/-/minify-3.8.5.tgz", + "integrity": "sha512-m7Umg719m9kqcq7kV6RXtoRZZyUKn1YQOExfpgbHCYCJvwHPR2J/lADtgtkCFZslUKIyqSsjYUmQeKqDGJpXDg==", + "engines": { + "node": ">=18" + } + }, + "node_modules/clean-css": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/clean-css/-/clean-css-5.3.3.tgz", + "integrity": "sha512-D5J+kHaVb/wKSFcyyV75uCn8fiY4sV38XJoe4CUyGQ+mOU/fMVYUdH1hJC+CJQ5uY3EnW27SbJYS4X8BiLrAFg==", + "dependencies": { + "source-map": "~0.6.0" + }, + "engines": { + "node": ">= 10.0" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/uglify-js": { + "version": "3.17.4", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.17.4.tgz", + "integrity": "sha512-T9q82TJI9e/C1TAxYvfb16xO120tMVFZrGA3f9/P4424DNu6ypK103y0GPFVa17yotwSyZW5iYXgjYHkGrJW/g==", + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/zlib": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/zlib/-/zlib-1.0.5.tgz", + "integrity": "sha512-40fpE2II+Cd3k8HWTWONfeKE2jL+P42iWJ1zzps5W51qcTsOUKM5Q5m2PFb0CLxlmFAaUuUdJGc3OfZy947v0w==", + "hasInstallScript": true, + "engines": { + "node": ">=0.2.0" + } + } + } +} diff --git a/node_modules/@minify-html/node-linux-x64/README.md b/node_modules/@minify-html/node-linux-x64/README.md new file mode 100644 index 0000000..0f6a248 --- /dev/null +++ b/node_modules/@minify-html/node-linux-x64/README.md @@ -0,0 +1 @@ +This is a specific platform-arch build for [@minify-html/nodejs](https://github.com/wilsonzlin/minify-html), and should not be installed directly. diff --git a/node_modules/@minify-html/node-linux-x64/index.node b/node_modules/@minify-html/node-linux-x64/index.node new file mode 100755 index 0000000..8923c36 Binary files /dev/null and b/node_modules/@minify-html/node-linux-x64/index.node differ diff --git a/node_modules/@minify-html/node-linux-x64/package.json b/node_modules/@minify-html/node-linux-x64/package.json new file mode 100644 index 0000000..756b8e0 --- /dev/null +++ b/node_modules/@minify-html/node-linux-x64/package.json @@ -0,0 +1,17 @@ +{ + "name": "@minify-html/node-linux-x64", + "version": "0.15.0", + "description": "@minify-html/node native module build for linux-x64", + "main": "index.node", + "files": [ + "README.md", + "index.node" + ], + "repository": "wilsonzlin/minify-html", + "os": [ + "linux" + ], + "cpu": [ + "x64" + ] +} \ No newline at end of file diff --git a/node_modules/@minify-html/node/README.md b/node_modules/@minify-html/node/README.md new file mode 100644 index 0000000..a1e19eb --- /dev/null +++ b/node_modules/@minify-html/node/README.md @@ -0,0 +1,497 @@ +

+minify-html + + + + + + + + +

+ +A Rust HTML minifier meticulously optimised for speed and effectiveness, with bindings for other languages. + +- Advanced minification strategy beats other minifiers while being much faster. +- Uses SIMD searching, direct tries, and lookup tables. +- Handles [invalid HTML](./notes/Parsing.md), with extensive testing and [fuzzing](./fuzz). +- Uses [minify-js](https://github.com/wilsonzlin/minify-js) and [lightningcss](https://github.com/parcel-bundler/lightningcss) for super fast JS and CSS minification. + +View the [changelog](./CHANGELOG.md) to see the latest updates. + +## Performance + +Comparison with [html-minifier](https://github.com/kangax/html-minifier) and [minimize](https://github.com/Swaagie/minimize), run on the top web pages. [See the breakdown here.](./bench) + +Chart showing speed of HTML minifiersChart showing compression of HTML minifiers + +The [onepass](https://github.com/wilsonzlin/minify-html/tree/master/rust/onepass) variant is even more optimised for speed. See its [README](https://github.com/wilsonzlin/minify-html/tree/master/rust/onepass) for more details. + +## Compatibility and usage + +
+ CLI + +The CLI is called [minhtml](./minhtml). +Precompiled binaries are available for Linux (ARM64 and x64), macOS (ARM64 and x64), and Windows (x64). +You can download them in the GitHub release. + +If you have Cargo installed, you can also build and install from source: `cargo install minhtml`. + +### Use + +Use the `--help` argument for more details. + +```bash +minhtml --output /path/to/output.min.html --keep-closing-tags --minify-css /path/to/src.html +``` + +To quickly parallel process a batch of files in place: + +```bash +minhtml --keep-closing-tags --minify-css /path/to/**/*.html +``` + +
+ +
+ Rust + +### Get + +```toml +[dependencies] +minify-html = "0.15.0" +``` + +### Use + +Check out the [docs](https://docs.rs/minify-html) for API and usage examples. + +
+ +
+ Deno + +- Package: https://wilsonl.in/minify-html/deno/0.15.0/index.js +- Binding: [WASM](https://webassembly.org/) +- Platforms: All + +### Use + +```ts +import init, {minify} from "https://wilsonl.in/minify-html/deno/0.15.0/index.js"; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +await init(); + +const minified = decoder.decode(minify(encoder.encode("

Hello, world!

"), { keep_spaces_between_attributes: true, keep_comments: true })); +``` + +All [`Cfg` fields](https://docs.rs/minify-html/latest/minify_html/struct.Cfg.html) are available as snake_case properties on the object provided as the second argument; if any are not set, they default to `false`. + +
+ +
+ Node.js + +- Package: [@minify-html/node](https://www.npmjs.com/package/@minify-html/node) +- Binding: [Neon](https://github.com/neon-bindings/neon) +- Platforms: Linux (ARM64 and x64), macOS (ARM64 and x64), Windows (x64); Node.js 8.6.0 and higher + +### Get + +Using npm: + +```bash +npm i @minify-html/node +``` + +Using Yarn: + +```bash +yarn add @minify-html/node +``` + +### Use + +TypeScript definitions are available. + +```ts +import { Buffer } from "node:buffer"; +import minifyHtml from "@minify-html/node"; +// Or `const minifyHtml = require("@minify-html/node")` if not using TS/ESM. + +const minified = minifyHtml.minify(Buffer.from("

Hello, world!

"), { keep_spaces_between_attributes: true, keep_comments: true }); +``` + +All [`Cfg` fields](https://docs.rs/minify-html/latest/minify_html/struct.Cfg.html) are available as snake_case properties on the object provided as the second argument; if any are not set, they default to `false`. + +
+ +
+ Java + +- Package: [in.wilsonl.minifyhtml](https://search.maven.org/artifact/in.wilsonl.minifyhtml/minify-html) +- Binding: [JNI](https://github.com/jni-rs/jni-rs) +- Platforms: Linux (ARM64 and x64), macOS (ARM64 and x64), Windows (x64); Java 7 and higher + +### Get + +Add as a Maven dependency: + +```xml + + in.wilsonl.minifyhtml + minify-html + 0.15.0 + +``` + +### Use + +```java +import in.wilsonl.minifyhtml.Configuration; +import in.wilsonl.minifyhtml.MinifyHtml; + +Configuration cfg = new Configuration.Builder() + .setKeepHtmlAndHeadOpeningTags(true) + .setMinifyCss(true) + .build(); + +String minified = MinifyHtml.minify("

Hello, world!

", cfg); +``` + +All [`Cfg` fields](https://docs.rs/minify-html/latest/minify_html/struct.Cfg.html) are available as camelCase setter methods on the `Builder`; if any are not set, they default to `false`. + +
+ +
+ Python + +- Package: [minify-html](https://pypi.org/project/minify-html) +- Binding: [PyO3](https://github.com/PyO3/pyo3) +- Platforms: Linux (ARM64 and x64), macOS (ARM64 and x64), Windows (x64); Python 3.8 to 3.12 + +### Get + +Add the PyPI project as a dependency and install it using `pip` or `pipenv`. + +### Use + +```python +import minify_html + +minified = minify_html.minify("

Hello, world!

", minify_js=True, remove_processing_instructions=True) +``` + +All [`Cfg` fields](https://docs.rs/minify-html/latest/minify_html/struct.Cfg.html) are available as Python keyword arguments; if any are omitted, they default to `False`. + +
+ +
+ Ruby + +- Package: [minify_html](https://rubygems.org/gems/minify_html) +- Binding: [rb-sys](https://github.com/oxidize-rb/rb-sys) and [magnus](https://github.com/matsadler/magnus) +- Platforms: Linux (ARM64 and x64), macOS (ARM64 and x64), Windows (x64); Ruby 2.7 to 3.2 + +### Get + +Add the library as a dependency to `Gemfile` or `*.gemspec`. + +### Use + +```ruby +require 'minify_html' + +print minify_html("

Hello, world!

", { :keep_spaces_between_attributes => true, :minify_js => true }) +``` + +All [`Cfg` fields](https://docs.rs/minify-html/latest/minify_html/struct.Cfg.html) are available; if any are omitted, they default to `false`. + +
+ +
+ WASM + +- Package: [@minify-html/wasm](https://npmjs.org/package/@minify-html/wasm) +- Binding: [WASM](https://webassembly.org/) +- Platforms: All + +A bundler may be required to use the WebAssembly module, see [this](https://rustwasm.github.io/wasm-bindgen/reference/deployment.html#bundlers) for more details. + +### Use + +```ts +import init, {minify} from "@minify-html/wasm"; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +await init(); + +const minified = decoder.decode(minify(encoder.encode("

Hello, world!

"), { keep_spaces_between_attributes: true, keep_comments: true })); +``` + +All [`Cfg` fields](https://docs.rs/minify-html/latest/minify_html/struct.Cfg.html) are available as snake_case properties on the object provided as the second argument; if any are not set, they default to `false`. + +
+ +## Templating syntax + +minify-html can parse and preserve `{{`/`{%`/`{#` and `<%` syntax in the source code, which allows minification of many HTML templates written for most engines like Pebble, Mustache, Django, Go, Jinja, Twix, Nunjucks, Handlebars, Sailfish, JSP, EJS, and ERB. Look for the `preserve_*_template_syntax` Cfg options. + +PHP blocks (` +Collapse whitespace + +> **Applies to:** any element except [whitespace sensitive](./minify-html-common/src/spec/tag/whitespace.rs) elements. + +Reduce a sequence of whitespace characters in text nodes to a single space (U+0020). + +
BeforeAfter
+ +```html +

↵ +··The·quick·brown·fox↵ +··jumps·over·the·lazy↵ +··dog.↵ +

+``` + +
+ +```html +

·The·quick·brown·fox·jumps·over·the·lazy·dog.·

+``` + +
+ + +
+Destroy whole whitespace + +> **Applies to:** any element except [whitespace sensitive](./minify-html-common/src/spec/tag/whitespace.rs), [content](src/spec/tag/whitespace.rs), [content-first](./minify-html-common/src/spec/tag/whitespace.rs), and [formatting](./minify-html-common/src/spec/tag/whitespace.rs) elements. + +Remove any text nodes between tags that only consist of whitespace characters. + +
BeforeAfter
+ +```html +
    ↵ +··
  • A
  • ↵ +··
  • B
  • ↵ +··
  • C
  • ↵ +
+``` + +
+ +```html +
    ↵ +··
  • A
  • B
  • C
  • ↵ +
+``` + +
+
+ +
+Trim whitespace + +> **Applies to:** any element except [whitespace sensitive](./minify-html-common/src/spec/tag/whitespace.rs) and [formatting](./minify-html-common/src/spec/tag/whitespace.rs) elements. + +Remove any leading/trailing whitespace from any leading/trailing text nodes of a tag. + +
BeforeAfter
+ +```html +

↵ +··Hey,·I·just·found↵ +··out·about·this·cool·website!↵ +··[1]↵ +

+``` + +
+ +```html +

Hey,·I·just·found↵ +··out·about·this·cool·website!↵ +··[1]

+``` + +
+
+ +#### Element types + +minify-html assumes HTML and SVG elements are used in specific ways, based on standards and best practices. By making these assumptions, it can apply optimal whitespace minification strategies. If these assumptions do not hold, consider adjusting the HTML source or turning off whitespace minification. + +|Group|Elements|Expected children| +|---|---|---| +|Formatting|`a`, `strong`, [and others](./minify-html-common/src/spec/tag/whitespace.rs)|Formatting elements, text.| +|Content|`h1`, `p`, [and others](./minify-html-common/src/spec/tag/whitespace.rs)|Formatting elements, text.| +|Layout|`div`, `ul`, [and others](./minify-html-common/src/spec/tag/whitespace.rs)|Layout elements, content elements.| +|Content-first|`label`, `li`, [and others](./minify-html-common/src/spec/tag/whitespace.rs)|Like content but could be layout with only one child.| + +
+Formatting elements + +> Whitespace is collapsed. + +Formatting elements are usually inline elements that wrap around part of some text in a content element, so its whitespace isn't trimmed as they're probably part of the content. + +
+ +
+Content elements + +> Whitespace is trimmed and collapsed. + +Content elements usually represent a contiguous and complete unit of content such as a paragraph. As such, whitespace is significant but sequences of them are most likely due to formatting. + +###### Before + +```html +

↵ +··Hey,·I·just·found↵ +··out·about·this·cool·website!↵ +··[1]↵ +

+``` + +###### After + +```html +

Hey,·I·just·found·out·about·this·cool·website!·[1]

+``` + +
+ +
+Layout elements + +> Whitespace is trimmed and collapsed. Whole whitespace is removed. + +These elements should only contain other elements and no text. This makes it possible to remove whole whitespace, which is useful when using `display: inline-block` so that whitespace between elements (e.g. indentation) does not alter layout and styling. + +###### Before + +```html + +``` + +###### After + +```html + +``` + +
+ +
+Content-first elements + +> Whitespace is trimmed and collapsed. + +These elements are usually like content elements but are occasionally used like a layout element with one child. Whole whitespace is not removed as it might contain content, but this is OK for using as layout as there is only one child and whitespace is trimmed. + +###### Before + +```html +
  • ↵ +··
    ↵ +····
    ↵ +····
    ↵ +··
    ↵ +
  • +``` + +###### After + +```html +
  • +``` + +
    + +### Tags + +[Optional opening and closing tags](https://html.spec.whatwg.org/multipage/syntax.html#syntax-tag-omission) are removed. + +### Attributes + +Any entities in attribute values are decoded, and then the shortest representation of the value is calculated and used: + +- Double quoted, with any `"` encoded. +- Single quoted, with any `'` encoded. +- Unquoted, with `"`/`'` first character (if applicable), any `>`, and any whitespace encoded. + +Attributes have their whitespace (after any decoding) trimmed and collapsed when possible. + +[Boolean attribute](https://github.com/wilsonzlin/html-data) values are removed. +[Some other attributes](https://github.com/wilsonzlin/html-data) are completely removed if their value is empty or the default value after any processing. + +`type` attributes on `script` tags with a value equaling a [JavaScript MIME type](https://mimesniff.spec.whatwg.org/#javascript-mime-type) are removed. + +If an attribute value is empty after any processing, everything but the name is completely removed (i.e. no `=`), as an empty attribute is implicitly [the same](https://html.spec.whatwg.org/multipage/syntax.html#attributes-2) as an attribute with an empty string value. + +Spaces are removed between attributes when possible. + +### Entities + +Entities are decoded if they're valid and shorter or equal in length when decoded. UTF-8 sequences that have a shorter entity representation are encoded. + +Numeric entities that do not refer to a valid [Unicode Scalar Value](https://www.unicode.org/glossary/#unicode_scalar_value) are replaced with the [replacement character](https://en.wikipedia.org/wiki/Specials_(Unicode_block)#Replacement_character). + +Encoding is avoided when possible; for example, `<` are only encoded in content if they are followed by a valid tag name character. +If necessary, the shortest entity representation is chosen. + +### Comments + +Comments are removed. + +### Ignored + +Bangs, [processing instructions](https://en.wikipedia.org/wiki/Processing_Instruction), and empty elements are not removed as it is assumed there is a special reason for their declaration. + +## Parsing + +minify-html can process any HTML, handling all possible syntax (including invalid ones) gracefully like browsers. See [Parsing.md](./notes/Parsing.md) for more details. + +## Issues and contributions + +Pull requests and any contributions welcome! + +If minify-html did something unexpected, misunderstood some syntax, or incorrectly kept/removed some code, [raise an issue](https://github.com/wilsonzlin/minify-html/issues) with some relevant code that can be used to reproduce and investigate the issue. diff --git a/node_modules/@minify-html/node/cli.js b/node_modules/@minify-html/node/cli.js new file mode 100755 index 0000000..a7b687e --- /dev/null +++ b/node_modules/@minify-html/node/cli.js @@ -0,0 +1,25 @@ +#!/usr/bin/env node + +const lib = require("."); +const fs = require("fs"); + +const cfg = {}; +let input; +let output; +const args = process.argv.slice(2); +let arg; +while ((arg = args.shift()) !== undefined) { + if (arg.slice(0, 2) === "--") { + const name = arg.slice(2); + if (name === "output") { + output = args.shift(); + } else { + cfg[name.replace(/-/g, "_")] = true; + } + } else { + input = arg; + } +} + +const min = lib.minify(fs.readFileSync(input), cfg); +fs.writeFileSync(output, min); diff --git a/node_modules/@minify-html/node/index.d.ts b/node_modules/@minify-html/node/index.d.ts new file mode 100644 index 0000000..7f0da0e --- /dev/null +++ b/node_modules/@minify-html/node/index.d.ts @@ -0,0 +1,42 @@ +/** + * Minifies a Buffer containing UTF-8 HTML code. + * + * @param src - Source HTML code + * @param cfg - Configurable minifier settings to use + * @returns Minified HTML code + */ +export function minify( + src: Buffer, + cfg: { + /** Do not minify DOCTYPEs. Minified DOCTYPEs may not be spec compliant. */ + do_not_minify_doctype?: boolean; + /** Ensure all unquoted attribute values in the output do not contain any characters prohibited by the WHATWG specification. */ + ensure_spec_compliant_unquoted_attribute_values?: boolean; + /** Do not omit closing tags when possible. */ + keep_closing_tags?: boolean; + /** Do not omit `` and `` opening tags when they don't have attributes. */ + keep_html_and_head_opening_tags?: boolean; + /** Keep spaces between attributes when possible to conform to HTML standards. */ + keep_spaces_between_attributes?: boolean; + /** Keep all comments. */ + keep_comments?: boolean; + /** Keep SSI comments. */ + keep_ssi_comments?: boolean; + /** When `{{`, `{#`, or `{%` are seen in content, all source code until the subsequent matching closing `}}`, `#}`, or `%}` respectively gets piped through untouched. */ + preserve_brace_template_syntax?: boolean; + /** When `<%` is seen in content, all source code until the subsequent matching closing `%>` gets piped through untouched. */ + preserve_chevron_percent_template_syntax?: boolean; + /** + * If enabled, content in ` + +-------------------------------------------------------------------------------- + + + + + +## Table of Contents + +- [Examples](#examples) + - [Consuming a source map](#consuming-a-source-map) + - [Generating a source map](#generating-a-source-map) + - [With SourceNode (high level API)](#with-sourcenode-high-level-api) + - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) +- [API](#api) + - [SourceMapConsumer](#sourcemapconsumer) + - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) + - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) + - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) + - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) + - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) + - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) + - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) + - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) + - [SourceMapGenerator](#sourcemapgenerator) + - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) + - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) + - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) + - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) + - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) + - [SourceNode](#sourcenode) + - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) + - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) + - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) + - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) + - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) + - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) + - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) + - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) + - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) + - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) + + + +## Examples + +### Consuming a source map + +```js +var rawSourceMap = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: 'http://example.com/www/js/', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' +}; + +var smc = new SourceMapConsumer(rawSourceMap); + +console.log(smc.sources); +// [ 'http://example.com/www/js/one.js', +// 'http://example.com/www/js/two.js' ] + +console.log(smc.originalPositionFor({ + line: 2, + column: 28 +})); +// { source: 'http://example.com/www/js/two.js', +// line: 2, +// column: 10, +// name: 'n' } + +console.log(smc.generatedPositionFor({ + source: 'http://example.com/www/js/two.js', + line: 2, + column: 10 +})); +// { line: 2, column: 28 } + +smc.eachMapping(function (m) { + // ... +}); +``` + +### Generating a source map + +In depth guide: +[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) + +#### With SourceNode (high level API) + +```js +function compile(ast) { + switch (ast.type) { + case 'BinaryExpression': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + [compile(ast.left), " + ", compile(ast.right)] + ); + case 'Literal': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + String(ast.value) + ); + // ... + default: + throw new Error("Bad AST"); + } +} + +var ast = parse("40 + 2", "add.js"); +console.log(compile(ast).toStringWithSourceMap({ + file: 'add.js' +})); +// { code: '40 + 2', +// map: [object SourceMapGenerator] } +``` + +#### With SourceMapGenerator (low level API) + +```js +var map = new SourceMapGenerator({ + file: "source-mapped.js" +}); + +map.addMapping({ + generated: { + line: 10, + column: 35 + }, + source: "foo.js", + original: { + line: 33, + column: 2 + }, + name: "christopher" +}); + +console.log(map.toString()); +// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' +``` + +## API + +Get a reference to the module: + +```js +// Node.js +var sourceMap = require('source-map'); + +// Browser builds +var sourceMap = window.sourceMap; + +// Inside Firefox +const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); +``` + +### SourceMapConsumer + +A SourceMapConsumer instance represents a parsed source map which we can query +for information about the original file positions by giving it a file position +in the generated source. + +#### new SourceMapConsumer(rawSourceMap) + +The only parameter is the raw source map (either as a string which can be +`JSON.parse`'d, or an object). According to the spec, source maps have the +following attributes: + +* `version`: Which version of the source map spec this map is following. + +* `sources`: An array of URLs to the original source files. + +* `names`: An array of identifiers which can be referenced by individual + mappings. + +* `sourceRoot`: Optional. The URL root from which all sources are relative. + +* `sourcesContent`: Optional. An array of contents of the original source files. + +* `mappings`: A string of base64 VLQs which contain the actual mappings. + +* `file`: Optional. The generated filename this source map is associated with. + +```js +var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); +``` + +#### SourceMapConsumer.prototype.computeColumnSpans() + +Compute the last column for each generated mapping. The last column is +inclusive. + +```js +// Before: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] + +consumer.computeColumnSpans(); + +// After: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1, +// lastColumn: 9 }, +// { line: 2, +// column: 10, +// lastColumn: 19 }, +// { line: 2, +// column: 20, +// lastColumn: Infinity } ] + +``` + +#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) + +Returns the original source, line, and column information for the generated +source's line and column positions provided. The only argument is an object with +the following properties: + +* `line`: The line number in the generated source. Line numbers in + this library are 1-based (note that the underlying source map + specification uses 0-based line numbers -- this library handles the + translation). + +* `column`: The column number in the generated source. Column numbers + in this library are 0-based. + +* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or + `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest + element that is smaller than or greater than the one we are searching for, + respectively, if the exact element cannot be found. Defaults to + `SourceMapConsumer.GREATEST_LOWER_BOUND`. + +and an object is returned with the following properties: + +* `source`: The original source file, or null if this information is not + available. + +* `line`: The line number in the original source, or null if this information is + not available. The line number is 1-based. + +* `column`: The column number in the original source, or null if this + information is not available. The column number is 0-based. + +* `name`: The original identifier, or null if this information is not available. + +```js +consumer.originalPositionFor({ line: 2, column: 10 }) +// { source: 'foo.coffee', +// line: 2, +// column: 2, +// name: null } + +consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) +// { source: null, +// line: null, +// column: null, +// name: null } +``` + +#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) + +Returns the generated line and column information for the original source, +line, and column positions provided. The only argument is an object with +the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: The column number in the original source. The column + number is 0-based. + +and an object is returned with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) +// { line: 1, +// column: 56 } +``` + +#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) + +Returns all generated line and column information for the original source, line, +and column provided. If no column is provided, returns all mappings +corresponding to a either the line we are searching for or the next closest line +that has any mappings. Otherwise, returns all mappings corresponding to the +given line and either the column we are searching for or the next closest column +that has any offsets. + +The only argument is an object with the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: Optional. The column number in the original source. The + column number is 0-based. + +and an array of objects is returned, each with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] +``` + +#### SourceMapConsumer.prototype.hasContentsOfAllSources() + +Return true if we have the embedded source content for every source listed in +the source map, false otherwise. + +In other words, if this method returns `true`, then +`consumer.sourceContentFor(s)` will succeed for every source `s` in +`consumer.sources`. + +```js +// ... +if (consumer.hasContentsOfAllSources()) { + consumerReadyCallback(consumer); +} else { + fetchSources(consumer, consumerReadyCallback); +} +// ... +``` + +#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) + +Returns the original source content for the source provided. The only +argument is the URL of the original source file. + +If the source content for the given source is not found, then an error is +thrown. Optionally, pass `true` as the second param to have `null` returned +instead. + +```js +consumer.sources +// [ "my-cool-lib.clj" ] + +consumer.sourceContentFor("my-cool-lib.clj") +// "..." + +consumer.sourceContentFor("this is not in the source map"); +// Error: "this is not in the source map" is not in the source map + +consumer.sourceContentFor("this is not in the source map", true); +// null +``` + +#### SourceMapConsumer.prototype.eachMapping(callback, context, order) + +Iterate over each mapping between an original source/line/column and a +generated line/column in this source map. + +* `callback`: The function that is called with each mapping. Mappings have the + form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, + name }` + +* `context`: Optional. If specified, this object will be the value of `this` + every time that `callback` is called. + +* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or + `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over + the mappings sorted by the generated file's line/column order or the + original's source/line/column order, respectively. Defaults to + `SourceMapConsumer.GENERATED_ORDER`. + +```js +consumer.eachMapping(function (m) { console.log(m); }) +// ... +// { source: 'illmatic.js', +// generatedLine: 1, +// generatedColumn: 0, +// originalLine: 1, +// originalColumn: 0, +// name: null } +// { source: 'illmatic.js', +// generatedLine: 2, +// generatedColumn: 0, +// originalLine: 2, +// originalColumn: 0, +// name: null } +// ... +``` +### SourceMapGenerator + +An instance of the SourceMapGenerator represents a source map which is being +built incrementally. + +#### new SourceMapGenerator([startOfSourceMap]) + +You may pass an object with the following properties: + +* `file`: The filename of the generated source that this source map is + associated with. + +* `sourceRoot`: A root for all relative URLs in this source map. + +* `skipValidation`: Optional. When `true`, disables validation of mappings as + they are added. This can improve performance but should be used with + discretion, as a last resort. Even then, one should avoid using this flag when + running tests, if possible. + +```js +var generator = new sourceMap.SourceMapGenerator({ + file: "my-generated-javascript-file.js", + sourceRoot: "http://example.com/app/js/" +}); +``` + +#### SourceMapGenerator.fromSourceMap(sourceMapConsumer) + +Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. + +* `sourceMapConsumer` The SourceMap. + +```js +var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); +``` + +#### SourceMapGenerator.prototype.addMapping(mapping) + +Add a single mapping from original source line and column to the generated +source's line and column for this source map being created. The mapping object +should have the following properties: + +* `generated`: An object with the generated line and column positions. + +* `original`: An object with the original line and column positions. + +* `source`: The original source file (relative to the sourceRoot). + +* `name`: An optional original token name for this mapping. + +```js +generator.addMapping({ + source: "module-one.scm", + original: { line: 128, column: 0 }, + generated: { line: 3, column: 456 } +}) +``` + +#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for an original source file. + +* `sourceFile` the URL of the original source file. + +* `sourceContent` the content of the source file. + +```js +generator.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) + +Applies a SourceMap for a source file to the SourceMap. +Each mapping to the supplied source file is rewritten using the +supplied SourceMap. Note: The resolution for the resulting mappings +is the minimum of this map and the supplied map. + +* `sourceMapConsumer`: The SourceMap to be applied. + +* `sourceFile`: Optional. The filename of the source file. + If omitted, sourceMapConsumer.file will be used, if it exists. + Otherwise an error will be thrown. + +* `sourceMapPath`: Optional. The dirname of the path to the SourceMap + to be applied. If relative, it is relative to the SourceMap. + + This parameter is needed when the two SourceMaps aren't in the same + directory, and the SourceMap to be applied contains relative source + paths. If so, those relative source paths need to be rewritten + relative to the SourceMap. + + If omitted, it is assumed that both SourceMaps are in the same directory, + thus not needing any rewriting. (Supplying `'.'` has the same effect.) + +#### SourceMapGenerator.prototype.toString() + +Renders the source map being generated to a string. + +```js +generator.toString() +// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' +``` + +### SourceNode + +SourceNodes provide a way to abstract over interpolating and/or concatenating +snippets of generated JavaScript source code, while maintaining the line and +column information associated between those snippets and the original source +code. This is useful as the final intermediate representation a compiler might +use before outputting the generated JS and source map. + +#### new SourceNode([line, column, source[, chunk[, name]]]) + +* `line`: The original line number associated with this source node, or null if + it isn't associated with an original line. The line number is 1-based. + +* `column`: The original column number associated with this source node, or null + if it isn't associated with an original column. The column number + is 0-based. + +* `source`: The original source's filename; null if no filename is provided. + +* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see + below. + +* `name`: Optional. The original identifier. + +```js +var node = new SourceNode(1, 2, "a.cpp", [ + new SourceNode(3, 4, "b.cpp", "extern int status;\n"), + new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), + new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), +]); +``` + +#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) + +Creates a SourceNode from generated code and a SourceMapConsumer. + +* `code`: The generated code + +* `sourceMapConsumer` The SourceMap for the generated code + +* `relativePath` The optional path that relative sources in `sourceMapConsumer` + should be relative to. + +```js +var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); +var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), + consumer); +``` + +#### SourceNode.prototype.add(chunk) + +Add a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.add(" + "); +node.add(otherNode); +node.add([leftHandOperandNode, " + ", rightHandOperandNode]); +``` + +#### SourceNode.prototype.prepend(chunk) + +Prepend a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.prepend("/** Build Id: f783haef86324gf **/\n\n"); +``` + +#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for a source file. This will be added to the +`SourceMap` in the `sourcesContent` field. + +* `sourceFile`: The filename of the source file + +* `sourceContent`: The content of the source file + +```js +node.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceNode.prototype.walk(fn) + +Walk over the tree of JS snippets in this node and its children. The walking +function is called once for each snippet of JS and is passed that snippet and +the its original associated source's line/column location. + +* `fn`: The traversal function. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.walk(function (code, loc) { console.log("WALK:", code, loc); }) +// WALK: uno { source: 'b.js', line: 3, column: 4, name: null } +// WALK: dos { source: 'a.js', line: 1, column: 2, name: null } +// WALK: tres { source: 'a.js', line: 1, column: 2, name: null } +// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } +``` + +#### SourceNode.prototype.walkSourceContents(fn) + +Walk over the tree of SourceNodes. The walking function is called for each +source file content and is passed the filename and source content. + +* `fn`: The traversal function. + +```js +var a = new SourceNode(1, 2, "a.js", "generated from a"); +a.setSourceContent("a.js", "original a"); +var b = new SourceNode(1, 2, "b.js", "generated from b"); +b.setSourceContent("b.js", "original b"); +var c = new SourceNode(1, 2, "c.js", "generated from c"); +c.setSourceContent("c.js", "original c"); + +var node = new SourceNode(null, null, null, [a, b, c]); +node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) +// WALK: a.js : original a +// WALK: b.js : original b +// WALK: c.js : original c +``` + +#### SourceNode.prototype.join(sep) + +Like `Array.prototype.join` except for SourceNodes. Inserts the separator +between each of this source node's children. + +* `sep`: The separator. + +```js +var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); +var operand = new SourceNode(3, 4, "a.rs", "="); +var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); + +var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); +var joinedNode = node.join(" "); +``` + +#### SourceNode.prototype.replaceRight(pattern, replacement) + +Call `String.prototype.replace` on the very right-most source snippet. Useful +for trimming white space from the end of a source node, etc. + +* `pattern`: The pattern to replace. + +* `replacement`: The thing to replace the pattern with. + +```js +// Trim trailing white space. +node.replaceRight(/\s*$/, ""); +``` + +#### SourceNode.prototype.toString() + +Return the string representation of this source node. Walks over the tree and +concatenates all the various snippets together to one string. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toString() +// 'unodostresquatro' +``` + +#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) + +Returns the string representation of this tree of source nodes, plus a +SourceMapGenerator which contains all the mappings between the generated and +original sources. + +The arguments are the same as those to `new SourceMapGenerator`. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toStringWithSourceMap({ file: "my-output-file.js" }) +// { code: 'unodostresquatro', +// map: [object SourceMapGenerator] } +``` diff --git a/node_modules/source-map/dist/source-map.debug.js b/node_modules/source-map/dist/source-map.debug.js new file mode 100644 index 0000000..aad0620 --- /dev/null +++ b/node_modules/source-map/dist/source-map.debug.js @@ -0,0 +1,3234 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // 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 +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 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. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + var hasNativeMap = typeof Map !== "undefined"; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + }; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]) +}); +; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vd2VicGFjay91bml2ZXJzYWxNb2R1bGVEZWZpbml0aW9uIiwid2VicGFjazovLy93ZWJwYWNrL2Jvb3RzdHJhcCAxNjI0YzcyOTliODg3ZjdiZGY2NCIsIndlYnBhY2s6Ly8vLi9zb3VyY2UtbWFwLmpzIiwid2VicGFjazovLy8uL2xpYi9zb3VyY2UtbWFwLWdlbmVyYXRvci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LXZscS5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LmpzIiwid2VicGFjazovLy8uL2xpYi91dGlsLmpzIiwid2VicGFjazovLy8uL2xpYi9hcnJheS1zZXQuanMiLCJ3ZWJwYWNrOi8vLy4vbGliL21hcHBpbmctbGlzdC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvc291cmNlLW1hcC1jb25zdW1lci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmluYXJ5LXNlYXJjaC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvcXVpY2stc29ydC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvc291cmNlLW5vZGUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsQ0FBQztBQUNELE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1hcHBpbmcuc291cmNlKTtcbiAgICAgICAgbmV4dCArPSBiYXNlNjRWTFEuZW5jb2RlKHNvdXJjZUlkeCAtIHByZXZpb3VzU291cmNlKTtcbiAgICAgICAgcHJldmlvdXNTb3VyY2UgPSBzb3VyY2VJZHg7XG5cbiAgICAgICAgLy8gbGluZXMgYXJlIHN0b3JlZCAwLWJhc2VkIGluIFNvdXJjZU1hcCBzcGVjIHZlcnNpb24gM1xuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5vcmlnaW5hbExpbmUgLSAxXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0gcHJldmlvdXNPcmlnaW5hbExpbmUpO1xuICAgICAgICBwcmV2aW91c09yaWdpbmFsTGluZSA9IG1hcHBpbmcub3JpZ2luYWxMaW5lIC0gMTtcblxuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5vcmlnaW5hbENvbHVtblxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAtIHByZXZpb3VzT3JpZ2luYWxDb2x1bW4pO1xuICAgICAgICBwcmV2aW91c09yaWdpbmFsQ29sdW1uID0gbWFwcGluZy5vcmlnaW5hbENvbHVtbjtcblxuICAgICAgICBpZiAobWFwcGluZy5uYW1lICE9IG51bGwpIHtcbiAgICAgICAgICBuYW1lSWR4ID0gdGhpcy5fbmFtZXMuaW5kZXhPZihtYXBwaW5nLm5hbWUpO1xuICAgICAgICAgIG5leHQgKz0gYmFzZTY0VkxRLmVuY29kZShuYW1lSWR4IC0gcHJldmlvdXNOYW1lKTtcbiAgICAgICAgICBwcmV2aW91c05hbWUgPSBuYW1lSWR4O1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIHJlc3VsdCArPSBuZXh0O1xuICAgIH1cblxuICAgIHJldHVybiByZXN1bHQ7XG4gIH07XG5cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuX2dlbmVyY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hU291cmNlTWFwQ29uc3VtZXIuc291cmNlcy5mb3JFYWNoKGZ1bmN0aW9uIChzb3VyY2VGaWxlKSB7XG4gICAgICB2YXIgY29udGVudCA9IGFTb3VyY2VNYXBDb25zdW1lci5zb3VyY2VDb250ZW50Rm9yKHNvdXJjZUZpbGUpO1xuICAgICAgaWYgKGNvbnRlbnQgIT0gbnVsbCkge1xuICAgICAgICBpZiAoYVJlbGF0aXZlUGF0aCAhPSBudWxsKSB7XG4gICAgICAgICAgc291cmNlRmlsZSA9IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBzb3VyY2VGaWxlKTtcbiAgICAgICAgfVxuICAgICAgICBub2RlLnNldFNvdXJjZUNvbnRlbnQoc291cmNlRmlsZSwgY29udGVudCk7XG4gICAgICB9XG4gICAgfSk7XG5cbiAgICByZXR1cm4gbm9kZTtcblxuICAgIGZ1bmN0aW9uIGFkZE1hcHBpbmdXaXRoQ29kZShtYXBwaW5nLCBjb2RlKSB7XG4gICAgICBpZiAobWFwcGluZyA9PT0gbnVsbCB8fCBtYXBwaW5nLnNvdXJjZSA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIG5vZGUuYWRkKGNvZGUpO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgdmFyIHNvdXJjZSA9IGFSZWxhdGl2ZVBhdGhcbiAgICAgICAgICA/IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBtYXBwaW5nLnNvdXJjZSlcbiAgICAgICAgICA6IG1hcHBpbmcuc291cmNlO1xuICAgICAgICBub2RlLmFkZChuZXcgU291cmNlTm9kZShtYXBwaW5nLm9yaWdpbmFsTGluZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgbWFwcGluZy5vcmlnaW5hbENvbHVtbixcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgc291cmNlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb2RlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIC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FNvdXJjZSA9IG51bGw7XG4gICAgICBzb3VyY2VNYXBwaW5nQWN0aXZlID0gZmFsc2U7XG4gICAgfVxuICAgIGZvciAodmFyIGlkeCA9IDAsIGxlbmd0aCA9IGNodW5rLmxlbmd0aDsgaWR4IDwgbGVuZ3RoOyBpZHgrKykge1xuICAgICAgaWYgKGNodW5rLmNoYXJDb2RlQXQoaWR4KSA9PT0gTkVXTElORV9DT0RFKSB7XG4gICAgICAgIGdlbmVyYXRlZC5saW5lKys7XG4gICAgICAgIGdlbmVyYXRlZC5jb2x1bW4gPSAwO1xuICAgICAgICAvLyBNYXBwaW5ncyBlbmQgYXQgZW9sXG4gICAgICAgIGlmIChpZHggKyAxID09PSBsZW5ndGgpIHtcbiAgICAgICAgICBsYXN0T3JpZ2luYWxTb3VyY2UgPSBudWxsO1xuICAgICAgICAgIHNvdXJjZU1hcHBpbmdBY3RpdmUgPSBmYWxzZTtcbiAgICAgICAgfSBlbHNlIGlmIChzb3VyY2VNYXBwaW5nQWN0aXZlKSB7XG4gICAgICAgICAgbWFwLmFkZE1hcHBpbmcoe1xuICAgICAgICAgICAgc291cmNlOiBvcmlnaW5hbC5zb3VyY2UsXG4gICAgICAgICAgICBvcmlnaW5hbDoge1xuICAgICAgICAgICAgICBsaW5lOiBvcmlnaW5hbC5saW5lLFxuICAgICAgICAgICAgICBjb2x1bW46IG9yaWdpbmFsLmNvbHVtblxuICAgICAgICAgICAgfSxcbiAgICAgICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgICAgICBsaW5lOiBnZW5lcmF0ZWQubGluZSxcbiAgICAgICAgICAgICAgY29sdW1uOiBnZW5lcmF0ZWQuY29sdW1uXG4gICAgICAgICAgICB9LFxuICAgICAgICAgICAgbmFtZTogb3JpZ2luYWwubmFtZVxuICAgICAgICAgIH0pO1xuICAgICAgICB9XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBnZW5lcmF0ZWQuY29sdW1uKys7XG4gICAgICB9XG4gICAgfVxuICB9KTtcbiAgdGhpcy53YWxrU291cmNlQ29udGVudHMoZnVuY3Rpb24gKHNvdXJjZUZpbGUsIHNvdXJjZUNvbnRlbnQpIHtcbiAgICBtYXAuc2V0U291cmNlQ29udGVudChzb3VyY2VGaWxlLCBzb3VyY2VDb250ZW50KTtcbiAgfSk7XG5cbiAgcmV0dXJuIHsgY29kZTogZ2VuZXJhdGVkLmNvZGUsIG1hcDogbWFwIH07XG59O1xuXG5leHBvcnRzLlNvdXJjZU5vZGUgPSBTb3VyY2VOb2RlO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvc291cmNlLW5vZGUuanNcbi8vIG1vZHVsZSBpZCA9IDEwXG4vLyBtb2R1bGUgY2h1bmtzID0gMCJdLCJzb3VyY2VSb290IjoiIn0= \ No newline at end of file diff --git a/node_modules/source-map/dist/source-map.js b/node_modules/source-map/dist/source-map.js new file mode 100644 index 0000000..b4eb087 --- /dev/null +++ b/node_modules/source-map/dist/source-map.js @@ -0,0 +1,3233 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // 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 +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 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. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + var hasNativeMap = typeof Map !== "undefined"; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + }; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]) +}); +; \ No newline at end of file diff --git a/node_modules/source-map/dist/source-map.min.js b/node_modules/source-map/dist/source-map.min.js new file mode 100644 index 0000000..c7c72da --- /dev/null +++ b/node_modules/source-map/dist/source-map.min.js @@ -0,0 +1,2 @@ +!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.sourceMap=n():e.sourceMap=n()}(this,function(){return function(e){function n(t){if(r[t])return r[t].exports;var o=r[t]={exports:{},id:t,loaded:!1};return e[t].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var r={};return n.m=e,n.c=r,n.p="",n(0)}([function(e,n,r){n.SourceMapGenerator=r(1).SourceMapGenerator,n.SourceMapConsumer=r(7).SourceMapConsumer,n.SourceNode=r(10).SourceNode},function(e,n,r){function t(e){e||(e={}),this._file=i.getArg(e,"file",null),this._sourceRoot=i.getArg(e,"sourceRoot",null),this._skipValidation=i.getArg(e,"skipValidation",!1),this._sources=new s,this._names=new s,this._mappings=new a,this._sourcesContents=null}var o=r(2),i=r(4),s=r(5).ArraySet,a=r(6).MappingList;t.prototype._version=3,t.fromSourceMap=function(e){var n=e.sourceRoot,r=new t({file:e.file,sourceRoot:n});return e.eachMapping(function(e){var t={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(t.source=e.source,null!=n&&(t.source=i.relative(n,t.source)),t.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(t.name=e.name)),r.addMapping(t)}),e.sources.forEach(function(t){var o=t;null!==n&&(o=i.relative(n,t)),r._sources.has(o)||r._sources.add(o);var s=e.sourceContentFor(t);null!=s&&r.setSourceContent(t,s)}),r},t.prototype.addMapping=function(e){var n=i.getArg(e,"generated"),r=i.getArg(e,"original",null),t=i.getArg(e,"source",null),o=i.getArg(e,"name",null);this._skipValidation||this._validateMapping(n,r,t,o),null!=t&&(t=String(t),this._sources.has(t)||this._sources.add(t)),null!=o&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:null!=r&&r.line,originalColumn:null!=r&&r.column,source:t,name:o})},t.prototype.setSourceContent=function(e,n){var r=e;null!=this._sourceRoot&&(r=i.relative(this._sourceRoot,r)),null!=n?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[i.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[i.toSetString(r)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},t.prototype.applySourceMap=function(e,n,r){var t=n;if(null==n){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');t=e.file}var o=this._sourceRoot;null!=o&&(t=i.relative(o,t));var a=new s,u=new s;this._mappings.unsortedForEach(function(n){if(n.source===t&&null!=n.originalLine){var s=e.originalPositionFor({line:n.originalLine,column:n.originalColumn});null!=s.source&&(n.source=s.source,null!=r&&(n.source=i.join(r,n.source)),null!=o&&(n.source=i.relative(o,n.source)),n.originalLine=s.line,n.originalColumn=s.column,null!=s.name&&(n.name=s.name))}var l=n.source;null==l||a.has(l)||a.add(l);var c=n.name;null==c||u.has(c)||u.add(c)},this),this._sources=a,this._names=u,e.sources.forEach(function(n){var t=e.sourceContentFor(n);null!=t&&(null!=r&&(n=i.join(r,n)),null!=o&&(n=i.relative(o,n)),this.setSourceContent(n,t))},this)},t.prototype._validateMapping=function(e,n,r,t){if(n&&"number"!=typeof n.line&&"number"!=typeof n.column)throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||n||r||t)&&!(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:n,name:t}))},t.prototype._serializeMappings=function(){for(var e,n,r,t,s=0,a=1,u=0,l=0,c=0,g=0,p="",h=this._mappings.toArray(),f=0,d=h.length;f0){if(!i.compareByGeneratedPositionsInflated(n,h[f-1]))continue;e+=","}e+=o.encode(n.generatedColumn-s),s=n.generatedColumn,null!=n.source&&(t=this._sources.indexOf(n.source),e+=o.encode(t-g),g=t,e+=o.encode(n.originalLine-1-l),l=n.originalLine-1,e+=o.encode(n.originalColumn-u),u=n.originalColumn,null!=n.name&&(r=this._names.indexOf(n.name),e+=o.encode(r-c),c=r)),p+=e}return p},t.prototype._generateSourcesContent=function(e,n){return e.map(function(e){if(!this._sourcesContents)return null;null!=n&&(e=i.relative(n,e));var r=i.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},t.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},t.prototype.toString=function(){return JSON.stringify(this.toJSON())},n.SourceMapGenerator=t},function(e,n,r){function t(e){return e<0?(-e<<1)+1:(e<<1)+0}function o(e){var n=1===(1&e),r=e>>1;return n?-r:r}var i=r(3),s=5,a=1<>>=s,o>0&&(n|=l),r+=i.encode(n);while(o>0);return r},n.decode=function(e,n,r){var t,a,c=e.length,g=0,p=0;do{if(n>=c)throw new Error("Expected more digits in base 64 VLQ value.");if(a=i.decode(e.charCodeAt(n++)),a===-1)throw new Error("Invalid base64 digit: "+e.charAt(n-1));t=!!(a&l),a&=u,g+=a<=0;c--)s=u[c],"."===s?u.splice(c,1):".."===s?l++:l>0&&(""===s?(u.splice(c+1,l),l=0):(u.splice(c,2),l--));return r=u.join("/"),""===r&&(r=a?"/":"."),i?(i.path=r,o(i)):r}function s(e,n){""===e&&(e="."),""===n&&(n=".");var r=t(n),s=t(e);if(s&&(e=s.path||"/"),r&&!r.scheme)return s&&(r.scheme=s.scheme),o(r);if(r||n.match(y))return n;if(s&&!s.host&&!s.path)return s.host=n,o(s);var a="/"===n.charAt(0)?n:i(e.replace(/\/+$/,"")+"/"+n);return s?(s.path=a,o(s)):a}function a(e,n){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==n.indexOf(e+"/");){var t=e.lastIndexOf("/");if(t<0)return n;if(e=e.slice(0,t),e.match(/^([^\/]+:\/)?\/*$/))return n;++r}return Array(r+1).join("../")+n.substr(e.length+1)}function u(e){return e}function l(e){return g(e)?"$"+e:e}function c(e){return g(e)?e.slice(1):e}function g(e){if(!e)return!1;var n=e.length;if(n<9)return!1;if(95!==e.charCodeAt(n-1)||95!==e.charCodeAt(n-2)||111!==e.charCodeAt(n-3)||116!==e.charCodeAt(n-4)||111!==e.charCodeAt(n-5)||114!==e.charCodeAt(n-6)||112!==e.charCodeAt(n-7)||95!==e.charCodeAt(n-8)||95!==e.charCodeAt(n-9))return!1;for(var r=n-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function p(e,n,r){var t=f(e.source,n.source);return 0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t||r?t:(t=e.generatedColumn-n.generatedColumn,0!==t?t:(t=e.generatedLine-n.generatedLine,0!==t?t:f(e.name,n.name)))))}function h(e,n,r){var t=e.generatedLine-n.generatedLine;return 0!==t?t:(t=e.generatedColumn-n.generatedColumn,0!==t||r?t:(t=f(e.source,n.source),0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t?t:f(e.name,n.name)))))}function f(e,n){return e===n?0:null===e?1:null===n?-1:e>n?1:-1}function d(e,n){var r=e.generatedLine-n.generatedLine;return 0!==r?r:(r=e.generatedColumn-n.generatedColumn,0!==r?r:(r=f(e.source,n.source),0!==r?r:(r=e.originalLine-n.originalLine,0!==r?r:(r=e.originalColumn-n.originalColumn,0!==r?r:f(e.name,n.name)))))}function m(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,""))}function _(e,n,r){if(n=n||"",e&&("/"!==e[e.length-1]&&"/"!==n[0]&&(e+="/"),n=e+n),r){var a=t(r);if(!a)throw new Error("sourceMapURL could not be parsed");if(a.path){var u=a.path.lastIndexOf("/");u>=0&&(a.path=a.path.substring(0,u+1))}n=s(o(a),n)}return i(n)}n.getArg=r;var v=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,y=/^data:.+\,.+$/;n.urlParse=t,n.urlGenerate=o,n.normalize=i,n.join=s,n.isAbsolute=function(e){return"/"===e.charAt(0)||v.test(e)},n.relative=a;var C=function(){var e=Object.create(null);return!("__proto__"in e)}();n.toSetString=C?u:l,n.fromSetString=C?u:c,n.compareByOriginalPositions=p,n.compareByGeneratedPositionsDeflated=h,n.compareByGeneratedPositionsInflated=d,n.parseSourceMapInput=m,n.computeSourceURL=_},function(e,n,r){function t(){this._array=[],this._set=s?new Map:Object.create(null)}var o=r(4),i=Object.prototype.hasOwnProperty,s="undefined"!=typeof Map;t.fromArray=function(e,n){for(var r=new t,o=0,i=e.length;o=0)return n}else{var r=o.toSetString(e);if(i.call(this._set,r))return this._set[r]}throw new Error('"'+e+'" is not in the set.')},t.prototype.at=function(e){if(e>=0&&er||t==r&&s>=o||i.compareByGeneratedPositionsInflated(e,n)<=0}function o(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=r(4);o.prototype.unsortedForEach=function(e,n){this._array.forEach(e,n)},o.prototype.add=function(e){t(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},o.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},n.MappingList=o},function(e,n,r){function t(e,n){var r=e;return"string"==typeof e&&(r=a.parseSourceMapInput(e)),null!=r.sections?new s(r,n):new o(r,n)}function o(e,n){var r=e;"string"==typeof e&&(r=a.parseSourceMapInput(e));var t=a.getArg(r,"version"),o=a.getArg(r,"sources"),i=a.getArg(r,"names",[]),s=a.getArg(r,"sourceRoot",null),u=a.getArg(r,"sourcesContent",null),c=a.getArg(r,"mappings"),g=a.getArg(r,"file",null);if(t!=this._version)throw new Error("Unsupported version: "+t);s&&(s=a.normalize(s)),o=o.map(String).map(a.normalize).map(function(e){return s&&a.isAbsolute(s)&&a.isAbsolute(e)?a.relative(s,e):e}),this._names=l.fromArray(i.map(String),!0),this._sources=l.fromArray(o,!0),this._absoluteSources=this._sources.toArray().map(function(e){return a.computeSourceURL(s,e,n)}),this.sourceRoot=s,this.sourcesContent=u,this._mappings=c,this._sourceMapURL=n,this.file=g}function i(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}function s(e,n){var r=e;"string"==typeof e&&(r=a.parseSourceMapInput(e));var o=a.getArg(r,"version"),i=a.getArg(r,"sections");if(o!=this._version)throw new Error("Unsupported version: "+o);this._sources=new l,this._names=new l;var s={line:-1,column:0};this._sections=i.map(function(e){if(e.url)throw new Error("Support for url field in sections not implemented.");var r=a.getArg(e,"offset"),o=a.getArg(r,"line"),i=a.getArg(r,"column");if(o=0){var i=this._originalMappings[o];if(void 0===e.column)for(var s=i.originalLine;i&&i.originalLine===s;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o];else for(var l=i.originalColumn;i&&i.originalLine===n&&i.originalColumn==l;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o]}return t},n.SourceMapConsumer=t,o.prototype=Object.create(t.prototype),o.prototype.consumer=t,o.prototype._findSourceIndex=function(e){var n=e;if(null!=this.sourceRoot&&(n=a.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);var r;for(r=0;r1&&(r.source=d+o[1],d+=o[1],r.originalLine=h+o[2],h=r.originalLine,r.originalLine+=1,r.originalColumn=f+o[3],f=r.originalColumn,o.length>4&&(r.name=m+o[4],m+=o[4])),A.push(r),"number"==typeof r.originalLine&&S.push(r)}g(A,a.compareByGeneratedPositionsDeflated),this.__generatedMappings=A,g(S,a.compareByOriginalPositions),this.__originalMappings=S},o.prototype._findMapping=function(e,n,r,t,o,i){if(e[r]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[r]);if(e[t]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[t]);return u.search(e,n,o,i)},o.prototype.computeColumnSpans=function(){for(var e=0;e=0){var o=this._generatedMappings[r];if(o.generatedLine===n.generatedLine){var i=a.getArg(o,"source",null);null!==i&&(i=this._sources.at(i),i=a.computeSourceURL(this.sourceRoot,i,this._sourceMapURL));var s=a.getArg(o,"name",null);return null!==s&&(s=this._names.at(s)),{source:i,line:a.getArg(o,"originalLine",null),column:a.getArg(o,"originalColumn",null),name:s}}}return{source:null,line:null,column:null,name:null}},o.prototype.hasContentsOfAllSources=function(){return!!this.sourcesContent&&(this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}))},o.prototype.sourceContentFor=function(e,n){if(!this.sourcesContent)return null;var r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];var t=e;null!=this.sourceRoot&&(t=a.relative(this.sourceRoot,t));var o;if(null!=this.sourceRoot&&(o=a.urlParse(this.sourceRoot))){var i=t.replace(/^file:\/\//,"");if("file"==o.scheme&&this._sources.has(i))return this.sourcesContent[this._sources.indexOf(i)];if((!o.path||"/"==o.path)&&this._sources.has("/"+t))return this.sourcesContent[this._sources.indexOf("/"+t)]}if(n)return null;throw new Error('"'+t+'" is not in the SourceMap.')},o.prototype.generatedPositionFor=function(e){var n=a.getArg(e,"source");if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};var r={source:n,originalLine:a.getArg(e,"line"),originalColumn:a.getArg(e,"column")},o=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",a.compareByOriginalPositions,a.getArg(e,"bias",t.GREATEST_LOWER_BOUND));if(o>=0){var i=this._originalMappings[o];if(i.source===r.source)return{line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},n.BasicSourceMapConsumer=o,s.prototype=Object.create(t.prototype),s.prototype.constructor=t,s.prototype._version=3,Object.defineProperty(s.prototype,"sources",{get:function(){for(var e=[],n=0;n0?t-u>1?r(u,t,o,i,s,a):a==n.LEAST_UPPER_BOUND?t1?r(e,u,o,i,s,a):a==n.LEAST_UPPER_BOUND?u:e<0?-1:e}n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2,n.search=function(e,t,o,i){if(0===t.length)return-1;var s=r(-1,t.length,e,t,o,i||n.GREATEST_LOWER_BOUND);if(s<0)return-1;for(;s-1>=0&&0===o(t[s],t[s-1],!0);)--s;return s}},function(e,n){function r(e,n,r){var t=e[n];e[n]=e[r],e[r]=t}function t(e,n){return Math.round(e+Math.random()*(n-e))}function o(e,n,i,s){if(i=0;n--)this.prepend(e[n]);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},t.prototype.walk=function(e){for(var n,r=0,t=this.children.length;r0){for(n=[],r=0;r 0 && aGenerated.column >= 0\n\t && !aOriginal && !aSource && !aName) {\n\t // Case 1.\n\t return;\n\t }\n\t else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n\t && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n\t && aGenerated.line > 0 && aGenerated.column >= 0\n\t && aOriginal.line > 0 && aOriginal.column >= 0\n\t && aSource) {\n\t // Cases 2 and 3.\n\t return;\n\t }\n\t else {\n\t throw new Error('Invalid mapping: ' + JSON.stringify({\n\t generated: aGenerated,\n\t source: aSource,\n\t original: aOriginal,\n\t name: aName\n\t }));\n\t }\n\t };\n\t\n\t/**\n\t * Serialize the accumulated mappings in to the stream of base 64 VLQs\n\t * specified by the source map format.\n\t */\n\tSourceMapGenerator.prototype._serializeMappings =\n\t function SourceMapGenerator_serializeMappings() {\n\t var previousGeneratedColumn = 0;\n\t var previousGeneratedLine = 1;\n\t var previousOriginalColumn = 0;\n\t var previousOriginalLine = 0;\n\t var previousName = 0;\n\t var previousSource = 0;\n\t var result = '';\n\t var next;\n\t var mapping;\n\t var nameIdx;\n\t var sourceIdx;\n\t\n\t var mappings = this._mappings.toArray();\n\t for (var i = 0, len = mappings.length; i < len; i++) {\n\t mapping = mappings[i];\n\t next = ''\n\t\n\t if (mapping.generatedLine !== previousGeneratedLine) {\n\t previousGeneratedColumn = 0;\n\t while (mapping.generatedLine !== previousGeneratedLine) {\n\t next += ';';\n\t previousGeneratedLine++;\n\t }\n\t }\n\t else {\n\t if (i > 0) {\n\t if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n\t continue;\n\t }\n\t next += ',';\n\t }\n\t }\n\t\n\t next += base64VLQ.encode(mapping.generatedColumn\n\t - previousGeneratedColumn);\n\t previousGeneratedColumn = mapping.generatedColumn;\n\t\n\t if (mapping.source != null) {\n\t sourceIdx = this._sources.indexOf(mapping.source);\n\t next += base64VLQ.encode(sourceIdx - previousSource);\n\t previousSource = sourceIdx;\n\t\n\t // lines are stored 0-based in SourceMap spec version 3\n\t next += base64VLQ.encode(mapping.originalLine - 1\n\t - previousOriginalLine);\n\t previousOriginalLine = mapping.originalLine - 1;\n\t\n\t next += base64VLQ.encode(mapping.originalColumn\n\t - previousOriginalColumn);\n\t previousOriginalColumn = mapping.originalColumn;\n\t\n\t if (mapping.name != null) {\n\t nameIdx = this._names.indexOf(mapping.name);\n\t next += base64VLQ.encode(nameIdx - previousName);\n\t previousName = nameIdx;\n\t }\n\t }\n\t\n\t result += next;\n\t }\n\t\n\t return result;\n\t };\n\t\n\tSourceMapGenerator.prototype._generateSourcesContent =\n\t function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n\t return aSources.map(function (source) {\n\t if (!this._sourcesContents) {\n\t return null;\n\t }\n\t if (aSourceRoot != null) {\n\t source = util.relative(aSourceRoot, source);\n\t }\n\t var key = util.toSetString(source);\n\t return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n\t ? this._sourcesContents[key]\n\t : null;\n\t }, this);\n\t };\n\t\n\t/**\n\t * Externalize the source map.\n\t */\n\tSourceMapGenerator.prototype.toJSON =\n\t function SourceMapGenerator_toJSON() {\n\t var map = {\n\t version: this._version,\n\t sources: this._sources.toArray(),\n\t names: this._names.toArray(),\n\t mappings: this._serializeMappings()\n\t };\n\t if (this._file != null) {\n\t map.file = this._file;\n\t }\n\t if (this._sourceRoot != null) {\n\t map.sourceRoot = this._sourceRoot;\n\t }\n\t if (this._sourcesContents) {\n\t map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n\t }\n\t\n\t return map;\n\t };\n\t\n\t/**\n\t * Render the source map being generated to a string.\n\t */\n\tSourceMapGenerator.prototype.toString =\n\t function SourceMapGenerator_toString() {\n\t return JSON.stringify(this.toJSON());\n\t };\n\t\n\texports.SourceMapGenerator = SourceMapGenerator;\n\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t *\n\t * Based on the Base 64 VLQ implementation in Closure Compiler:\n\t * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n\t *\n\t * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n\t * Redistribution and use in source and binary forms, with or without\n\t * modification, are permitted provided that the following conditions are\n\t * met:\n\t *\n\t * * Redistributions of source code must retain the above copyright\n\t * notice, this list of conditions and the following disclaimer.\n\t * * Redistributions in binary form must reproduce the above\n\t * copyright notice, this list of conditions and the following\n\t * disclaimer in the documentation and/or other materials provided\n\t * with the distribution.\n\t * * Neither the name of Google Inc. nor the names of its\n\t * contributors may be used to endorse or promote products derived\n\t * from this software without specific prior written permission.\n\t *\n\t * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\t * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\t * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\t * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\t * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\t * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\t * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\t * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\t * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\t * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\t * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\t */\n\t\n\tvar base64 = __webpack_require__(3);\n\t\n\t// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n\t// length quantities we use in the source map spec, the first bit is the sign,\n\t// the next four bits are the actual value, and the 6th bit is the\n\t// continuation bit. The continuation bit tells us whether there are more\n\t// digits in this value following this digit.\n\t//\n\t// Continuation\n\t// | Sign\n\t// | |\n\t// V V\n\t// 101011\n\t\n\tvar VLQ_BASE_SHIFT = 5;\n\t\n\t// binary: 100000\n\tvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\t\n\t// binary: 011111\n\tvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\t\n\t// binary: 100000\n\tvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\t\n\t/**\n\t * Converts from a two-complement value to a value where the sign bit is\n\t * placed in the least significant bit. For example, as decimals:\n\t * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n\t * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n\t */\n\tfunction toVLQSigned(aValue) {\n\t return aValue < 0\n\t ? ((-aValue) << 1) + 1\n\t : (aValue << 1) + 0;\n\t}\n\t\n\t/**\n\t * Converts to a two-complement value from a value where the sign bit is\n\t * placed in the least significant bit. For example, as decimals:\n\t * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n\t * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n\t */\n\tfunction fromVLQSigned(aValue) {\n\t var isNegative = (aValue & 1) === 1;\n\t var shifted = aValue >> 1;\n\t return isNegative\n\t ? -shifted\n\t : shifted;\n\t}\n\t\n\t/**\n\t * Returns the base 64 VLQ encoded value.\n\t */\n\texports.encode = function base64VLQ_encode(aValue) {\n\t var encoded = \"\";\n\t var digit;\n\t\n\t var vlq = toVLQSigned(aValue);\n\t\n\t do {\n\t digit = vlq & VLQ_BASE_MASK;\n\t vlq >>>= VLQ_BASE_SHIFT;\n\t if (vlq > 0) {\n\t // There are still more digits in this value, so we must make sure the\n\t // continuation bit is marked.\n\t digit |= VLQ_CONTINUATION_BIT;\n\t }\n\t encoded += base64.encode(digit);\n\t } while (vlq > 0);\n\t\n\t return encoded;\n\t};\n\t\n\t/**\n\t * Decodes the next base 64 VLQ value from the given string and returns the\n\t * value and the rest of the string via the out parameter.\n\t */\n\texports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n\t var strLen = aStr.length;\n\t var result = 0;\n\t var shift = 0;\n\t var continuation, digit;\n\t\n\t do {\n\t if (aIndex >= strLen) {\n\t throw new Error(\"Expected more digits in base 64 VLQ value.\");\n\t }\n\t\n\t digit = base64.decode(aStr.charCodeAt(aIndex++));\n\t if (digit === -1) {\n\t throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n\t }\n\t\n\t continuation = !!(digit & VLQ_CONTINUATION_BIT);\n\t digit &= VLQ_BASE_MASK;\n\t result = result + (digit << shift);\n\t shift += VLQ_BASE_SHIFT;\n\t } while (continuation);\n\t\n\t aOutParam.value = fromVLQSigned(result);\n\t aOutParam.rest = aIndex;\n\t};\n\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\t\n\t/**\n\t * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n\t */\n\texports.encode = function (number) {\n\t if (0 <= number && number < intToCharMap.length) {\n\t return intToCharMap[number];\n\t }\n\t throw new TypeError(\"Must be between 0 and 63: \" + number);\n\t};\n\t\n\t/**\n\t * Decode a single base 64 character code digit to an integer. Returns -1 on\n\t * failure.\n\t */\n\texports.decode = function (charCode) {\n\t var bigA = 65; // 'A'\n\t var bigZ = 90; // 'Z'\n\t\n\t var littleA = 97; // 'a'\n\t var littleZ = 122; // 'z'\n\t\n\t var zero = 48; // '0'\n\t var nine = 57; // '9'\n\t\n\t var plus = 43; // '+'\n\t var slash = 47; // '/'\n\t\n\t var littleOffset = 26;\n\t var numberOffset = 52;\n\t\n\t // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n\t if (bigA <= charCode && charCode <= bigZ) {\n\t return (charCode - bigA);\n\t }\n\t\n\t // 26 - 51: abcdefghijklmnopqrstuvwxyz\n\t if (littleA <= charCode && charCode <= littleZ) {\n\t return (charCode - littleA + littleOffset);\n\t }\n\t\n\t // 52 - 61: 0123456789\n\t if (zero <= charCode && charCode <= nine) {\n\t return (charCode - zero + numberOffset);\n\t }\n\t\n\t // 62: +\n\t if (charCode == plus) {\n\t return 62;\n\t }\n\t\n\t // 63: /\n\t if (charCode == slash) {\n\t return 63;\n\t }\n\t\n\t // Invalid base64 digit.\n\t return -1;\n\t};\n\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\t/**\n\t * This is a helper function for getting values from parameter/options\n\t * objects.\n\t *\n\t * @param args The object we are extracting values from\n\t * @param name The name of the property we are getting.\n\t * @param defaultValue An optional value to return if the property is missing\n\t * from the object. If this is not specified and the property is missing, an\n\t * error will be thrown.\n\t */\n\tfunction getArg(aArgs, aName, aDefaultValue) {\n\t if (aName in aArgs) {\n\t return aArgs[aName];\n\t } else if (arguments.length === 3) {\n\t return aDefaultValue;\n\t } else {\n\t throw new Error('\"' + aName + '\" is a required argument.');\n\t }\n\t}\n\texports.getArg = getArg;\n\t\n\tvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\n\tvar dataUrlRegexp = /^data:.+\\,.+$/;\n\t\n\tfunction urlParse(aUrl) {\n\t var match = aUrl.match(urlRegexp);\n\t if (!match) {\n\t return null;\n\t }\n\t return {\n\t scheme: match[1],\n\t auth: match[2],\n\t host: match[3],\n\t port: match[4],\n\t path: match[5]\n\t };\n\t}\n\texports.urlParse = urlParse;\n\t\n\tfunction urlGenerate(aParsedUrl) {\n\t var url = '';\n\t if (aParsedUrl.scheme) {\n\t url += aParsedUrl.scheme + ':';\n\t }\n\t url += '//';\n\t if (aParsedUrl.auth) {\n\t url += aParsedUrl.auth + '@';\n\t }\n\t if (aParsedUrl.host) {\n\t url += aParsedUrl.host;\n\t }\n\t if (aParsedUrl.port) {\n\t url += \":\" + aParsedUrl.port\n\t }\n\t if (aParsedUrl.path) {\n\t url += aParsedUrl.path;\n\t }\n\t return url;\n\t}\n\texports.urlGenerate = urlGenerate;\n\t\n\t/**\n\t * Normalizes a path, or the path portion of a URL:\n\t *\n\t * - Replaces consecutive slashes with one slash.\n\t * - Removes unnecessary '.' parts.\n\t * - Removes unnecessary '/..' parts.\n\t *\n\t * Based on code in the Node.js 'path' core module.\n\t *\n\t * @param aPath The path or url to normalize.\n\t */\n\tfunction normalize(aPath) {\n\t var path = aPath;\n\t var url = urlParse(aPath);\n\t if (url) {\n\t if (!url.path) {\n\t return aPath;\n\t }\n\t path = url.path;\n\t }\n\t var isAbsolute = exports.isAbsolute(path);\n\t\n\t var parts = path.split(/\\/+/);\n\t for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n\t part = parts[i];\n\t if (part === '.') {\n\t parts.splice(i, 1);\n\t } else if (part === '..') {\n\t up++;\n\t } else if (up > 0) {\n\t if (part === '') {\n\t // The first part is blank if the path is absolute. Trying to go\n\t // above the root is a no-op. Therefore we can remove all '..' parts\n\t // directly after the root.\n\t parts.splice(i + 1, up);\n\t up = 0;\n\t } else {\n\t parts.splice(i, 2);\n\t up--;\n\t }\n\t }\n\t }\n\t path = parts.join('/');\n\t\n\t if (path === '') {\n\t path = isAbsolute ? '/' : '.';\n\t }\n\t\n\t if (url) {\n\t url.path = path;\n\t return urlGenerate(url);\n\t }\n\t return path;\n\t}\n\texports.normalize = normalize;\n\t\n\t/**\n\t * Joins two paths/URLs.\n\t *\n\t * @param aRoot The root path or URL.\n\t * @param aPath The path or URL to be joined with the root.\n\t *\n\t * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n\t * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n\t * first.\n\t * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n\t * is updated with the result and aRoot is returned. Otherwise the result\n\t * is returned.\n\t * - If aPath is absolute, the result is aPath.\n\t * - Otherwise the two paths are joined with a slash.\n\t * - Joining for example 'http://' and 'www.example.com' is also supported.\n\t */\n\tfunction join(aRoot, aPath) {\n\t if (aRoot === \"\") {\n\t aRoot = \".\";\n\t }\n\t if (aPath === \"\") {\n\t aPath = \".\";\n\t }\n\t var aPathUrl = urlParse(aPath);\n\t var aRootUrl = urlParse(aRoot);\n\t if (aRootUrl) {\n\t aRoot = aRootUrl.path || '/';\n\t }\n\t\n\t // `join(foo, '//www.example.org')`\n\t if (aPathUrl && !aPathUrl.scheme) {\n\t if (aRootUrl) {\n\t aPathUrl.scheme = aRootUrl.scheme;\n\t }\n\t return urlGenerate(aPathUrl);\n\t }\n\t\n\t if (aPathUrl || aPath.match(dataUrlRegexp)) {\n\t return aPath;\n\t }\n\t\n\t // `join('http://', 'www.example.com')`\n\t if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n\t aRootUrl.host = aPath;\n\t return urlGenerate(aRootUrl);\n\t }\n\t\n\t var joined = aPath.charAt(0) === '/'\n\t ? aPath\n\t : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\t\n\t if (aRootUrl) {\n\t aRootUrl.path = joined;\n\t return urlGenerate(aRootUrl);\n\t }\n\t return joined;\n\t}\n\texports.join = join;\n\t\n\texports.isAbsolute = function (aPath) {\n\t return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n\t};\n\t\n\t/**\n\t * Make a path relative to a URL or another path.\n\t *\n\t * @param aRoot The root path or URL.\n\t * @param aPath The path or URL to be made relative to aRoot.\n\t */\n\tfunction relative(aRoot, aPath) {\n\t if (aRoot === \"\") {\n\t aRoot = \".\";\n\t }\n\t\n\t aRoot = aRoot.replace(/\\/$/, '');\n\t\n\t // It is possible for the path to be above the root. In this case, simply\n\t // checking whether the root is a prefix of the path won't work. Instead, we\n\t // need to remove components from the root one by one, until either we find\n\t // a prefix that fits, or we run out of components to remove.\n\t var level = 0;\n\t while (aPath.indexOf(aRoot + '/') !== 0) {\n\t var index = aRoot.lastIndexOf(\"/\");\n\t if (index < 0) {\n\t return aPath;\n\t }\n\t\n\t // If the only part of the root that is left is the scheme (i.e. http://,\n\t // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n\t // have exhausted all components, so the path is not relative to the root.\n\t aRoot = aRoot.slice(0, index);\n\t if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n\t return aPath;\n\t }\n\t\n\t ++level;\n\t }\n\t\n\t // Make sure we add a \"../\" for each component we removed from the root.\n\t return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n\t}\n\texports.relative = relative;\n\t\n\tvar supportsNullProto = (function () {\n\t var obj = Object.create(null);\n\t return !('__proto__' in obj);\n\t}());\n\t\n\tfunction identity (s) {\n\t return s;\n\t}\n\t\n\t/**\n\t * Because behavior goes wacky when you set `__proto__` on objects, we\n\t * have to prefix all the strings in our set with an arbitrary character.\n\t *\n\t * See https://github.com/mozilla/source-map/pull/31 and\n\t * https://github.com/mozilla/source-map/issues/30\n\t *\n\t * @param String aStr\n\t */\n\tfunction toSetString(aStr) {\n\t if (isProtoString(aStr)) {\n\t return '$' + aStr;\n\t }\n\t\n\t return aStr;\n\t}\n\texports.toSetString = supportsNullProto ? identity : toSetString;\n\t\n\tfunction fromSetString(aStr) {\n\t if (isProtoString(aStr)) {\n\t return aStr.slice(1);\n\t }\n\t\n\t return aStr;\n\t}\n\texports.fromSetString = supportsNullProto ? identity : fromSetString;\n\t\n\tfunction isProtoString(s) {\n\t if (!s) {\n\t return false;\n\t }\n\t\n\t var length = s.length;\n\t\n\t if (length < 9 /* \"__proto__\".length */) {\n\t return false;\n\t }\n\t\n\t if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n\t s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n\t s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n\t s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n\t s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n\t s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 9) !== 95 /* '_' */) {\n\t return false;\n\t }\n\t\n\t for (var i = length - 10; i >= 0; i--) {\n\t if (s.charCodeAt(i) !== 36 /* '$' */) {\n\t return false;\n\t }\n\t }\n\t\n\t return true;\n\t}\n\t\n\t/**\n\t * Comparator between two mappings where the original positions are compared.\n\t *\n\t * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n\t * mappings with the same original source/line/column, but different generated\n\t * line and column the same. Useful when searching for a mapping with a\n\t * stubbed out mapping.\n\t */\n\tfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n\t var cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0 || onlyCompareOriginal) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByOriginalPositions = compareByOriginalPositions;\n\t\n\t/**\n\t * Comparator between two mappings with deflated source and name indices where\n\t * the generated positions are compared.\n\t *\n\t * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n\t * mappings with the same generated line and column, but different\n\t * source/name/original line and column the same. Useful when searching for a\n\t * mapping with a stubbed out mapping.\n\t */\n\tfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n\t var cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0 || onlyCompareGenerated) {\n\t return cmp;\n\t }\n\t\n\t cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\t\n\tfunction strcmp(aStr1, aStr2) {\n\t if (aStr1 === aStr2) {\n\t return 0;\n\t }\n\t\n\t if (aStr1 === null) {\n\t return 1; // aStr2 !== null\n\t }\n\t\n\t if (aStr2 === null) {\n\t return -1; // aStr1 !== null\n\t }\n\t\n\t if (aStr1 > aStr2) {\n\t return 1;\n\t }\n\t\n\t return -1;\n\t}\n\t\n\t/**\n\t * Comparator between two mappings with inflated source and name strings where\n\t * the generated positions are compared.\n\t */\n\tfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n\t var cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\t\n\t/**\n\t * Strip any JSON XSSI avoidance prefix from the string (as documented\n\t * in the source maps specification), and then parse the string as\n\t * JSON.\n\t */\n\tfunction parseSourceMapInput(str) {\n\t return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n\t}\n\texports.parseSourceMapInput = parseSourceMapInput;\n\t\n\t/**\n\t * Compute the URL of a source given the the source root, the source's\n\t * URL, and the source map's URL.\n\t */\n\tfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n\t sourceURL = sourceURL || '';\n\t\n\t if (sourceRoot) {\n\t // This follows what Chrome does.\n\t if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n\t sourceRoot += '/';\n\t }\n\t // The spec says:\n\t // Line 4: An optional source root, useful for relocating source\n\t // files on a server or removing repeated values in the\n\t // “sources” entry. This value is prepended to the individual\n\t // entries in the “source” field.\n\t sourceURL = sourceRoot + sourceURL;\n\t }\n\t\n\t // Historically, SourceMapConsumer did not take the sourceMapURL as\n\t // a parameter. This mode is still somewhat supported, which is why\n\t // this code block is conditional. However, it's preferable to pass\n\t // the source map URL to SourceMapConsumer, so that this function\n\t // can implement the source URL resolution algorithm as outlined in\n\t // the spec. This block is basically the equivalent of:\n\t // new URL(sourceURL, sourceMapURL).toString()\n\t // ... except it avoids using URL, which wasn't available in the\n\t // older releases of node still supported by this library.\n\t //\n\t // The spec says:\n\t // If the sources are not absolute URLs after prepending of the\n\t // “sourceRoot”, the sources are resolved relative to the\n\t // SourceMap (like resolving script src in a html document).\n\t if (sourceMapURL) {\n\t var parsed = urlParse(sourceMapURL);\n\t if (!parsed) {\n\t throw new Error(\"sourceMapURL could not be parsed\");\n\t }\n\t if (parsed.path) {\n\t // Strip the last path component, but keep the \"/\".\n\t var index = parsed.path.lastIndexOf('/');\n\t if (index >= 0) {\n\t parsed.path = parsed.path.substring(0, index + 1);\n\t }\n\t }\n\t sourceURL = join(urlGenerate(parsed), sourceURL);\n\t }\n\t\n\t return normalize(sourceURL);\n\t}\n\texports.computeSourceURL = computeSourceURL;\n\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\tvar has = Object.prototype.hasOwnProperty;\n\tvar hasNativeMap = typeof Map !== \"undefined\";\n\t\n\t/**\n\t * A data structure which is a combination of an array and a set. Adding a new\n\t * member is O(1), testing for membership is O(1), and finding the index of an\n\t * element is O(1). Removing elements from the set is not supported. Only\n\t * strings are supported for membership.\n\t */\n\tfunction ArraySet() {\n\t this._array = [];\n\t this._set = hasNativeMap ? new Map() : Object.create(null);\n\t}\n\t\n\t/**\n\t * Static method for creating ArraySet instances from an existing array.\n\t */\n\tArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n\t var set = new ArraySet();\n\t for (var i = 0, len = aArray.length; i < len; i++) {\n\t set.add(aArray[i], aAllowDuplicates);\n\t }\n\t return set;\n\t};\n\t\n\t/**\n\t * Return how many unique items are in this ArraySet. If duplicates have been\n\t * added, than those do not count towards the size.\n\t *\n\t * @returns Number\n\t */\n\tArraySet.prototype.size = function ArraySet_size() {\n\t return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n\t};\n\t\n\t/**\n\t * Add the given string to this set.\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n\t var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n\t var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n\t var idx = this._array.length;\n\t if (!isDuplicate || aAllowDuplicates) {\n\t this._array.push(aStr);\n\t }\n\t if (!isDuplicate) {\n\t if (hasNativeMap) {\n\t this._set.set(aStr, idx);\n\t } else {\n\t this._set[sStr] = idx;\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Is the given string a member of this set?\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.has = function ArraySet_has(aStr) {\n\t if (hasNativeMap) {\n\t return this._set.has(aStr);\n\t } else {\n\t var sStr = util.toSetString(aStr);\n\t return has.call(this._set, sStr);\n\t }\n\t};\n\t\n\t/**\n\t * What is the index of the given string in the array?\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n\t if (hasNativeMap) {\n\t var idx = this._set.get(aStr);\n\t if (idx >= 0) {\n\t return idx;\n\t }\n\t } else {\n\t var sStr = util.toSetString(aStr);\n\t if (has.call(this._set, sStr)) {\n\t return this._set[sStr];\n\t }\n\t }\n\t\n\t throw new Error('\"' + aStr + '\" is not in the set.');\n\t};\n\t\n\t/**\n\t * What is the element at the given index?\n\t *\n\t * @param Number aIdx\n\t */\n\tArraySet.prototype.at = function ArraySet_at(aIdx) {\n\t if (aIdx >= 0 && aIdx < this._array.length) {\n\t return this._array[aIdx];\n\t }\n\t throw new Error('No element indexed by ' + aIdx);\n\t};\n\t\n\t/**\n\t * Returns the array representation of this set (which has the proper indices\n\t * indicated by indexOf). Note that this is a copy of the internal array used\n\t * for storing the members so that no one can mess with internal state.\n\t */\n\tArraySet.prototype.toArray = function ArraySet_toArray() {\n\t return this._array.slice();\n\t};\n\t\n\texports.ArraySet = ArraySet;\n\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2014 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\t\n\t/**\n\t * Determine whether mappingB is after mappingA with respect to generated\n\t * position.\n\t */\n\tfunction generatedPositionAfter(mappingA, mappingB) {\n\t // Optimized for most common case\n\t var lineA = mappingA.generatedLine;\n\t var lineB = mappingB.generatedLine;\n\t var columnA = mappingA.generatedColumn;\n\t var columnB = mappingB.generatedColumn;\n\t return lineB > lineA || lineB == lineA && columnB >= columnA ||\n\t util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n\t}\n\t\n\t/**\n\t * A data structure to provide a sorted view of accumulated mappings in a\n\t * performance conscious manner. It trades a neglibable overhead in general\n\t * case for a large speedup in case of mappings being added in order.\n\t */\n\tfunction MappingList() {\n\t this._array = [];\n\t this._sorted = true;\n\t // Serves as infimum\n\t this._last = {generatedLine: -1, generatedColumn: 0};\n\t}\n\t\n\t/**\n\t * Iterate through internal items. This method takes the same arguments that\n\t * `Array.prototype.forEach` takes.\n\t *\n\t * NOTE: The order of the mappings is NOT guaranteed.\n\t */\n\tMappingList.prototype.unsortedForEach =\n\t function MappingList_forEach(aCallback, aThisArg) {\n\t this._array.forEach(aCallback, aThisArg);\n\t };\n\t\n\t/**\n\t * Add the given source mapping.\n\t *\n\t * @param Object aMapping\n\t */\n\tMappingList.prototype.add = function MappingList_add(aMapping) {\n\t if (generatedPositionAfter(this._last, aMapping)) {\n\t this._last = aMapping;\n\t this._array.push(aMapping);\n\t } else {\n\t this._sorted = false;\n\t this._array.push(aMapping);\n\t }\n\t};\n\t\n\t/**\n\t * Returns the flat, sorted array of mappings. The mappings are sorted by\n\t * generated position.\n\t *\n\t * WARNING: This method returns internal data without copying, for\n\t * performance. The return value must NOT be mutated, and should be treated as\n\t * an immutable borrow. If you want to take ownership, you must make your own\n\t * copy.\n\t */\n\tMappingList.prototype.toArray = function MappingList_toArray() {\n\t if (!this._sorted) {\n\t this._array.sort(util.compareByGeneratedPositionsInflated);\n\t this._sorted = true;\n\t }\n\t return this._array;\n\t};\n\t\n\texports.MappingList = MappingList;\n\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\tvar binarySearch = __webpack_require__(8);\n\tvar ArraySet = __webpack_require__(5).ArraySet;\n\tvar base64VLQ = __webpack_require__(2);\n\tvar quickSort = __webpack_require__(9).quickSort;\n\t\n\tfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t return sourceMap.sections != null\n\t ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n\t : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n\t}\n\t\n\tSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n\t return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n\t}\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tSourceMapConsumer.prototype._version = 3;\n\t\n\t// `__generatedMappings` and `__originalMappings` are arrays that hold the\n\t// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n\t// are lazily instantiated, accessed via the `_generatedMappings` and\n\t// `_originalMappings` getters respectively, and we only parse the mappings\n\t// and create these arrays once queried for a source location. We jump through\n\t// these hoops because there can be many thousands of mappings, and parsing\n\t// them is expensive, so we only want to do it if we must.\n\t//\n\t// Each object in the arrays is of the form:\n\t//\n\t// {\n\t// generatedLine: The line number in the generated code,\n\t// generatedColumn: The column number in the generated code,\n\t// source: The path to the original source file that generated this\n\t// chunk of code,\n\t// originalLine: The line number in the original source that\n\t// corresponds to this chunk of generated code,\n\t// originalColumn: The column number in the original source that\n\t// corresponds to this chunk of generated code,\n\t// name: The name of the original symbol which generated this chunk of\n\t// code.\n\t// }\n\t//\n\t// All properties except for `generatedLine` and `generatedColumn` can be\n\t// `null`.\n\t//\n\t// `_generatedMappings` is ordered by the generated positions.\n\t//\n\t// `_originalMappings` is ordered by the original positions.\n\t\n\tSourceMapConsumer.prototype.__generatedMappings = null;\n\tObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n\t configurable: true,\n\t enumerable: true,\n\t get: function () {\n\t if (!this.__generatedMappings) {\n\t this._parseMappings(this._mappings, this.sourceRoot);\n\t }\n\t\n\t return this.__generatedMappings;\n\t }\n\t});\n\t\n\tSourceMapConsumer.prototype.__originalMappings = null;\n\tObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n\t configurable: true,\n\t enumerable: true,\n\t get: function () {\n\t if (!this.__originalMappings) {\n\t this._parseMappings(this._mappings, this.sourceRoot);\n\t }\n\t\n\t return this.__originalMappings;\n\t }\n\t});\n\t\n\tSourceMapConsumer.prototype._charIsMappingSeparator =\n\t function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n\t var c = aStr.charAt(index);\n\t return c === \";\" || c === \",\";\n\t };\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tSourceMapConsumer.prototype._parseMappings =\n\t function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t throw new Error(\"Subclasses must implement _parseMappings\");\n\t };\n\t\n\tSourceMapConsumer.GENERATED_ORDER = 1;\n\tSourceMapConsumer.ORIGINAL_ORDER = 2;\n\t\n\tSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\n\tSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\t\n\t/**\n\t * Iterate over each mapping between an original source/line/column and a\n\t * generated line/column in this source map.\n\t *\n\t * @param Function aCallback\n\t * The function that is called with each mapping.\n\t * @param Object aContext\n\t * Optional. If specified, this object will be the value of `this` every\n\t * time that `aCallback` is called.\n\t * @param aOrder\n\t * Either `SourceMapConsumer.GENERATED_ORDER` or\n\t * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n\t * iterate over the mappings sorted by the generated file's line/column\n\t * order or the original's source/line/column order, respectively. Defaults to\n\t * `SourceMapConsumer.GENERATED_ORDER`.\n\t */\n\tSourceMapConsumer.prototype.eachMapping =\n\t function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n\t var context = aContext || null;\n\t var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\t\n\t var mappings;\n\t switch (order) {\n\t case SourceMapConsumer.GENERATED_ORDER:\n\t mappings = this._generatedMappings;\n\t break;\n\t case SourceMapConsumer.ORIGINAL_ORDER:\n\t mappings = this._originalMappings;\n\t break;\n\t default:\n\t throw new Error(\"Unknown order of iteration.\");\n\t }\n\t\n\t var sourceRoot = this.sourceRoot;\n\t mappings.map(function (mapping) {\n\t var source = mapping.source === null ? null : this._sources.at(mapping.source);\n\t source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n\t return {\n\t source: source,\n\t generatedLine: mapping.generatedLine,\n\t generatedColumn: mapping.generatedColumn,\n\t originalLine: mapping.originalLine,\n\t originalColumn: mapping.originalColumn,\n\t name: mapping.name === null ? null : this._names.at(mapping.name)\n\t };\n\t }, this).forEach(aCallback, context);\n\t };\n\t\n\t/**\n\t * Returns all generated line and column information for the original source,\n\t * line, and column provided. If no column is provided, returns all mappings\n\t * corresponding to a either the line we are searching for or the next\n\t * closest line that has any mappings. Otherwise, returns all mappings\n\t * corresponding to the given line and either the column we are searching for\n\t * or the next closest column that has any offsets.\n\t *\n\t * The only argument is an object with the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number is 1-based.\n\t * - column: Optional. the column number in the original source.\n\t * The column number is 0-based.\n\t *\n\t * and an array of objects is returned, each with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tSourceMapConsumer.prototype.allGeneratedPositionsFor =\n\t function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n\t var line = util.getArg(aArgs, 'line');\n\t\n\t // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n\t // returns the index of the closest mapping less than the needle. By\n\t // setting needle.originalColumn to 0, we thus find the last mapping for\n\t // the given line, provided such a mapping exists.\n\t var needle = {\n\t source: util.getArg(aArgs, 'source'),\n\t originalLine: line,\n\t originalColumn: util.getArg(aArgs, 'column', 0)\n\t };\n\t\n\t needle.source = this._findSourceIndex(needle.source);\n\t if (needle.source < 0) {\n\t return [];\n\t }\n\t\n\t var mappings = [];\n\t\n\t var index = this._findMapping(needle,\n\t this._originalMappings,\n\t \"originalLine\",\n\t \"originalColumn\",\n\t util.compareByOriginalPositions,\n\t binarySearch.LEAST_UPPER_BOUND);\n\t if (index >= 0) {\n\t var mapping = this._originalMappings[index];\n\t\n\t if (aArgs.column === undefined) {\n\t var originalLine = mapping.originalLine;\n\t\n\t // Iterate until either we run out of mappings, or we run into\n\t // a mapping for a different line than the one we found. Since\n\t // mappings are sorted, this is guaranteed to find all mappings for\n\t // the line we found.\n\t while (mapping && mapping.originalLine === originalLine) {\n\t mappings.push({\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t });\n\t\n\t mapping = this._originalMappings[++index];\n\t }\n\t } else {\n\t var originalColumn = mapping.originalColumn;\n\t\n\t // Iterate until either we run out of mappings, or we run into\n\t // a mapping for a different line than the one we were searching for.\n\t // Since mappings are sorted, this is guaranteed to find all mappings for\n\t // the line we are searching for.\n\t while (mapping &&\n\t mapping.originalLine === line &&\n\t mapping.originalColumn == originalColumn) {\n\t mappings.push({\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t });\n\t\n\t mapping = this._originalMappings[++index];\n\t }\n\t }\n\t }\n\t\n\t return mappings;\n\t };\n\t\n\texports.SourceMapConsumer = SourceMapConsumer;\n\t\n\t/**\n\t * A BasicSourceMapConsumer instance represents a parsed source map which we can\n\t * query for information about the original file positions by giving it a file\n\t * position in the generated source.\n\t *\n\t * The first parameter is the raw source map (either as a JSON string, or\n\t * already parsed to an object). According to the spec, source maps have the\n\t * following attributes:\n\t *\n\t * - version: Which version of the source map spec this map is following.\n\t * - sources: An array of URLs to the original source files.\n\t * - names: An array of identifiers which can be referrenced by individual mappings.\n\t * - sourceRoot: Optional. The URL root from which all sources are relative.\n\t * - sourcesContent: Optional. An array of contents of the original source files.\n\t * - mappings: A string of base64 VLQs which contain the actual mappings.\n\t * - file: Optional. The generated file this source map is associated with.\n\t *\n\t * Here is an example source map, taken from the source map spec[0]:\n\t *\n\t * {\n\t * version : 3,\n\t * file: \"out.js\",\n\t * sourceRoot : \"\",\n\t * sources: [\"foo.js\", \"bar.js\"],\n\t * names: [\"src\", \"maps\", \"are\", \"fun\"],\n\t * mappings: \"AA,AB;;ABCDE;\"\n\t * }\n\t *\n\t * The second parameter, if given, is a string whose value is the URL\n\t * at which the source map was found. This URL is used to compute the\n\t * sources array.\n\t *\n\t * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n\t */\n\tfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t var version = util.getArg(sourceMap, 'version');\n\t var sources = util.getArg(sourceMap, 'sources');\n\t // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n\t // requires the array) to play nice here.\n\t var names = util.getArg(sourceMap, 'names', []);\n\t var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n\t var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n\t var mappings = util.getArg(sourceMap, 'mappings');\n\t var file = util.getArg(sourceMap, 'file', null);\n\t\n\t // Once again, Sass deviates from the spec and supplies the version as a\n\t // string rather than a number, so we use loose equality checking here.\n\t if (version != this._version) {\n\t throw new Error('Unsupported version: ' + version);\n\t }\n\t\n\t if (sourceRoot) {\n\t sourceRoot = util.normalize(sourceRoot);\n\t }\n\t\n\t sources = sources\n\t .map(String)\n\t // Some source maps produce relative source paths like \"./foo.js\" instead of\n\t // \"foo.js\". Normalize these first so that future comparisons will succeed.\n\t // See bugzil.la/1090768.\n\t .map(util.normalize)\n\t // Always ensure that absolute sources are internally stored relative to\n\t // the source root, if the source root is absolute. Not doing this would\n\t // be particularly problematic when the source root is a prefix of the\n\t // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n\t .map(function (source) {\n\t return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n\t ? util.relative(sourceRoot, source)\n\t : source;\n\t });\n\t\n\t // Pass `true` below to allow duplicate names and sources. While source maps\n\t // are intended to be compressed and deduplicated, the TypeScript compiler\n\t // sometimes generates source maps with duplicates in them. See Github issue\n\t // #72 and bugzil.la/889492.\n\t this._names = ArraySet.fromArray(names.map(String), true);\n\t this._sources = ArraySet.fromArray(sources, true);\n\t\n\t this._absoluteSources = this._sources.toArray().map(function (s) {\n\t return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n\t });\n\t\n\t this.sourceRoot = sourceRoot;\n\t this.sourcesContent = sourcesContent;\n\t this._mappings = mappings;\n\t this._sourceMapURL = aSourceMapURL;\n\t this.file = file;\n\t}\n\t\n\tBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\n\tBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\t\n\t/**\n\t * Utility function to find the index of a source. Returns -1 if not\n\t * found.\n\t */\n\tBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n\t var relativeSource = aSource;\n\t if (this.sourceRoot != null) {\n\t relativeSource = util.relative(this.sourceRoot, relativeSource);\n\t }\n\t\n\t if (this._sources.has(relativeSource)) {\n\t return this._sources.indexOf(relativeSource);\n\t }\n\t\n\t // Maybe aSource is an absolute URL as returned by |sources|. In\n\t // this case we can't simply undo the transform.\n\t var i;\n\t for (i = 0; i < this._absoluteSources.length; ++i) {\n\t if (this._absoluteSources[i] == aSource) {\n\t return i;\n\t }\n\t }\n\t\n\t return -1;\n\t};\n\t\n\t/**\n\t * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n\t *\n\t * @param SourceMapGenerator aSourceMap\n\t * The source map that will be consumed.\n\t * @param String aSourceMapURL\n\t * The URL at which the source map can be found (optional)\n\t * @returns BasicSourceMapConsumer\n\t */\n\tBasicSourceMapConsumer.fromSourceMap =\n\t function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n\t var smc = Object.create(BasicSourceMapConsumer.prototype);\n\t\n\t var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n\t var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n\t smc.sourceRoot = aSourceMap._sourceRoot;\n\t smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n\t smc.sourceRoot);\n\t smc.file = aSourceMap._file;\n\t smc._sourceMapURL = aSourceMapURL;\n\t smc._absoluteSources = smc._sources.toArray().map(function (s) {\n\t return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n\t });\n\t\n\t // Because we are modifying the entries (by converting string sources and\n\t // names to indices into the sources and names ArraySets), we have to make\n\t // a copy of the entry or else bad things happen. Shared mutable state\n\t // strikes again! See github issue #191.\n\t\n\t var generatedMappings = aSourceMap._mappings.toArray().slice();\n\t var destGeneratedMappings = smc.__generatedMappings = [];\n\t var destOriginalMappings = smc.__originalMappings = [];\n\t\n\t for (var i = 0, length = generatedMappings.length; i < length; i++) {\n\t var srcMapping = generatedMappings[i];\n\t var destMapping = new Mapping;\n\t destMapping.generatedLine = srcMapping.generatedLine;\n\t destMapping.generatedColumn = srcMapping.generatedColumn;\n\t\n\t if (srcMapping.source) {\n\t destMapping.source = sources.indexOf(srcMapping.source);\n\t destMapping.originalLine = srcMapping.originalLine;\n\t destMapping.originalColumn = srcMapping.originalColumn;\n\t\n\t if (srcMapping.name) {\n\t destMapping.name = names.indexOf(srcMapping.name);\n\t }\n\t\n\t destOriginalMappings.push(destMapping);\n\t }\n\t\n\t destGeneratedMappings.push(destMapping);\n\t }\n\t\n\t quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\t\n\t return smc;\n\t };\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tBasicSourceMapConsumer.prototype._version = 3;\n\t\n\t/**\n\t * The list of original sources.\n\t */\n\tObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n\t get: function () {\n\t return this._absoluteSources.slice();\n\t }\n\t});\n\t\n\t/**\n\t * Provide the JIT with a nice shape / hidden class.\n\t */\n\tfunction Mapping() {\n\t this.generatedLine = 0;\n\t this.generatedColumn = 0;\n\t this.source = null;\n\t this.originalLine = null;\n\t this.originalColumn = null;\n\t this.name = null;\n\t}\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tBasicSourceMapConsumer.prototype._parseMappings =\n\t function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t var generatedLine = 1;\n\t var previousGeneratedColumn = 0;\n\t var previousOriginalLine = 0;\n\t var previousOriginalColumn = 0;\n\t var previousSource = 0;\n\t var previousName = 0;\n\t var length = aStr.length;\n\t var index = 0;\n\t var cachedSegments = {};\n\t var temp = {};\n\t var originalMappings = [];\n\t var generatedMappings = [];\n\t var mapping, str, segment, end, value;\n\t\n\t while (index < length) {\n\t if (aStr.charAt(index) === ';') {\n\t generatedLine++;\n\t index++;\n\t previousGeneratedColumn = 0;\n\t }\n\t else if (aStr.charAt(index) === ',') {\n\t index++;\n\t }\n\t else {\n\t mapping = new Mapping();\n\t mapping.generatedLine = generatedLine;\n\t\n\t // Because each offset is encoded relative to the previous one,\n\t // many segments often have the same encoding. We can exploit this\n\t // fact by caching the parsed variable length fields of each segment,\n\t // allowing us to avoid a second parse if we encounter the same\n\t // segment again.\n\t for (end = index; end < length; end++) {\n\t if (this._charIsMappingSeparator(aStr, end)) {\n\t break;\n\t }\n\t }\n\t str = aStr.slice(index, end);\n\t\n\t segment = cachedSegments[str];\n\t if (segment) {\n\t index += str.length;\n\t } else {\n\t segment = [];\n\t while (index < end) {\n\t base64VLQ.decode(aStr, index, temp);\n\t value = temp.value;\n\t index = temp.rest;\n\t segment.push(value);\n\t }\n\t\n\t if (segment.length === 2) {\n\t throw new Error('Found a source, but no line and column');\n\t }\n\t\n\t if (segment.length === 3) {\n\t throw new Error('Found a source and line, but no column');\n\t }\n\t\n\t cachedSegments[str] = segment;\n\t }\n\t\n\t // Generated column.\n\t mapping.generatedColumn = previousGeneratedColumn + segment[0];\n\t previousGeneratedColumn = mapping.generatedColumn;\n\t\n\t if (segment.length > 1) {\n\t // Original source.\n\t mapping.source = previousSource + segment[1];\n\t previousSource += segment[1];\n\t\n\t // Original line.\n\t mapping.originalLine = previousOriginalLine + segment[2];\n\t previousOriginalLine = mapping.originalLine;\n\t // Lines are stored 0-based\n\t mapping.originalLine += 1;\n\t\n\t // Original column.\n\t mapping.originalColumn = previousOriginalColumn + segment[3];\n\t previousOriginalColumn = mapping.originalColumn;\n\t\n\t if (segment.length > 4) {\n\t // Original name.\n\t mapping.name = previousName + segment[4];\n\t previousName += segment[4];\n\t }\n\t }\n\t\n\t generatedMappings.push(mapping);\n\t if (typeof mapping.originalLine === 'number') {\n\t originalMappings.push(mapping);\n\t }\n\t }\n\t }\n\t\n\t quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n\t this.__generatedMappings = generatedMappings;\n\t\n\t quickSort(originalMappings, util.compareByOriginalPositions);\n\t this.__originalMappings = originalMappings;\n\t };\n\t\n\t/**\n\t * Find the mapping that best matches the hypothetical \"needle\" mapping that\n\t * we are searching for in the given \"haystack\" of mappings.\n\t */\n\tBasicSourceMapConsumer.prototype._findMapping =\n\t function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n\t aColumnName, aComparator, aBias) {\n\t // To return the position we are searching for, we must first find the\n\t // mapping for the given position and then return the opposite position it\n\t // points to. Because the mappings are sorted, we can use binary search to\n\t // find the best mapping.\n\t\n\t if (aNeedle[aLineName] <= 0) {\n\t throw new TypeError('Line must be greater than or equal to 1, got '\n\t + aNeedle[aLineName]);\n\t }\n\t if (aNeedle[aColumnName] < 0) {\n\t throw new TypeError('Column must be greater than or equal to 0, got '\n\t + aNeedle[aColumnName]);\n\t }\n\t\n\t return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n\t };\n\t\n\t/**\n\t * Compute the last column for each generated mapping. The last column is\n\t * inclusive.\n\t */\n\tBasicSourceMapConsumer.prototype.computeColumnSpans =\n\t function SourceMapConsumer_computeColumnSpans() {\n\t for (var index = 0; index < this._generatedMappings.length; ++index) {\n\t var mapping = this._generatedMappings[index];\n\t\n\t // Mappings do not contain a field for the last generated columnt. We\n\t // can come up with an optimistic estimate, however, by assuming that\n\t // mappings are contiguous (i.e. given two consecutive mappings, the\n\t // first mapping ends where the second one starts).\n\t if (index + 1 < this._generatedMappings.length) {\n\t var nextMapping = this._generatedMappings[index + 1];\n\t\n\t if (mapping.generatedLine === nextMapping.generatedLine) {\n\t mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n\t continue;\n\t }\n\t }\n\t\n\t // The last mapping for each line spans the entire line.\n\t mapping.lastGeneratedColumn = Infinity;\n\t }\n\t };\n\t\n\t/**\n\t * Returns the original source, line, and column information for the generated\n\t * source's line and column positions provided. The only argument is an object\n\t * with the following properties:\n\t *\n\t * - line: The line number in the generated source. The line number\n\t * is 1-based.\n\t * - column: The column number in the generated source. The column\n\t * number is 0-based.\n\t * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n\t * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - source: The original source file, or null.\n\t * - line: The line number in the original source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the original source, or null. The\n\t * column number is 0-based.\n\t * - name: The original identifier, or null.\n\t */\n\tBasicSourceMapConsumer.prototype.originalPositionFor =\n\t function SourceMapConsumer_originalPositionFor(aArgs) {\n\t var needle = {\n\t generatedLine: util.getArg(aArgs, 'line'),\n\t generatedColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t var index = this._findMapping(\n\t needle,\n\t this._generatedMappings,\n\t \"generatedLine\",\n\t \"generatedColumn\",\n\t util.compareByGeneratedPositionsDeflated,\n\t util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n\t );\n\t\n\t if (index >= 0) {\n\t var mapping = this._generatedMappings[index];\n\t\n\t if (mapping.generatedLine === needle.generatedLine) {\n\t var source = util.getArg(mapping, 'source', null);\n\t if (source !== null) {\n\t source = this._sources.at(source);\n\t source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n\t }\n\t var name = util.getArg(mapping, 'name', null);\n\t if (name !== null) {\n\t name = this._names.at(name);\n\t }\n\t return {\n\t source: source,\n\t line: util.getArg(mapping, 'originalLine', null),\n\t column: util.getArg(mapping, 'originalColumn', null),\n\t name: name\n\t };\n\t }\n\t }\n\t\n\t return {\n\t source: null,\n\t line: null,\n\t column: null,\n\t name: null\n\t };\n\t };\n\t\n\t/**\n\t * Return true if we have the source content for every source in the source\n\t * map, false otherwise.\n\t */\n\tBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n\t function BasicSourceMapConsumer_hasContentsOfAllSources() {\n\t if (!this.sourcesContent) {\n\t return false;\n\t }\n\t return this.sourcesContent.length >= this._sources.size() &&\n\t !this.sourcesContent.some(function (sc) { return sc == null; });\n\t };\n\t\n\t/**\n\t * Returns the original source content. The only argument is the url of the\n\t * original source file. Returns null if no original source content is\n\t * available.\n\t */\n\tBasicSourceMapConsumer.prototype.sourceContentFor =\n\t function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n\t if (!this.sourcesContent) {\n\t return null;\n\t }\n\t\n\t var index = this._findSourceIndex(aSource);\n\t if (index >= 0) {\n\t return this.sourcesContent[index];\n\t }\n\t\n\t var relativeSource = aSource;\n\t if (this.sourceRoot != null) {\n\t relativeSource = util.relative(this.sourceRoot, relativeSource);\n\t }\n\t\n\t var url;\n\t if (this.sourceRoot != null\n\t && (url = util.urlParse(this.sourceRoot))) {\n\t // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n\t // many users. We can help them out when they expect file:// URIs to\n\t // behave like it would if they were running a local HTTP server. See\n\t // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n\t var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n\t if (url.scheme == \"file\"\n\t && this._sources.has(fileUriAbsPath)) {\n\t return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n\t }\n\t\n\t if ((!url.path || url.path == \"/\")\n\t && this._sources.has(\"/\" + relativeSource)) {\n\t return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n\t }\n\t }\n\t\n\t // This function is used recursively from\n\t // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n\t // don't want to throw if we can't find the source - we just want to\n\t // return null, so we provide a flag to exit gracefully.\n\t if (nullOnMissing) {\n\t return null;\n\t }\n\t else {\n\t throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n\t }\n\t };\n\t\n\t/**\n\t * Returns the generated line and column information for the original source,\n\t * line, and column positions provided. The only argument is an object with\n\t * the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number\n\t * is 1-based.\n\t * - column: The column number in the original source. The column\n\t * number is 0-based.\n\t * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n\t * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tBasicSourceMapConsumer.prototype.generatedPositionFor =\n\t function SourceMapConsumer_generatedPositionFor(aArgs) {\n\t var source = util.getArg(aArgs, 'source');\n\t source = this._findSourceIndex(source);\n\t if (source < 0) {\n\t return {\n\t line: null,\n\t column: null,\n\t lastColumn: null\n\t };\n\t }\n\t\n\t var needle = {\n\t source: source,\n\t originalLine: util.getArg(aArgs, 'line'),\n\t originalColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t var index = this._findMapping(\n\t needle,\n\t this._originalMappings,\n\t \"originalLine\",\n\t \"originalColumn\",\n\t util.compareByOriginalPositions,\n\t util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n\t );\n\t\n\t if (index >= 0) {\n\t var mapping = this._originalMappings[index];\n\t\n\t if (mapping.source === needle.source) {\n\t return {\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t };\n\t }\n\t }\n\t\n\t return {\n\t line: null,\n\t column: null,\n\t lastColumn: null\n\t };\n\t };\n\t\n\texports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\t\n\t/**\n\t * An IndexedSourceMapConsumer instance represents a parsed source map which\n\t * we can query for information. It differs from BasicSourceMapConsumer in\n\t * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n\t * input.\n\t *\n\t * The first parameter is a raw source map (either as a JSON string, or already\n\t * parsed to an object). According to the spec for indexed source maps, they\n\t * have the following attributes:\n\t *\n\t * - version: Which version of the source map spec this map is following.\n\t * - file: Optional. The generated file this source map is associated with.\n\t * - sections: A list of section definitions.\n\t *\n\t * Each value under the \"sections\" field has two fields:\n\t * - offset: The offset into the original specified at which this section\n\t * begins to apply, defined as an object with a \"line\" and \"column\"\n\t * field.\n\t * - map: A source map definition. This source map could also be indexed,\n\t * but doesn't have to be.\n\t *\n\t * Instead of the \"map\" field, it's also possible to have a \"url\" field\n\t * specifying a URL to retrieve a source map from, but that's currently\n\t * unsupported.\n\t *\n\t * Here's an example source map, taken from the source map spec[0], but\n\t * modified to omit a section which uses the \"url\" field.\n\t *\n\t * {\n\t * version : 3,\n\t * file: \"app.js\",\n\t * sections: [{\n\t * offset: {line:100, column:10},\n\t * map: {\n\t * version : 3,\n\t * file: \"section.js\",\n\t * sources: [\"foo.js\", \"bar.js\"],\n\t * names: [\"src\", \"maps\", \"are\", \"fun\"],\n\t * mappings: \"AAAA,E;;ABCDE;\"\n\t * }\n\t * }],\n\t * }\n\t *\n\t * The second parameter, if given, is a string whose value is the URL\n\t * at which the source map was found. This URL is used to compute the\n\t * sources array.\n\t *\n\t * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n\t */\n\tfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t var version = util.getArg(sourceMap, 'version');\n\t var sections = util.getArg(sourceMap, 'sections');\n\t\n\t if (version != this._version) {\n\t throw new Error('Unsupported version: ' + version);\n\t }\n\t\n\t this._sources = new ArraySet();\n\t this._names = new ArraySet();\n\t\n\t var lastOffset = {\n\t line: -1,\n\t column: 0\n\t };\n\t this._sections = sections.map(function (s) {\n\t if (s.url) {\n\t // The url field will require support for asynchronicity.\n\t // See https://github.com/mozilla/source-map/issues/16\n\t throw new Error('Support for url field in sections not implemented.');\n\t }\n\t var offset = util.getArg(s, 'offset');\n\t var offsetLine = util.getArg(offset, 'line');\n\t var offsetColumn = util.getArg(offset, 'column');\n\t\n\t if (offsetLine < lastOffset.line ||\n\t (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n\t throw new Error('Section offsets must be ordered and non-overlapping.');\n\t }\n\t lastOffset = offset;\n\t\n\t return {\n\t generatedOffset: {\n\t // The offset fields are 0-based, but we use 1-based indices when\n\t // encoding/decoding from VLQ.\n\t generatedLine: offsetLine + 1,\n\t generatedColumn: offsetColumn + 1\n\t },\n\t consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n\t }\n\t });\n\t}\n\t\n\tIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\n\tIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tIndexedSourceMapConsumer.prototype._version = 3;\n\t\n\t/**\n\t * The list of original sources.\n\t */\n\tObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n\t get: function () {\n\t var sources = [];\n\t for (var i = 0; i < this._sections.length; i++) {\n\t for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n\t sources.push(this._sections[i].consumer.sources[j]);\n\t }\n\t }\n\t return sources;\n\t }\n\t});\n\t\n\t/**\n\t * Returns the original source, line, and column information for the generated\n\t * source's line and column positions provided. The only argument is an object\n\t * with the following properties:\n\t *\n\t * - line: The line number in the generated source. The line number\n\t * is 1-based.\n\t * - column: The column number in the generated source. The column\n\t * number is 0-based.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - source: The original source file, or null.\n\t * - line: The line number in the original source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the original source, or null. The\n\t * column number is 0-based.\n\t * - name: The original identifier, or null.\n\t */\n\tIndexedSourceMapConsumer.prototype.originalPositionFor =\n\t function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n\t var needle = {\n\t generatedLine: util.getArg(aArgs, 'line'),\n\t generatedColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t // Find the section containing the generated position we're trying to map\n\t // to an original position.\n\t var sectionIndex = binarySearch.search(needle, this._sections,\n\t function(needle, section) {\n\t var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n\t if (cmp) {\n\t return cmp;\n\t }\n\t\n\t return (needle.generatedColumn -\n\t section.generatedOffset.generatedColumn);\n\t });\n\t var section = this._sections[sectionIndex];\n\t\n\t if (!section) {\n\t return {\n\t source: null,\n\t line: null,\n\t column: null,\n\t name: null\n\t };\n\t }\n\t\n\t return section.consumer.originalPositionFor({\n\t line: needle.generatedLine -\n\t (section.generatedOffset.generatedLine - 1),\n\t column: needle.generatedColumn -\n\t (section.generatedOffset.generatedLine === needle.generatedLine\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0),\n\t bias: aArgs.bias\n\t });\n\t };\n\t\n\t/**\n\t * Return true if we have the source content for every source in the source\n\t * map, false otherwise.\n\t */\n\tIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n\t function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n\t return this._sections.every(function (s) {\n\t return s.consumer.hasContentsOfAllSources();\n\t });\n\t };\n\t\n\t/**\n\t * Returns the original source content. The only argument is the url of the\n\t * original source file. Returns null if no original source content is\n\t * available.\n\t */\n\tIndexedSourceMapConsumer.prototype.sourceContentFor =\n\t function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t\n\t var content = section.consumer.sourceContentFor(aSource, true);\n\t if (content) {\n\t return content;\n\t }\n\t }\n\t if (nullOnMissing) {\n\t return null;\n\t }\n\t else {\n\t throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n\t }\n\t };\n\t\n\t/**\n\t * Returns the generated line and column information for the original source,\n\t * line, and column positions provided. The only argument is an object with\n\t * the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number\n\t * is 1-based.\n\t * - column: The column number in the original source. The column\n\t * number is 0-based.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based. \n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tIndexedSourceMapConsumer.prototype.generatedPositionFor =\n\t function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t\n\t // Only consider this section if the requested source is in the list of\n\t // sources of the consumer.\n\t if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n\t continue;\n\t }\n\t var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n\t if (generatedPosition) {\n\t var ret = {\n\t line: generatedPosition.line +\n\t (section.generatedOffset.generatedLine - 1),\n\t column: generatedPosition.column +\n\t (section.generatedOffset.generatedLine === generatedPosition.line\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0)\n\t };\n\t return ret;\n\t }\n\t }\n\t\n\t return {\n\t line: null,\n\t column: null\n\t };\n\t };\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tIndexedSourceMapConsumer.prototype._parseMappings =\n\t function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t this.__generatedMappings = [];\n\t this.__originalMappings = [];\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t var sectionMappings = section.consumer._generatedMappings;\n\t for (var j = 0; j < sectionMappings.length; j++) {\n\t var mapping = sectionMappings[j];\n\t\n\t var source = section.consumer._sources.at(mapping.source);\n\t source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n\t this._sources.add(source);\n\t source = this._sources.indexOf(source);\n\t\n\t var name = null;\n\t if (mapping.name) {\n\t name = section.consumer._names.at(mapping.name);\n\t this._names.add(name);\n\t name = this._names.indexOf(name);\n\t }\n\t\n\t // The mappings coming from the consumer for the section have\n\t // generated positions relative to the start of the section, so we\n\t // need to offset them to be relative to the start of the concatenated\n\t // generated file.\n\t var adjustedMapping = {\n\t source: source,\n\t generatedLine: mapping.generatedLine +\n\t (section.generatedOffset.generatedLine - 1),\n\t generatedColumn: mapping.generatedColumn +\n\t (section.generatedOffset.generatedLine === mapping.generatedLine\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0),\n\t originalLine: mapping.originalLine,\n\t originalColumn: mapping.originalColumn,\n\t name: name\n\t };\n\t\n\t this.__generatedMappings.push(adjustedMapping);\n\t if (typeof adjustedMapping.originalLine === 'number') {\n\t this.__originalMappings.push(adjustedMapping);\n\t }\n\t }\n\t }\n\t\n\t quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n\t quickSort(this.__originalMappings, util.compareByOriginalPositions);\n\t };\n\t\n\texports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\texports.GREATEST_LOWER_BOUND = 1;\n\texports.LEAST_UPPER_BOUND = 2;\n\t\n\t/**\n\t * Recursive implementation of binary search.\n\t *\n\t * @param aLow Indices here and lower do not contain the needle.\n\t * @param aHigh Indices here and higher do not contain the needle.\n\t * @param aNeedle The element being searched for.\n\t * @param aHaystack The non-empty array being searched.\n\t * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n\t * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n\t * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t */\n\tfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n\t // This function terminates when one of the following is true:\n\t //\n\t // 1. We find the exact element we are looking for.\n\t //\n\t // 2. We did not find the exact element, but we can return the index of\n\t // the next-closest element.\n\t //\n\t // 3. We did not find the exact element, and there is no next-closest\n\t // element than the one we are searching for, so we return -1.\n\t var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n\t var cmp = aCompare(aNeedle, aHaystack[mid], true);\n\t if (cmp === 0) {\n\t // Found the element we are looking for.\n\t return mid;\n\t }\n\t else if (cmp > 0) {\n\t // Our needle is greater than aHaystack[mid].\n\t if (aHigh - mid > 1) {\n\t // The element is in the upper half.\n\t return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n\t }\n\t\n\t // The exact needle element was not found in this haystack. Determine if\n\t // we are in termination case (3) or (2) and return the appropriate thing.\n\t if (aBias == exports.LEAST_UPPER_BOUND) {\n\t return aHigh < aHaystack.length ? aHigh : -1;\n\t } else {\n\t return mid;\n\t }\n\t }\n\t else {\n\t // Our needle is less than aHaystack[mid].\n\t if (mid - aLow > 1) {\n\t // The element is in the lower half.\n\t return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n\t }\n\t\n\t // we are in termination case (3) or (2) and return the appropriate thing.\n\t if (aBias == exports.LEAST_UPPER_BOUND) {\n\t return mid;\n\t } else {\n\t return aLow < 0 ? -1 : aLow;\n\t }\n\t }\n\t}\n\t\n\t/**\n\t * This is an implementation of binary search which will always try and return\n\t * the index of the closest element if there is no exact hit. This is because\n\t * mappings between original and generated line/col pairs are single points,\n\t * and there is an implicit region between each of them, so a miss just means\n\t * that you aren't on the very start of a region.\n\t *\n\t * @param aNeedle The element you are looking for.\n\t * @param aHaystack The array that is being searched.\n\t * @param aCompare A function which takes the needle and an element in the\n\t * array and returns -1, 0, or 1 depending on whether the needle is less\n\t * than, equal to, or greater than the element, respectively.\n\t * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n\t * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n\t */\n\texports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n\t if (aHaystack.length === 0) {\n\t return -1;\n\t }\n\t\n\t var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n\t aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n\t if (index < 0) {\n\t return -1;\n\t }\n\t\n\t // We have found either the exact element, or the next-closest element than\n\t // the one we are searching for. However, there may be more than one such\n\t // element. Make sure we always return the smallest of these.\n\t while (index - 1 >= 0) {\n\t if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n\t break;\n\t }\n\t --index;\n\t }\n\t\n\t return index;\n\t};\n\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\t// It turns out that some (most?) JavaScript engines don't self-host\n\t// `Array.prototype.sort`. This makes sense because C++ will likely remain\n\t// faster than JS when doing raw CPU-intensive sorting. However, when using a\n\t// custom comparator function, calling back and forth between the VM's C++ and\n\t// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n\t// worse generated code for the comparator function than would be optimal. In\n\t// fact, when sorting with a comparator, these costs outweigh the benefits of\n\t// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n\t// a ~3500ms mean speed-up in `bench/bench.html`.\n\t\n\t/**\n\t * Swap the elements indexed by `x` and `y` in the array `ary`.\n\t *\n\t * @param {Array} ary\n\t * The array.\n\t * @param {Number} x\n\t * The index of the first item.\n\t * @param {Number} y\n\t * The index of the second item.\n\t */\n\tfunction swap(ary, x, y) {\n\t var temp = ary[x];\n\t ary[x] = ary[y];\n\t ary[y] = temp;\n\t}\n\t\n\t/**\n\t * Returns a random integer within the range `low .. high` inclusive.\n\t *\n\t * @param {Number} low\n\t * The lower bound on the range.\n\t * @param {Number} high\n\t * The upper bound on the range.\n\t */\n\tfunction randomIntInRange(low, high) {\n\t return Math.round(low + (Math.random() * (high - low)));\n\t}\n\t\n\t/**\n\t * The Quick Sort algorithm.\n\t *\n\t * @param {Array} ary\n\t * An array to sort.\n\t * @param {function} comparator\n\t * Function to use to compare two items.\n\t * @param {Number} p\n\t * Start index of the array\n\t * @param {Number} r\n\t * End index of the array\n\t */\n\tfunction doQuickSort(ary, comparator, p, r) {\n\t // If our lower bound is less than our upper bound, we (1) partition the\n\t // array into two pieces and (2) recurse on each half. If it is not, this is\n\t // the empty array and our base case.\n\t\n\t if (p < r) {\n\t // (1) Partitioning.\n\t //\n\t // The partitioning chooses a pivot between `p` and `r` and moves all\n\t // elements that are less than or equal to the pivot to the before it, and\n\t // all the elements that are greater than it after it. The effect is that\n\t // once partition is done, the pivot is in the exact place it will be when\n\t // the array is put in sorted order, and it will not need to be moved\n\t // again. This runs in O(n) time.\n\t\n\t // Always choose a random pivot so that an input array which is reverse\n\t // sorted does not cause O(n^2) running time.\n\t var pivotIndex = randomIntInRange(p, r);\n\t var i = p - 1;\n\t\n\t swap(ary, pivotIndex, r);\n\t var pivot = ary[r];\n\t\n\t // Immediately after `j` is incremented in this loop, the following hold\n\t // true:\n\t //\n\t // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n\t //\n\t // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n\t for (var j = p; j < r; j++) {\n\t if (comparator(ary[j], pivot) <= 0) {\n\t i += 1;\n\t swap(ary, i, j);\n\t }\n\t }\n\t\n\t swap(ary, i + 1, j);\n\t var q = i + 1;\n\t\n\t // (2) Recurse on each half.\n\t\n\t doQuickSort(ary, comparator, p, q - 1);\n\t doQuickSort(ary, comparator, q + 1, r);\n\t }\n\t}\n\t\n\t/**\n\t * Sort the given array in-place with the given comparator function.\n\t *\n\t * @param {Array} ary\n\t * An array to sort.\n\t * @param {function} comparator\n\t * Function to use to compare two items.\n\t */\n\texports.quickSort = function (ary, comparator) {\n\t doQuickSort(ary, comparator, 0, ary.length - 1);\n\t};\n\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;\n\tvar util = __webpack_require__(4);\n\t\n\t// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n\t// operating systems these days (capturing the result).\n\tvar REGEX_NEWLINE = /(\\r?\\n)/;\n\t\n\t// Newline character code for charCodeAt() comparisons\n\tvar NEWLINE_CODE = 10;\n\t\n\t// Private symbol for identifying `SourceNode`s when multiple versions of\n\t// the source-map library are loaded. This MUST NOT CHANGE across\n\t// versions!\n\tvar isSourceNode = \"$$$isSourceNode$$$\";\n\t\n\t/**\n\t * SourceNodes provide a way to abstract over interpolating/concatenating\n\t * snippets of generated JavaScript source code while maintaining the line and\n\t * column information associated with the original source code.\n\t *\n\t * @param aLine The original line number.\n\t * @param aColumn The original column number.\n\t * @param aSource The original source's filename.\n\t * @param aChunks Optional. An array of strings which are snippets of\n\t * generated JS, or other SourceNodes.\n\t * @param aName The original identifier.\n\t */\n\tfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n\t this.children = [];\n\t this.sourceContents = {};\n\t this.line = aLine == null ? null : aLine;\n\t this.column = aColumn == null ? null : aColumn;\n\t this.source = aSource == null ? null : aSource;\n\t this.name = aName == null ? null : aName;\n\t this[isSourceNode] = true;\n\t if (aChunks != null) this.add(aChunks);\n\t}\n\t\n\t/**\n\t * Creates a SourceNode from generated code and a SourceMapConsumer.\n\t *\n\t * @param aGeneratedCode The generated code\n\t * @param aSourceMapConsumer The SourceMap for the generated code\n\t * @param aRelativePath Optional. The path that relative sources in the\n\t * SourceMapConsumer should be relative to.\n\t */\n\tSourceNode.fromStringWithSourceMap =\n\t function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n\t // The SourceNode we want to fill with the generated code\n\t // and the SourceMap\n\t var node = new SourceNode();\n\t\n\t // All even indices of this array are one line of the generated code,\n\t // while all odd indices are the newlines between two adjacent lines\n\t // (since `REGEX_NEWLINE` captures its match).\n\t // Processed fragments are accessed by calling `shiftNextLine`.\n\t var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n\t var remainingLinesIndex = 0;\n\t var shiftNextLine = function() {\n\t var lineContents = getNextLine();\n\t // The last line of a file might not have a newline.\n\t var newLine = getNextLine() || \"\";\n\t return lineContents + newLine;\n\t\n\t function getNextLine() {\n\t return remainingLinesIndex < remainingLines.length ?\n\t remainingLines[remainingLinesIndex++] : undefined;\n\t }\n\t };\n\t\n\t // We need to remember the position of \"remainingLines\"\n\t var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\t\n\t // The generate SourceNodes we need a code range.\n\t // To extract it current and last mapping is used.\n\t // Here we store the last mapping.\n\t var lastMapping = null;\n\t\n\t aSourceMapConsumer.eachMapping(function (mapping) {\n\t if (lastMapping !== null) {\n\t // We add the code from \"lastMapping\" to \"mapping\":\n\t // First check if there is a new line in between.\n\t if (lastGeneratedLine < mapping.generatedLine) {\n\t // Associate first line with \"lastMapping\"\n\t addMappingWithCode(lastMapping, shiftNextLine());\n\t lastGeneratedLine++;\n\t lastGeneratedColumn = 0;\n\t // The remaining code is added without mapping\n\t } else {\n\t // There is no new line in between.\n\t // Associate the code between \"lastGeneratedColumn\" and\n\t // \"mapping.generatedColumn\" with \"lastMapping\"\n\t var nextLine = remainingLines[remainingLinesIndex] || '';\n\t var code = nextLine.substr(0, mapping.generatedColumn -\n\t lastGeneratedColumn);\n\t remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n\t lastGeneratedColumn);\n\t lastGeneratedColumn = mapping.generatedColumn;\n\t addMappingWithCode(lastMapping, code);\n\t // No more remaining code, continue\n\t lastMapping = mapping;\n\t return;\n\t }\n\t }\n\t // We add the generated code until the first mapping\n\t // to the SourceNode without any mapping.\n\t // Each line is added as separate string.\n\t while (lastGeneratedLine < mapping.generatedLine) {\n\t node.add(shiftNextLine());\n\t lastGeneratedLine++;\n\t }\n\t if (lastGeneratedColumn < mapping.generatedColumn) {\n\t var nextLine = remainingLines[remainingLinesIndex] || '';\n\t node.add(nextLine.substr(0, mapping.generatedColumn));\n\t remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n\t lastGeneratedColumn = mapping.generatedColumn;\n\t }\n\t lastMapping = mapping;\n\t }, this);\n\t // We have processed all mappings.\n\t if (remainingLinesIndex < remainingLines.length) {\n\t if (lastMapping) {\n\t // Associate the remaining code in the current line with \"lastMapping\"\n\t addMappingWithCode(lastMapping, shiftNextLine());\n\t }\n\t // and add the remaining lines without any mapping\n\t node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n\t }\n\t\n\t // Copy sourcesContent into SourceNode\n\t aSourceMapConsumer.sources.forEach(function (sourceFile) {\n\t var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n\t if (content != null) {\n\t if (aRelativePath != null) {\n\t sourceFile = util.join(aRelativePath, sourceFile);\n\t }\n\t node.setSourceContent(sourceFile, content);\n\t }\n\t });\n\t\n\t return node;\n\t\n\t function addMappingWithCode(mapping, code) {\n\t if (mapping === null || mapping.source === undefined) {\n\t node.add(code);\n\t } else {\n\t var source = aRelativePath\n\t ? util.join(aRelativePath, mapping.source)\n\t : mapping.source;\n\t node.add(new SourceNode(mapping.originalLine,\n\t mapping.originalColumn,\n\t source,\n\t code,\n\t mapping.name));\n\t }\n\t }\n\t };\n\t\n\t/**\n\t * Add a chunk of generated JS to this source node.\n\t *\n\t * @param aChunk A string snippet of generated JS code, another instance of\n\t * SourceNode, or an array where each member is one of those things.\n\t */\n\tSourceNode.prototype.add = function SourceNode_add(aChunk) {\n\t if (Array.isArray(aChunk)) {\n\t aChunk.forEach(function (chunk) {\n\t this.add(chunk);\n\t }, this);\n\t }\n\t else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n\t if (aChunk) {\n\t this.children.push(aChunk);\n\t }\n\t }\n\t else {\n\t throw new TypeError(\n\t \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n\t );\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Add a chunk of generated JS to the beginning of this source node.\n\t *\n\t * @param aChunk A string snippet of generated JS code, another instance of\n\t * SourceNode, or an array where each member is one of those things.\n\t */\n\tSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n\t if (Array.isArray(aChunk)) {\n\t for (var i = aChunk.length-1; i >= 0; i--) {\n\t this.prepend(aChunk[i]);\n\t }\n\t }\n\t else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n\t this.children.unshift(aChunk);\n\t }\n\t else {\n\t throw new TypeError(\n\t \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n\t );\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Walk over the tree of JS snippets in this node and its children. The\n\t * walking function is called once for each snippet of JS and is passed that\n\t * snippet and the its original associated source's line/column location.\n\t *\n\t * @param aFn The traversal function.\n\t */\n\tSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n\t var chunk;\n\t for (var i = 0, len = this.children.length; i < len; i++) {\n\t chunk = this.children[i];\n\t if (chunk[isSourceNode]) {\n\t chunk.walk(aFn);\n\t }\n\t else {\n\t if (chunk !== '') {\n\t aFn(chunk, { source: this.source,\n\t line: this.line,\n\t column: this.column,\n\t name: this.name });\n\t }\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n\t * each of `this.children`.\n\t *\n\t * @param aSep The separator.\n\t */\n\tSourceNode.prototype.join = function SourceNode_join(aSep) {\n\t var newChildren;\n\t var i;\n\t var len = this.children.length;\n\t if (len > 0) {\n\t newChildren = [];\n\t for (i = 0; i < len-1; i++) {\n\t newChildren.push(this.children[i]);\n\t newChildren.push(aSep);\n\t }\n\t newChildren.push(this.children[i]);\n\t this.children = newChildren;\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Call String.prototype.replace on the very right-most source snippet. Useful\n\t * for trimming whitespace from the end of a source node, etc.\n\t *\n\t * @param aPattern The pattern to replace.\n\t * @param aReplacement The thing to replace the pattern with.\n\t */\n\tSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n\t var lastChild = this.children[this.children.length - 1];\n\t if (lastChild[isSourceNode]) {\n\t lastChild.replaceRight(aPattern, aReplacement);\n\t }\n\t else if (typeof lastChild === 'string') {\n\t this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n\t }\n\t else {\n\t this.children.push(''.replace(aPattern, aReplacement));\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Set the source content for a source file. This will be added to the SourceMapGenerator\n\t * in the sourcesContent field.\n\t *\n\t * @param aSourceFile The filename of the source file\n\t * @param aSourceContent The content of the source file\n\t */\n\tSourceNode.prototype.setSourceContent =\n\t function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n\t this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n\t };\n\t\n\t/**\n\t * Walk over the tree of SourceNodes. The walking function is called for each\n\t * source file content and is passed the filename and source content.\n\t *\n\t * @param aFn The traversal function.\n\t */\n\tSourceNode.prototype.walkSourceContents =\n\t function SourceNode_walkSourceContents(aFn) {\n\t for (var i = 0, len = this.children.length; i < len; i++) {\n\t if (this.children[i][isSourceNode]) {\n\t this.children[i].walkSourceContents(aFn);\n\t }\n\t }\n\t\n\t var sources = Object.keys(this.sourceContents);\n\t for (var i = 0, len = sources.length; i < len; i++) {\n\t aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n\t }\n\t };\n\t\n\t/**\n\t * Return the string representation of this source node. Walks over the tree\n\t * and concatenates all the various snippets together to one string.\n\t */\n\tSourceNode.prototype.toString = function SourceNode_toString() {\n\t var str = \"\";\n\t this.walk(function (chunk) {\n\t str += chunk;\n\t });\n\t return str;\n\t};\n\t\n\t/**\n\t * Returns the string representation of this source node along with a source\n\t * map.\n\t */\n\tSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n\t var generated = {\n\t code: \"\",\n\t line: 1,\n\t column: 0\n\t };\n\t var map = new SourceMapGenerator(aArgs);\n\t var sourceMappingActive = false;\n\t var lastOriginalSource = null;\n\t var lastOriginalLine = null;\n\t var lastOriginalColumn = null;\n\t var lastOriginalName = null;\n\t this.walk(function (chunk, original) {\n\t generated.code += chunk;\n\t if (original.source !== null\n\t && original.line !== null\n\t && original.column !== null) {\n\t if(lastOriginalSource !== original.source\n\t || lastOriginalLine !== original.line\n\t || lastOriginalColumn !== original.column\n\t || lastOriginalName !== original.name) {\n\t map.addMapping({\n\t source: original.source,\n\t original: {\n\t line: original.line,\n\t column: original.column\n\t },\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t },\n\t name: original.name\n\t });\n\t }\n\t lastOriginalSource = original.source;\n\t lastOriginalLine = original.line;\n\t lastOriginalColumn = original.column;\n\t lastOriginalName = original.name;\n\t sourceMappingActive = true;\n\t } else if (sourceMappingActive) {\n\t map.addMapping({\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t }\n\t });\n\t lastOriginalSource = null;\n\t sourceMappingActive = false;\n\t }\n\t for (var idx = 0, length = chunk.length; idx < length; idx++) {\n\t if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n\t generated.line++;\n\t generated.column = 0;\n\t // Mappings end at eol\n\t if (idx + 1 === length) {\n\t lastOriginalSource = null;\n\t sourceMappingActive = false;\n\t } else if (sourceMappingActive) {\n\t map.addMapping({\n\t source: original.source,\n\t original: {\n\t line: original.line,\n\t column: original.column\n\t },\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t },\n\t name: original.name\n\t });\n\t }\n\t } else {\n\t generated.column++;\n\t }\n\t }\n\t });\n\t this.walkSourceContents(function (sourceFile, sourceContent) {\n\t map.setSourceContent(sourceFile, sourceContent);\n\t });\n\t\n\t return { code: generated.code, map: map };\n\t};\n\t\n\texports.SourceNode = SourceNode;\n\n\n/***/ })\n/******/ ])\n});\n;\n\n\n// WEBPACK FOOTER //\n// source-map.min.js"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 0fd5815da764db5fb9fe","/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./lib/source-node').SourceNode;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./source-map.js\n// module id = 0\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar base64VLQ = require('./base64-vlq');\nvar util = require('./util');\nvar ArraySet = require('./array-set').ArraySet;\nvar MappingList = require('./mapping-list').MappingList;\n\n/**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n * - file: The filename of the generated source.\n * - sourceRoot: A root for all relative URLs in this source map.\n */\nfunction SourceMapGenerator(aArgs) {\n if (!aArgs) {\n aArgs = {};\n }\n this._file = util.getArg(aArgs, 'file', null);\n this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n this._skipValidation = util.getArg(aArgs, 'skipValidation', false);\n this._sources = new ArraySet();\n this._names = new ArraySet();\n this._mappings = new MappingList();\n this._sourcesContents = null;\n}\n\nSourceMapGenerator.prototype._version = 3;\n\n/**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\nSourceMapGenerator.fromSourceMap =\n function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {\n var sourceRoot = aSourceMapConsumer.sourceRoot;\n var generator = new SourceMapGenerator({\n file: aSourceMapConsumer.file,\n sourceRoot: sourceRoot\n });\n aSourceMapConsumer.eachMapping(function (mapping) {\n var newMapping = {\n generated: {\n line: mapping.generatedLine,\n column: mapping.generatedColumn\n }\n };\n\n if (mapping.source != null) {\n newMapping.source = mapping.source;\n if (sourceRoot != null) {\n newMapping.source = util.relative(sourceRoot, newMapping.source);\n }\n\n newMapping.original = {\n line: mapping.originalLine,\n column: mapping.originalColumn\n };\n\n if (mapping.name != null) {\n newMapping.name = mapping.name;\n }\n }\n\n generator.addMapping(newMapping);\n });\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var sourceRelative = sourceFile;\n if (sourceRoot !== null) {\n sourceRelative = util.relative(sourceRoot, sourceFile);\n }\n\n if (!generator._sources.has(sourceRelative)) {\n generator._sources.add(sourceRelative);\n }\n\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n generator.setSourceContent(sourceFile, content);\n }\n });\n return generator;\n };\n\n/**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n * - generated: An object with the generated line and column positions.\n * - original: An object with the original line and column positions.\n * - source: The original source file (relative to the sourceRoot).\n * - name: An optional original token name for this mapping.\n */\nSourceMapGenerator.prototype.addMapping =\n function SourceMapGenerator_addMapping(aArgs) {\n var generated = util.getArg(aArgs, 'generated');\n var original = util.getArg(aArgs, 'original', null);\n var source = util.getArg(aArgs, 'source', null);\n var name = util.getArg(aArgs, 'name', null);\n\n if (!this._skipValidation) {\n this._validateMapping(generated, original, source, name);\n }\n\n if (source != null) {\n source = String(source);\n if (!this._sources.has(source)) {\n this._sources.add(source);\n }\n }\n\n if (name != null) {\n name = String(name);\n if (!this._names.has(name)) {\n this._names.add(name);\n }\n }\n\n this._mappings.add({\n generatedLine: generated.line,\n generatedColumn: generated.column,\n originalLine: original != null && original.line,\n originalColumn: original != null && original.column,\n source: source,\n name: name\n });\n };\n\n/**\n * Set the source content for a source file.\n */\nSourceMapGenerator.prototype.setSourceContent =\n function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n var source = aSourceFile;\n if (this._sourceRoot != null) {\n source = util.relative(this._sourceRoot, source);\n }\n\n if (aSourceContent != null) {\n // Add the source content to the _sourcesContents map.\n // Create a new _sourcesContents map if the property is null.\n if (!this._sourcesContents) {\n this._sourcesContents = Object.create(null);\n }\n this._sourcesContents[util.toSetString(source)] = aSourceContent;\n } else if (this._sourcesContents) {\n // Remove the source file from the _sourcesContents map.\n // If the _sourcesContents map is empty, set the property to null.\n delete this._sourcesContents[util.toSetString(source)];\n if (Object.keys(this._sourcesContents).length === 0) {\n this._sourcesContents = null;\n }\n }\n };\n\n/**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n * If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n * to be applied. If relative, it is relative to the SourceMapConsumer.\n * This parameter is needed when the two source maps aren't in the same\n * directory, and the source map to be applied contains relative source\n * paths. If so, those relative source paths need to be rewritten\n * relative to the SourceMapGenerator.\n */\nSourceMapGenerator.prototype.applySourceMap =\n function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n var sourceFile = aSourceFile;\n // If aSourceFile is omitted, we will use the file property of the SourceMap\n if (aSourceFile == null) {\n if (aSourceMapConsumer.file == null) {\n throw new Error(\n 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n 'or the source map\\'s \"file\" property. Both were omitted.'\n );\n }\n sourceFile = aSourceMapConsumer.file;\n }\n var sourceRoot = this._sourceRoot;\n // Make \"sourceFile\" relative if an absolute Url is passed.\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n // Applying the SourceMap can add and remove items from the sources and\n // the names array.\n var newSources = new ArraySet();\n var newNames = new ArraySet();\n\n // Find mappings for the \"sourceFile\"\n this._mappings.unsortedForEach(function (mapping) {\n if (mapping.source === sourceFile && mapping.originalLine != null) {\n // Check if it can be mapped by the source map, then update the mapping.\n var original = aSourceMapConsumer.originalPositionFor({\n line: mapping.originalLine,\n column: mapping.originalColumn\n });\n if (original.source != null) {\n // Copy mapping\n mapping.source = original.source;\n if (aSourceMapPath != null) {\n mapping.source = util.join(aSourceMapPath, mapping.source)\n }\n if (sourceRoot != null) {\n mapping.source = util.relative(sourceRoot, mapping.source);\n }\n mapping.originalLine = original.line;\n mapping.originalColumn = original.column;\n if (original.name != null) {\n mapping.name = original.name;\n }\n }\n }\n\n var source = mapping.source;\n if (source != null && !newSources.has(source)) {\n newSources.add(source);\n }\n\n var name = mapping.name;\n if (name != null && !newNames.has(name)) {\n newNames.add(name);\n }\n\n }, this);\n this._sources = newSources;\n this._names = newNames;\n\n // Copy sourcesContents of applied map.\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aSourceMapPath != null) {\n sourceFile = util.join(aSourceMapPath, sourceFile);\n }\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n this.setSourceContent(sourceFile, content);\n }\n }, this);\n };\n\n/**\n * A mapping can have one of the three levels of data:\n *\n * 1. Just the generated position.\n * 2. The Generated position, original position, and original source.\n * 3. Generated and original position, original source, as well as a name\n * token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\nSourceMapGenerator.prototype._validateMapping =\n function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n aName) {\n // When aOriginal is truthy but has empty values for .line and .column,\n // it is most likely a programmer error. In this case we throw a very\n // specific error message to try to guide them the right way.\n // For example: https://github.com/Polymer/polymer-bundler/pull/519\n if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {\n throw new Error(\n 'original.line and original.column are not numbers -- you probably meant to omit ' +\n 'the original mapping entirely and only map the generated position. If so, pass ' +\n 'null for the original mapping instead of an object with empty or null values.'\n );\n }\n\n if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aGenerated.line > 0 && aGenerated.column >= 0\n && !aOriginal && !aSource && !aName) {\n // Case 1.\n return;\n }\n else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n && aGenerated.line > 0 && aGenerated.column >= 0\n && aOriginal.line > 0 && aOriginal.column >= 0\n && aSource) {\n // Cases 2 and 3.\n return;\n }\n else {\n throw new Error('Invalid mapping: ' + JSON.stringify({\n generated: aGenerated,\n source: aSource,\n original: aOriginal,\n name: aName\n }));\n }\n };\n\n/**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\nSourceMapGenerator.prototype._serializeMappings =\n function SourceMapGenerator_serializeMappings() {\n var previousGeneratedColumn = 0;\n var previousGeneratedLine = 1;\n var previousOriginalColumn = 0;\n var previousOriginalLine = 0;\n var previousName = 0;\n var previousSource = 0;\n var result = '';\n var next;\n var mapping;\n var nameIdx;\n var sourceIdx;\n\n var mappings = this._mappings.toArray();\n for (var i = 0, len = mappings.length; i < len; i++) {\n mapping = mappings[i];\n next = ''\n\n if (mapping.generatedLine !== previousGeneratedLine) {\n previousGeneratedColumn = 0;\n while (mapping.generatedLine !== previousGeneratedLine) {\n next += ';';\n previousGeneratedLine++;\n }\n }\n else {\n if (i > 0) {\n if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n continue;\n }\n next += ',';\n }\n }\n\n next += base64VLQ.encode(mapping.generatedColumn\n - previousGeneratedColumn);\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (mapping.source != null) {\n sourceIdx = this._sources.indexOf(mapping.source);\n next += base64VLQ.encode(sourceIdx - previousSource);\n previousSource = sourceIdx;\n\n // lines are stored 0-based in SourceMap spec version 3\n next += base64VLQ.encode(mapping.originalLine - 1\n - previousOriginalLine);\n previousOriginalLine = mapping.originalLine - 1;\n\n next += base64VLQ.encode(mapping.originalColumn\n - previousOriginalColumn);\n previousOriginalColumn = mapping.originalColumn;\n\n if (mapping.name != null) {\n nameIdx = this._names.indexOf(mapping.name);\n next += base64VLQ.encode(nameIdx - previousName);\n previousName = nameIdx;\n }\n }\n\n result += next;\n }\n\n return result;\n };\n\nSourceMapGenerator.prototype._generateSourcesContent =\n function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n return aSources.map(function (source) {\n if (!this._sourcesContents) {\n return null;\n }\n if (aSourceRoot != null) {\n source = util.relative(aSourceRoot, source);\n }\n var key = util.toSetString(source);\n return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n ? this._sourcesContents[key]\n : null;\n }, this);\n };\n\n/**\n * Externalize the source map.\n */\nSourceMapGenerator.prototype.toJSON =\n function SourceMapGenerator_toJSON() {\n var map = {\n version: this._version,\n sources: this._sources.toArray(),\n names: this._names.toArray(),\n mappings: this._serializeMappings()\n };\n if (this._file != null) {\n map.file = this._file;\n }\n if (this._sourceRoot != null) {\n map.sourceRoot = this._sourceRoot;\n }\n if (this._sourcesContents) {\n map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n }\n\n return map;\n };\n\n/**\n * Render the source map being generated to a string.\n */\nSourceMapGenerator.prototype.toString =\n function SourceMapGenerator_toString() {\n return JSON.stringify(this.toJSON());\n };\n\nexports.SourceMapGenerator = SourceMapGenerator;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-map-generator.js\n// module id = 1\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nvar base64 = require('./base64');\n\n// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n// length quantities we use in the source map spec, the first bit is the sign,\n// the next four bits are the actual value, and the 6th bit is the\n// continuation bit. The continuation bit tells us whether there are more\n// digits in this value following this digit.\n//\n// Continuation\n// | Sign\n// | |\n// V V\n// 101011\n\nvar VLQ_BASE_SHIFT = 5;\n\n// binary: 100000\nvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n// binary: 011111\nvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\n// binary: 100000\nvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n/**\n * Converts from a two-complement value to a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\nfunction toVLQSigned(aValue) {\n return aValue < 0\n ? ((-aValue) << 1) + 1\n : (aValue << 1) + 0;\n}\n\n/**\n * Converts to a two-complement value from a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\nfunction fromVLQSigned(aValue) {\n var isNegative = (aValue & 1) === 1;\n var shifted = aValue >> 1;\n return isNegative\n ? -shifted\n : shifted;\n}\n\n/**\n * Returns the base 64 VLQ encoded value.\n */\nexports.encode = function base64VLQ_encode(aValue) {\n var encoded = \"\";\n var digit;\n\n var vlq = toVLQSigned(aValue);\n\n do {\n digit = vlq & VLQ_BASE_MASK;\n vlq >>>= VLQ_BASE_SHIFT;\n if (vlq > 0) {\n // There are still more digits in this value, so we must make sure the\n // continuation bit is marked.\n digit |= VLQ_CONTINUATION_BIT;\n }\n encoded += base64.encode(digit);\n } while (vlq > 0);\n\n return encoded;\n};\n\n/**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string via the out parameter.\n */\nexports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n var strLen = aStr.length;\n var result = 0;\n var shift = 0;\n var continuation, digit;\n\n do {\n if (aIndex >= strLen) {\n throw new Error(\"Expected more digits in base 64 VLQ value.\");\n }\n\n digit = base64.decode(aStr.charCodeAt(aIndex++));\n if (digit === -1) {\n throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n }\n\n continuation = !!(digit & VLQ_CONTINUATION_BIT);\n digit &= VLQ_BASE_MASK;\n result = result + (digit << shift);\n shift += VLQ_BASE_SHIFT;\n } while (continuation);\n\n aOutParam.value = fromVLQSigned(result);\n aOutParam.rest = aIndex;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/base64-vlq.js\n// module id = 2\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\n/**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\nexports.encode = function (number) {\n if (0 <= number && number < intToCharMap.length) {\n return intToCharMap[number];\n }\n throw new TypeError(\"Must be between 0 and 63: \" + number);\n};\n\n/**\n * Decode a single base 64 character code digit to an integer. Returns -1 on\n * failure.\n */\nexports.decode = function (charCode) {\n var bigA = 65; // 'A'\n var bigZ = 90; // 'Z'\n\n var littleA = 97; // 'a'\n var littleZ = 122; // 'z'\n\n var zero = 48; // '0'\n var nine = 57; // '9'\n\n var plus = 43; // '+'\n var slash = 47; // '/'\n\n var littleOffset = 26;\n var numberOffset = 52;\n\n // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n if (bigA <= charCode && charCode <= bigZ) {\n return (charCode - bigA);\n }\n\n // 26 - 51: abcdefghijklmnopqrstuvwxyz\n if (littleA <= charCode && charCode <= littleZ) {\n return (charCode - littleA + littleOffset);\n }\n\n // 52 - 61: 0123456789\n if (zero <= charCode && charCode <= nine) {\n return (charCode - zero + numberOffset);\n }\n\n // 62: +\n if (charCode == plus) {\n return 62;\n }\n\n // 63: /\n if (charCode == slash) {\n return 63;\n }\n\n // Invalid base64 digit.\n return -1;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/base64.js\n// module id = 3\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\nfunction getArg(aArgs, aName, aDefaultValue) {\n if (aName in aArgs) {\n return aArgs[aName];\n } else if (arguments.length === 3) {\n return aDefaultValue;\n } else {\n throw new Error('\"' + aName + '\" is a required argument.');\n }\n}\nexports.getArg = getArg;\n\nvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\nvar dataUrlRegexp = /^data:.+\\,.+$/;\n\nfunction urlParse(aUrl) {\n var match = aUrl.match(urlRegexp);\n if (!match) {\n return null;\n }\n return {\n scheme: match[1],\n auth: match[2],\n host: match[3],\n port: match[4],\n path: match[5]\n };\n}\nexports.urlParse = urlParse;\n\nfunction urlGenerate(aParsedUrl) {\n var url = '';\n if (aParsedUrl.scheme) {\n url += aParsedUrl.scheme + ':';\n }\n url += '//';\n if (aParsedUrl.auth) {\n url += aParsedUrl.auth + '@';\n }\n if (aParsedUrl.host) {\n url += aParsedUrl.host;\n }\n if (aParsedUrl.port) {\n url += \":\" + aParsedUrl.port\n }\n if (aParsedUrl.path) {\n url += aParsedUrl.path;\n }\n return url;\n}\nexports.urlGenerate = urlGenerate;\n\n/**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consecutive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\nfunction normalize(aPath) {\n var path = aPath;\n var url = urlParse(aPath);\n if (url) {\n if (!url.path) {\n return aPath;\n }\n path = url.path;\n }\n var isAbsolute = exports.isAbsolute(path);\n\n var parts = path.split(/\\/+/);\n for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n part = parts[i];\n if (part === '.') {\n parts.splice(i, 1);\n } else if (part === '..') {\n up++;\n } else if (up > 0) {\n if (part === '') {\n // The first part is blank if the path is absolute. Trying to go\n // above the root is a no-op. Therefore we can remove all '..' parts\n // directly after the root.\n parts.splice(i + 1, up);\n up = 0;\n } else {\n parts.splice(i, 2);\n up--;\n }\n }\n }\n path = parts.join('/');\n\n if (path === '') {\n path = isAbsolute ? '/' : '.';\n }\n\n if (url) {\n url.path = path;\n return urlGenerate(url);\n }\n return path;\n}\nexports.normalize = normalize;\n\n/**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n * first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n * is updated with the result and aRoot is returned. Otherwise the result\n * is returned.\n * - If aPath is absolute, the result is aPath.\n * - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\nfunction join(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n if (aPath === \"\") {\n aPath = \".\";\n }\n var aPathUrl = urlParse(aPath);\n var aRootUrl = urlParse(aRoot);\n if (aRootUrl) {\n aRoot = aRootUrl.path || '/';\n }\n\n // `join(foo, '//www.example.org')`\n if (aPathUrl && !aPathUrl.scheme) {\n if (aRootUrl) {\n aPathUrl.scheme = aRootUrl.scheme;\n }\n return urlGenerate(aPathUrl);\n }\n\n if (aPathUrl || aPath.match(dataUrlRegexp)) {\n return aPath;\n }\n\n // `join('http://', 'www.example.com')`\n if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n aRootUrl.host = aPath;\n return urlGenerate(aRootUrl);\n }\n\n var joined = aPath.charAt(0) === '/'\n ? aPath\n : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n if (aRootUrl) {\n aRootUrl.path = joined;\n return urlGenerate(aRootUrl);\n }\n return joined;\n}\nexports.join = join;\n\nexports.isAbsolute = function (aPath) {\n return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n};\n\n/**\n * Make a path relative to a URL or another path.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be made relative to aRoot.\n */\nfunction relative(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n\n aRoot = aRoot.replace(/\\/$/, '');\n\n // It is possible for the path to be above the root. In this case, simply\n // checking whether the root is a prefix of the path won't work. Instead, we\n // need to remove components from the root one by one, until either we find\n // a prefix that fits, or we run out of components to remove.\n var level = 0;\n while (aPath.indexOf(aRoot + '/') !== 0) {\n var index = aRoot.lastIndexOf(\"/\");\n if (index < 0) {\n return aPath;\n }\n\n // If the only part of the root that is left is the scheme (i.e. http://,\n // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n // have exhausted all components, so the path is not relative to the root.\n aRoot = aRoot.slice(0, index);\n if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n return aPath;\n }\n\n ++level;\n }\n\n // Make sure we add a \"../\" for each component we removed from the root.\n return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n}\nexports.relative = relative;\n\nvar supportsNullProto = (function () {\n var obj = Object.create(null);\n return !('__proto__' in obj);\n}());\n\nfunction identity (s) {\n return s;\n}\n\n/**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\nfunction toSetString(aStr) {\n if (isProtoString(aStr)) {\n return '$' + aStr;\n }\n\n return aStr;\n}\nexports.toSetString = supportsNullProto ? identity : toSetString;\n\nfunction fromSetString(aStr) {\n if (isProtoString(aStr)) {\n return aStr.slice(1);\n }\n\n return aStr;\n}\nexports.fromSetString = supportsNullProto ? identity : fromSetString;\n\nfunction isProtoString(s) {\n if (!s) {\n return false;\n }\n\n var length = s.length;\n\n if (length < 9 /* \"__proto__\".length */) {\n return false;\n }\n\n if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n s.charCodeAt(length - 9) !== 95 /* '_' */) {\n return false;\n }\n\n for (var i = length - 10; i >= 0; i--) {\n if (s.charCodeAt(i) !== 36 /* '$' */) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\nfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n var cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0 || onlyCompareOriginal) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByOriginalPositions = compareByOriginalPositions;\n\n/**\n * Comparator between two mappings with deflated source and name indices where\n * the generated positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\nfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0 || onlyCompareGenerated) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction strcmp(aStr1, aStr2) {\n if (aStr1 === aStr2) {\n return 0;\n }\n\n if (aStr1 === null) {\n return 1; // aStr2 !== null\n }\n\n if (aStr2 === null) {\n return -1; // aStr1 !== null\n }\n\n if (aStr1 > aStr2) {\n return 1;\n }\n\n return -1;\n}\n\n/**\n * Comparator between two mappings with inflated source and name strings where\n * the generated positions are compared.\n */\nfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\n/**\n * Strip any JSON XSSI avoidance prefix from the string (as documented\n * in the source maps specification), and then parse the string as\n * JSON.\n */\nfunction parseSourceMapInput(str) {\n return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n}\nexports.parseSourceMapInput = parseSourceMapInput;\n\n/**\n * Compute the URL of a source given the the source root, the source's\n * URL, and the source map's URL.\n */\nfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n sourceURL = sourceURL || '';\n\n if (sourceRoot) {\n // This follows what Chrome does.\n if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n sourceRoot += '/';\n }\n // The spec says:\n // Line 4: An optional source root, useful for relocating source\n // files on a server or removing repeated values in the\n // “sources” entry. This value is prepended to the individual\n // entries in the “source” field.\n sourceURL = sourceRoot + sourceURL;\n }\n\n // Historically, SourceMapConsumer did not take the sourceMapURL as\n // a parameter. This mode is still somewhat supported, which is why\n // this code block is conditional. However, it's preferable to pass\n // the source map URL to SourceMapConsumer, so that this function\n // can implement the source URL resolution algorithm as outlined in\n // the spec. This block is basically the equivalent of:\n // new URL(sourceURL, sourceMapURL).toString()\n // ... except it avoids using URL, which wasn't available in the\n // older releases of node still supported by this library.\n //\n // The spec says:\n // If the sources are not absolute URLs after prepending of the\n // “sourceRoot”, the sources are resolved relative to the\n // SourceMap (like resolving script src in a html document).\n if (sourceMapURL) {\n var parsed = urlParse(sourceMapURL);\n if (!parsed) {\n throw new Error(\"sourceMapURL could not be parsed\");\n }\n if (parsed.path) {\n // Strip the last path component, but keep the \"/\".\n var index = parsed.path.lastIndexOf('/');\n if (index >= 0) {\n parsed.path = parsed.path.substring(0, index + 1);\n }\n }\n sourceURL = join(urlGenerate(parsed), sourceURL);\n }\n\n return normalize(sourceURL);\n}\nexports.computeSourceURL = computeSourceURL;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/util.js\n// module id = 4\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar has = Object.prototype.hasOwnProperty;\nvar hasNativeMap = typeof Map !== \"undefined\";\n\n/**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\nfunction ArraySet() {\n this._array = [];\n this._set = hasNativeMap ? new Map() : Object.create(null);\n}\n\n/**\n * Static method for creating ArraySet instances from an existing array.\n */\nArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n var set = new ArraySet();\n for (var i = 0, len = aArray.length; i < len; i++) {\n set.add(aArray[i], aAllowDuplicates);\n }\n return set;\n};\n\n/**\n * Return how many unique items are in this ArraySet. If duplicates have been\n * added, than those do not count towards the size.\n *\n * @returns Number\n */\nArraySet.prototype.size = function ArraySet_size() {\n return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n};\n\n/**\n * Add the given string to this set.\n *\n * @param String aStr\n */\nArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n var idx = this._array.length;\n if (!isDuplicate || aAllowDuplicates) {\n this._array.push(aStr);\n }\n if (!isDuplicate) {\n if (hasNativeMap) {\n this._set.set(aStr, idx);\n } else {\n this._set[sStr] = idx;\n }\n }\n};\n\n/**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\nArraySet.prototype.has = function ArraySet_has(aStr) {\n if (hasNativeMap) {\n return this._set.has(aStr);\n } else {\n var sStr = util.toSetString(aStr);\n return has.call(this._set, sStr);\n }\n};\n\n/**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\nArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n if (hasNativeMap) {\n var idx = this._set.get(aStr);\n if (idx >= 0) {\n return idx;\n }\n } else {\n var sStr = util.toSetString(aStr);\n if (has.call(this._set, sStr)) {\n return this._set[sStr];\n }\n }\n\n throw new Error('\"' + aStr + '\" is not in the set.');\n};\n\n/**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\nArraySet.prototype.at = function ArraySet_at(aIdx) {\n if (aIdx >= 0 && aIdx < this._array.length) {\n return this._array[aIdx];\n }\n throw new Error('No element indexed by ' + aIdx);\n};\n\n/**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\nArraySet.prototype.toArray = function ArraySet_toArray() {\n return this._array.slice();\n};\n\nexports.ArraySet = ArraySet;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/array-set.js\n// module id = 5\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2014 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\n\n/**\n * Determine whether mappingB is after mappingA with respect to generated\n * position.\n */\nfunction generatedPositionAfter(mappingA, mappingB) {\n // Optimized for most common case\n var lineA = mappingA.generatedLine;\n var lineB = mappingB.generatedLine;\n var columnA = mappingA.generatedColumn;\n var columnB = mappingB.generatedColumn;\n return lineB > lineA || lineB == lineA && columnB >= columnA ||\n util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n}\n\n/**\n * A data structure to provide a sorted view of accumulated mappings in a\n * performance conscious manner. It trades a neglibable overhead in general\n * case for a large speedup in case of mappings being added in order.\n */\nfunction MappingList() {\n this._array = [];\n this._sorted = true;\n // Serves as infimum\n this._last = {generatedLine: -1, generatedColumn: 0};\n}\n\n/**\n * Iterate through internal items. This method takes the same arguments that\n * `Array.prototype.forEach` takes.\n *\n * NOTE: The order of the mappings is NOT guaranteed.\n */\nMappingList.prototype.unsortedForEach =\n function MappingList_forEach(aCallback, aThisArg) {\n this._array.forEach(aCallback, aThisArg);\n };\n\n/**\n * Add the given source mapping.\n *\n * @param Object aMapping\n */\nMappingList.prototype.add = function MappingList_add(aMapping) {\n if (generatedPositionAfter(this._last, aMapping)) {\n this._last = aMapping;\n this._array.push(aMapping);\n } else {\n this._sorted = false;\n this._array.push(aMapping);\n }\n};\n\n/**\n * Returns the flat, sorted array of mappings. The mappings are sorted by\n * generated position.\n *\n * WARNING: This method returns internal data without copying, for\n * performance. The return value must NOT be mutated, and should be treated as\n * an immutable borrow. If you want to take ownership, you must make your own\n * copy.\n */\nMappingList.prototype.toArray = function MappingList_toArray() {\n if (!this._sorted) {\n this._array.sort(util.compareByGeneratedPositionsInflated);\n this._sorted = true;\n }\n return this._array;\n};\n\nexports.MappingList = MappingList;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/mapping-list.js\n// module id = 6\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar binarySearch = require('./binary-search');\nvar ArraySet = require('./array-set').ArraySet;\nvar base64VLQ = require('./base64-vlq');\nvar quickSort = require('./quick-sort').quickSort;\n\nfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n return sourceMap.sections != null\n ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n}\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nSourceMapConsumer.prototype._version = 3;\n\n// `__generatedMappings` and `__originalMappings` are arrays that hold the\n// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n// are lazily instantiated, accessed via the `_generatedMappings` and\n// `_originalMappings` getters respectively, and we only parse the mappings\n// and create these arrays once queried for a source location. We jump through\n// these hoops because there can be many thousands of mappings, and parsing\n// them is expensive, so we only want to do it if we must.\n//\n// Each object in the arrays is of the form:\n//\n// {\n// generatedLine: The line number in the generated code,\n// generatedColumn: The column number in the generated code,\n// source: The path to the original source file that generated this\n// chunk of code,\n// originalLine: The line number in the original source that\n// corresponds to this chunk of generated code,\n// originalColumn: The column number in the original source that\n// corresponds to this chunk of generated code,\n// name: The name of the original symbol which generated this chunk of\n// code.\n// }\n//\n// All properties except for `generatedLine` and `generatedColumn` can be\n// `null`.\n//\n// `_generatedMappings` is ordered by the generated positions.\n//\n// `_originalMappings` is ordered by the original positions.\n\nSourceMapConsumer.prototype.__generatedMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__generatedMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__generatedMappings;\n }\n});\n\nSourceMapConsumer.prototype.__originalMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__originalMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__originalMappings;\n }\n});\n\nSourceMapConsumer.prototype._charIsMappingSeparator =\n function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n var c = aStr.charAt(index);\n return c === \";\" || c === \",\";\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n throw new Error(\"Subclasses must implement _parseMappings\");\n };\n\nSourceMapConsumer.GENERATED_ORDER = 1;\nSourceMapConsumer.ORIGINAL_ORDER = 2;\n\nSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\nSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\n/**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n * The function that is called with each mapping.\n * @param Object aContext\n * Optional. If specified, this object will be the value of `this` every\n * time that `aCallback` is called.\n * @param aOrder\n * Either `SourceMapConsumer.GENERATED_ORDER` or\n * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n * iterate over the mappings sorted by the generated file's line/column\n * order or the original's source/line/column order, respectively. Defaults to\n * `SourceMapConsumer.GENERATED_ORDER`.\n */\nSourceMapConsumer.prototype.eachMapping =\n function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n var context = aContext || null;\n var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n var mappings;\n switch (order) {\n case SourceMapConsumer.GENERATED_ORDER:\n mappings = this._generatedMappings;\n break;\n case SourceMapConsumer.ORIGINAL_ORDER:\n mappings = this._originalMappings;\n break;\n default:\n throw new Error(\"Unknown order of iteration.\");\n }\n\n var sourceRoot = this.sourceRoot;\n mappings.map(function (mapping) {\n var source = mapping.source === null ? null : this._sources.at(mapping.source);\n source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n return {\n source: source,\n generatedLine: mapping.generatedLine,\n generatedColumn: mapping.generatedColumn,\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: mapping.name === null ? null : this._names.at(mapping.name)\n };\n }, this).forEach(aCallback, context);\n };\n\n/**\n * Returns all generated line and column information for the original source,\n * line, and column provided. If no column is provided, returns all mappings\n * corresponding to a either the line we are searching for or the next\n * closest line that has any mappings. Otherwise, returns all mappings\n * corresponding to the given line and either the column we are searching for\n * or the next closest column that has any offsets.\n *\n * The only argument is an object with the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number is 1-based.\n * - column: Optional. the column number in the original source.\n * The column number is 0-based.\n *\n * and an array of objects is returned, each with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nSourceMapConsumer.prototype.allGeneratedPositionsFor =\n function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n var line = util.getArg(aArgs, 'line');\n\n // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n // returns the index of the closest mapping less than the needle. By\n // setting needle.originalColumn to 0, we thus find the last mapping for\n // the given line, provided such a mapping exists.\n var needle = {\n source: util.getArg(aArgs, 'source'),\n originalLine: line,\n originalColumn: util.getArg(aArgs, 'column', 0)\n };\n\n needle.source = this._findSourceIndex(needle.source);\n if (needle.source < 0) {\n return [];\n }\n\n var mappings = [];\n\n var index = this._findMapping(needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n binarySearch.LEAST_UPPER_BOUND);\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (aArgs.column === undefined) {\n var originalLine = mapping.originalLine;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we found. Since\n // mappings are sorted, this is guaranteed to find all mappings for\n // the line we found.\n while (mapping && mapping.originalLine === originalLine) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n } else {\n var originalColumn = mapping.originalColumn;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we were searching for.\n // Since mappings are sorted, this is guaranteed to find all mappings for\n // the line we are searching for.\n while (mapping &&\n mapping.originalLine === line &&\n mapping.originalColumn == originalColumn) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n }\n }\n\n return mappings;\n };\n\nexports.SourceMapConsumer = SourceMapConsumer;\n\n/**\n * A BasicSourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The first parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - sources: An array of URLs to the original source files.\n * - names: An array of identifiers which can be referrenced by individual mappings.\n * - sourceRoot: Optional. The URL root from which all sources are relative.\n * - sourcesContent: Optional. An array of contents of the original source files.\n * - mappings: A string of base64 VLQs which contain the actual mappings.\n * - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n * {\n * version : 3,\n * file: \"out.js\",\n * sourceRoot : \"\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AA,AB;;ABCDE;\"\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sources = util.getArg(sourceMap, 'sources');\n // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n // requires the array) to play nice here.\n var names = util.getArg(sourceMap, 'names', []);\n var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n var mappings = util.getArg(sourceMap, 'mappings');\n var file = util.getArg(sourceMap, 'file', null);\n\n // Once again, Sass deviates from the spec and supplies the version as a\n // string rather than a number, so we use loose equality checking here.\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n if (sourceRoot) {\n sourceRoot = util.normalize(sourceRoot);\n }\n\n sources = sources\n .map(String)\n // Some source maps produce relative source paths like \"./foo.js\" instead of\n // \"foo.js\". Normalize these first so that future comparisons will succeed.\n // See bugzil.la/1090768.\n .map(util.normalize)\n // Always ensure that absolute sources are internally stored relative to\n // the source root, if the source root is absolute. Not doing this would\n // be particularly problematic when the source root is a prefix of the\n // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n .map(function (source) {\n return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n ? util.relative(sourceRoot, source)\n : source;\n });\n\n // Pass `true` below to allow duplicate names and sources. While source maps\n // are intended to be compressed and deduplicated, the TypeScript compiler\n // sometimes generates source maps with duplicates in them. See Github issue\n // #72 and bugzil.la/889492.\n this._names = ArraySet.fromArray(names.map(String), true);\n this._sources = ArraySet.fromArray(sources, true);\n\n this._absoluteSources = this._sources.toArray().map(function (s) {\n return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n });\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this._sourceMapURL = aSourceMapURL;\n this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Utility function to find the index of a source. Returns -1 if not\n * found.\n */\nBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n if (this._sources.has(relativeSource)) {\n return this._sources.indexOf(relativeSource);\n }\n\n // Maybe aSource is an absolute URL as returned by |sources|. In\n // this case we can't simply undo the transform.\n var i;\n for (i = 0; i < this._absoluteSources.length; ++i) {\n if (this._absoluteSources[i] == aSource) {\n return i;\n }\n }\n\n return -1;\n};\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @param String aSourceMapURL\n * The URL at which the source map can be found (optional)\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n var smc = Object.create(BasicSourceMapConsumer.prototype);\n\n var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n smc.sourceRoot = aSourceMap._sourceRoot;\n smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n smc.sourceRoot);\n smc.file = aSourceMap._file;\n smc._sourceMapURL = aSourceMapURL;\n smc._absoluteSources = smc._sources.toArray().map(function (s) {\n return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n });\n\n // Because we are modifying the entries (by converting string sources and\n // names to indices into the sources and names ArraySets), we have to make\n // a copy of the entry or else bad things happen. Shared mutable state\n // strikes again! See github issue #191.\n\n var generatedMappings = aSourceMap._mappings.toArray().slice();\n var destGeneratedMappings = smc.__generatedMappings = [];\n var destOriginalMappings = smc.__originalMappings = [];\n\n for (var i = 0, length = generatedMappings.length; i < length; i++) {\n var srcMapping = generatedMappings[i];\n var destMapping = new Mapping;\n destMapping.generatedLine = srcMapping.generatedLine;\n destMapping.generatedColumn = srcMapping.generatedColumn;\n\n if (srcMapping.source) {\n destMapping.source = sources.indexOf(srcMapping.source);\n destMapping.originalLine = srcMapping.originalLine;\n destMapping.originalColumn = srcMapping.originalColumn;\n\n if (srcMapping.name) {\n destMapping.name = names.indexOf(srcMapping.name);\n }\n\n destOriginalMappings.push(destMapping);\n }\n\n destGeneratedMappings.push(destMapping);\n }\n\n quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\n return smc;\n };\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nBasicSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n get: function () {\n return this._absoluteSources.slice();\n }\n});\n\n/**\n * Provide the JIT with a nice shape / hidden class.\n */\nfunction Mapping() {\n this.generatedLine = 0;\n this.generatedColumn = 0;\n this.source = null;\n this.originalLine = null;\n this.originalColumn = null;\n this.name = null;\n}\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nBasicSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n var generatedLine = 1;\n var previousGeneratedColumn = 0;\n var previousOriginalLine = 0;\n var previousOriginalColumn = 0;\n var previousSource = 0;\n var previousName = 0;\n var length = aStr.length;\n var index = 0;\n var cachedSegments = {};\n var temp = {};\n var originalMappings = [];\n var generatedMappings = [];\n var mapping, str, segment, end, value;\n\n while (index < length) {\n if (aStr.charAt(index) === ';') {\n generatedLine++;\n index++;\n previousGeneratedColumn = 0;\n }\n else if (aStr.charAt(index) === ',') {\n index++;\n }\n else {\n mapping = new Mapping();\n mapping.generatedLine = generatedLine;\n\n // Because each offset is encoded relative to the previous one,\n // many segments often have the same encoding. We can exploit this\n // fact by caching the parsed variable length fields of each segment,\n // allowing us to avoid a second parse if we encounter the same\n // segment again.\n for (end = index; end < length; end++) {\n if (this._charIsMappingSeparator(aStr, end)) {\n break;\n }\n }\n str = aStr.slice(index, end);\n\n segment = cachedSegments[str];\n if (segment) {\n index += str.length;\n } else {\n segment = [];\n while (index < end) {\n base64VLQ.decode(aStr, index, temp);\n value = temp.value;\n index = temp.rest;\n segment.push(value);\n }\n\n if (segment.length === 2) {\n throw new Error('Found a source, but no line and column');\n }\n\n if (segment.length === 3) {\n throw new Error('Found a source and line, but no column');\n }\n\n cachedSegments[str] = segment;\n }\n\n // Generated column.\n mapping.generatedColumn = previousGeneratedColumn + segment[0];\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (segment.length > 1) {\n // Original source.\n mapping.source = previousSource + segment[1];\n previousSource += segment[1];\n\n // Original line.\n mapping.originalLine = previousOriginalLine + segment[2];\n previousOriginalLine = mapping.originalLine;\n // Lines are stored 0-based\n mapping.originalLine += 1;\n\n // Original column.\n mapping.originalColumn = previousOriginalColumn + segment[3];\n previousOriginalColumn = mapping.originalColumn;\n\n if (segment.length > 4) {\n // Original name.\n mapping.name = previousName + segment[4];\n previousName += segment[4];\n }\n }\n\n generatedMappings.push(mapping);\n if (typeof mapping.originalLine === 'number') {\n originalMappings.push(mapping);\n }\n }\n }\n\n quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n this.__generatedMappings = generatedMappings;\n\n quickSort(originalMappings, util.compareByOriginalPositions);\n this.__originalMappings = originalMappings;\n };\n\n/**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\nBasicSourceMapConsumer.prototype._findMapping =\n function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n aColumnName, aComparator, aBias) {\n // To return the position we are searching for, we must first find the\n // mapping for the given position and then return the opposite position it\n // points to. Because the mappings are sorted, we can use binary search to\n // find the best mapping.\n\n if (aNeedle[aLineName] <= 0) {\n throw new TypeError('Line must be greater than or equal to 1, got '\n + aNeedle[aLineName]);\n }\n if (aNeedle[aColumnName] < 0) {\n throw new TypeError('Column must be greater than or equal to 0, got '\n + aNeedle[aColumnName]);\n }\n\n return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n };\n\n/**\n * Compute the last column for each generated mapping. The last column is\n * inclusive.\n */\nBasicSourceMapConsumer.prototype.computeColumnSpans =\n function SourceMapConsumer_computeColumnSpans() {\n for (var index = 0; index < this._generatedMappings.length; ++index) {\n var mapping = this._generatedMappings[index];\n\n // Mappings do not contain a field for the last generated columnt. We\n // can come up with an optimistic estimate, however, by assuming that\n // mappings are contiguous (i.e. given two consecutive mappings, the\n // first mapping ends where the second one starts).\n if (index + 1 < this._generatedMappings.length) {\n var nextMapping = this._generatedMappings[index + 1];\n\n if (mapping.generatedLine === nextMapping.generatedLine) {\n mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n continue;\n }\n }\n\n // The last mapping for each line spans the entire line.\n mapping.lastGeneratedColumn = Infinity;\n }\n };\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nBasicSourceMapConsumer.prototype.originalPositionFor =\n function SourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._generatedMappings,\n \"generatedLine\",\n \"generatedColumn\",\n util.compareByGeneratedPositionsDeflated,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._generatedMappings[index];\n\n if (mapping.generatedLine === needle.generatedLine) {\n var source = util.getArg(mapping, 'source', null);\n if (source !== null) {\n source = this._sources.at(source);\n source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n }\n var name = util.getArg(mapping, 'name', null);\n if (name !== null) {\n name = this._names.at(name);\n }\n return {\n source: source,\n line: util.getArg(mapping, 'originalLine', null),\n column: util.getArg(mapping, 'originalColumn', null),\n name: name\n };\n }\n }\n\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n function BasicSourceMapConsumer_hasContentsOfAllSources() {\n if (!this.sourcesContent) {\n return false;\n }\n return this.sourcesContent.length >= this._sources.size() &&\n !this.sourcesContent.some(function (sc) { return sc == null; });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nBasicSourceMapConsumer.prototype.sourceContentFor =\n function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n if (!this.sourcesContent) {\n return null;\n }\n\n var index = this._findSourceIndex(aSource);\n if (index >= 0) {\n return this.sourcesContent[index];\n }\n\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n var url;\n if (this.sourceRoot != null\n && (url = util.urlParse(this.sourceRoot))) {\n // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n // many users. We can help them out when they expect file:// URIs to\n // behave like it would if they were running a local HTTP server. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n if (url.scheme == \"file\"\n && this._sources.has(fileUriAbsPath)) {\n return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n }\n\n if ((!url.path || url.path == \"/\")\n && this._sources.has(\"/\" + relativeSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n }\n }\n\n // This function is used recursively from\n // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n // don't want to throw if we can't find the source - we just want to\n // return null, so we provide a flag to exit gracefully.\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var source = util.getArg(aArgs, 'source');\n source = this._findSourceIndex(source);\n if (source < 0) {\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n }\n\n var needle = {\n source: source,\n originalLine: util.getArg(aArgs, 'line'),\n originalColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (mapping.source === needle.source) {\n return {\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n };\n }\n }\n\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n };\n\nexports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\n/**\n * An IndexedSourceMapConsumer instance represents a parsed source map which\n * we can query for information. It differs from BasicSourceMapConsumer in\n * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n * input.\n *\n * The first parameter is a raw source map (either as a JSON string, or already\n * parsed to an object). According to the spec for indexed source maps, they\n * have the following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - file: Optional. The generated file this source map is associated with.\n * - sections: A list of section definitions.\n *\n * Each value under the \"sections\" field has two fields:\n * - offset: The offset into the original specified at which this section\n * begins to apply, defined as an object with a \"line\" and \"column\"\n * field.\n * - map: A source map definition. This source map could also be indexed,\n * but doesn't have to be.\n *\n * Instead of the \"map\" field, it's also possible to have a \"url\" field\n * specifying a URL to retrieve a source map from, but that's currently\n * unsupported.\n *\n * Here's an example source map, taken from the source map spec[0], but\n * modified to omit a section which uses the \"url\" field.\n *\n * {\n * version : 3,\n * file: \"app.js\",\n * sections: [{\n * offset: {line:100, column:10},\n * map: {\n * version : 3,\n * file: \"section.js\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AAAA,E;;ABCDE;\"\n * }\n * }],\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sections = util.getArg(sourceMap, 'sections');\n\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n this._sources = new ArraySet();\n this._names = new ArraySet();\n\n var lastOffset = {\n line: -1,\n column: 0\n };\n this._sections = sections.map(function (s) {\n if (s.url) {\n // The url field will require support for asynchronicity.\n // See https://github.com/mozilla/source-map/issues/16\n throw new Error('Support for url field in sections not implemented.');\n }\n var offset = util.getArg(s, 'offset');\n var offsetLine = util.getArg(offset, 'line');\n var offsetColumn = util.getArg(offset, 'column');\n\n if (offsetLine < lastOffset.line ||\n (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n throw new Error('Section offsets must be ordered and non-overlapping.');\n }\n lastOffset = offset;\n\n return {\n generatedOffset: {\n // The offset fields are 0-based, but we use 1-based indices when\n // encoding/decoding from VLQ.\n generatedLine: offsetLine + 1,\n generatedColumn: offsetColumn + 1\n },\n consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n }\n });\n}\n\nIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nIndexedSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n get: function () {\n var sources = [];\n for (var i = 0; i < this._sections.length; i++) {\n for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n sources.push(this._sections[i].consumer.sources[j]);\n }\n }\n return sources;\n }\n});\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nIndexedSourceMapConsumer.prototype.originalPositionFor =\n function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n // Find the section containing the generated position we're trying to map\n // to an original position.\n var sectionIndex = binarySearch.search(needle, this._sections,\n function(needle, section) {\n var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n return (needle.generatedColumn -\n section.generatedOffset.generatedColumn);\n });\n var section = this._sections[sectionIndex];\n\n if (!section) {\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n }\n\n return section.consumer.originalPositionFor({\n line: needle.generatedLine -\n (section.generatedOffset.generatedLine - 1),\n column: needle.generatedColumn -\n (section.generatedOffset.generatedLine === needle.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n bias: aArgs.bias\n });\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n return this._sections.every(function (s) {\n return s.consumer.hasContentsOfAllSources();\n });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nIndexedSourceMapConsumer.prototype.sourceContentFor =\n function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n var content = section.consumer.sourceContentFor(aSource, true);\n if (content) {\n return content;\n }\n }\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based. \n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nIndexedSourceMapConsumer.prototype.generatedPositionFor =\n function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n // Only consider this section if the requested source is in the list of\n // sources of the consumer.\n if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n continue;\n }\n var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n if (generatedPosition) {\n var ret = {\n line: generatedPosition.line +\n (section.generatedOffset.generatedLine - 1),\n column: generatedPosition.column +\n (section.generatedOffset.generatedLine === generatedPosition.line\n ? section.generatedOffset.generatedColumn - 1\n : 0)\n };\n return ret;\n }\n }\n\n return {\n line: null,\n column: null\n };\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nIndexedSourceMapConsumer.prototype._parseMappings =\n function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n var sectionMappings = section.consumer._generatedMappings;\n for (var j = 0; j < sectionMappings.length; j++) {\n var mapping = sectionMappings[j];\n\n var source = section.consumer._sources.at(mapping.source);\n source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n this._sources.add(source);\n source = this._sources.indexOf(source);\n\n var name = null;\n if (mapping.name) {\n name = section.consumer._names.at(mapping.name);\n this._names.add(name);\n name = this._names.indexOf(name);\n }\n\n // The mappings coming from the consumer for the section have\n // generated positions relative to the start of the section, so we\n // need to offset them to be relative to the start of the concatenated\n // generated file.\n var adjustedMapping = {\n source: source,\n generatedLine: mapping.generatedLine +\n (section.generatedOffset.generatedLine - 1),\n generatedColumn: mapping.generatedColumn +\n (section.generatedOffset.generatedLine === mapping.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: name\n };\n\n this.__generatedMappings.push(adjustedMapping);\n if (typeof adjustedMapping.originalLine === 'number') {\n this.__originalMappings.push(adjustedMapping);\n }\n }\n }\n\n quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n quickSort(this.__originalMappings, util.compareByOriginalPositions);\n };\n\nexports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-map-consumer.js\n// module id = 7\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nexports.GREATEST_LOWER_BOUND = 1;\nexports.LEAST_UPPER_BOUND = 2;\n\n/**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n */\nfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n // This function terminates when one of the following is true:\n //\n // 1. We find the exact element we are looking for.\n //\n // 2. We did not find the exact element, but we can return the index of\n // the next-closest element.\n //\n // 3. We did not find the exact element, and there is no next-closest\n // element than the one we are searching for, so we return -1.\n var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n var cmp = aCompare(aNeedle, aHaystack[mid], true);\n if (cmp === 0) {\n // Found the element we are looking for.\n return mid;\n }\n else if (cmp > 0) {\n // Our needle is greater than aHaystack[mid].\n if (aHigh - mid > 1) {\n // The element is in the upper half.\n return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // The exact needle element was not found in this haystack. Determine if\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return aHigh < aHaystack.length ? aHigh : -1;\n } else {\n return mid;\n }\n }\n else {\n // Our needle is less than aHaystack[mid].\n if (mid - aLow > 1) {\n // The element is in the lower half.\n return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return mid;\n } else {\n return aLow < 0 ? -1 : aLow;\n }\n }\n}\n\n/**\n * This is an implementation of binary search which will always try and return\n * the index of the closest element if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n * array and returns -1, 0, or 1 depending on whether the needle is less\n * than, equal to, or greater than the element, respectively.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n */\nexports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n if (aHaystack.length === 0) {\n return -1;\n }\n\n var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n if (index < 0) {\n return -1;\n }\n\n // We have found either the exact element, or the next-closest element than\n // the one we are searching for. However, there may be more than one such\n // element. Make sure we always return the smallest of these.\n while (index - 1 >= 0) {\n if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n break;\n }\n --index;\n }\n\n return index;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/binary-search.js\n// module id = 8\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n// It turns out that some (most?) JavaScript engines don't self-host\n// `Array.prototype.sort`. This makes sense because C++ will likely remain\n// faster than JS when doing raw CPU-intensive sorting. However, when using a\n// custom comparator function, calling back and forth between the VM's C++ and\n// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n// worse generated code for the comparator function than would be optimal. In\n// fact, when sorting with a comparator, these costs outweigh the benefits of\n// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n// a ~3500ms mean speed-up in `bench/bench.html`.\n\n/**\n * Swap the elements indexed by `x` and `y` in the array `ary`.\n *\n * @param {Array} ary\n * The array.\n * @param {Number} x\n * The index of the first item.\n * @param {Number} y\n * The index of the second item.\n */\nfunction swap(ary, x, y) {\n var temp = ary[x];\n ary[x] = ary[y];\n ary[y] = temp;\n}\n\n/**\n * Returns a random integer within the range `low .. high` inclusive.\n *\n * @param {Number} low\n * The lower bound on the range.\n * @param {Number} high\n * The upper bound on the range.\n */\nfunction randomIntInRange(low, high) {\n return Math.round(low + (Math.random() * (high - low)));\n}\n\n/**\n * The Quick Sort algorithm.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n * @param {Number} p\n * Start index of the array\n * @param {Number} r\n * End index of the array\n */\nfunction doQuickSort(ary, comparator, p, r) {\n // If our lower bound is less than our upper bound, we (1) partition the\n // array into two pieces and (2) recurse on each half. If it is not, this is\n // the empty array and our base case.\n\n if (p < r) {\n // (1) Partitioning.\n //\n // The partitioning chooses a pivot between `p` and `r` and moves all\n // elements that are less than or equal to the pivot to the before it, and\n // all the elements that are greater than it after it. The effect is that\n // once partition is done, the pivot is in the exact place it will be when\n // the array is put in sorted order, and it will not need to be moved\n // again. This runs in O(n) time.\n\n // Always choose a random pivot so that an input array which is reverse\n // sorted does not cause O(n^2) running time.\n var pivotIndex = randomIntInRange(p, r);\n var i = p - 1;\n\n swap(ary, pivotIndex, r);\n var pivot = ary[r];\n\n // Immediately after `j` is incremented in this loop, the following hold\n // true:\n //\n // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n //\n // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n for (var j = p; j < r; j++) {\n if (comparator(ary[j], pivot) <= 0) {\n i += 1;\n swap(ary, i, j);\n }\n }\n\n swap(ary, i + 1, j);\n var q = i + 1;\n\n // (2) Recurse on each half.\n\n doQuickSort(ary, comparator, p, q - 1);\n doQuickSort(ary, comparator, q + 1, r);\n }\n}\n\n/**\n * Sort the given array in-place with the given comparator function.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n */\nexports.quickSort = function (ary, comparator) {\n doQuickSort(ary, comparator, 0, ary.length - 1);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/quick-sort.js\n// module id = 9\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;\nvar util = require('./util');\n\n// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n// operating systems these days (capturing the result).\nvar REGEX_NEWLINE = /(\\r?\\n)/;\n\n// Newline character code for charCodeAt() comparisons\nvar NEWLINE_CODE = 10;\n\n// Private symbol for identifying `SourceNode`s when multiple versions of\n// the source-map library are loaded. This MUST NOT CHANGE across\n// versions!\nvar isSourceNode = \"$$$isSourceNode$$$\";\n\n/**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n * generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\nfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n this.children = [];\n this.sourceContents = {};\n this.line = aLine == null ? null : aLine;\n this.column = aColumn == null ? null : aColumn;\n this.source = aSource == null ? null : aSource;\n this.name = aName == null ? null : aName;\n this[isSourceNode] = true;\n if (aChunks != null) this.add(aChunks);\n}\n\n/**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n * @param aRelativePath Optional. The path that relative sources in the\n * SourceMapConsumer should be relative to.\n */\nSourceNode.fromStringWithSourceMap =\n function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n // The SourceNode we want to fill with the generated code\n // and the SourceMap\n var node = new SourceNode();\n\n // All even indices of this array are one line of the generated code,\n // while all odd indices are the newlines between two adjacent lines\n // (since `REGEX_NEWLINE` captures its match).\n // Processed fragments are accessed by calling `shiftNextLine`.\n var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n var remainingLinesIndex = 0;\n var shiftNextLine = function() {\n var lineContents = getNextLine();\n // The last line of a file might not have a newline.\n var newLine = getNextLine() || \"\";\n return lineContents + newLine;\n\n function getNextLine() {\n return remainingLinesIndex < remainingLines.length ?\n remainingLines[remainingLinesIndex++] : undefined;\n }\n };\n\n // We need to remember the position of \"remainingLines\"\n var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n // The generate SourceNodes we need a code range.\n // To extract it current and last mapping is used.\n // Here we store the last mapping.\n var lastMapping = null;\n\n aSourceMapConsumer.eachMapping(function (mapping) {\n if (lastMapping !== null) {\n // We add the code from \"lastMapping\" to \"mapping\":\n // First check if there is a new line in between.\n if (lastGeneratedLine < mapping.generatedLine) {\n // Associate first line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n lastGeneratedLine++;\n lastGeneratedColumn = 0;\n // The remaining code is added without mapping\n } else {\n // There is no new line in between.\n // Associate the code between \"lastGeneratedColumn\" and\n // \"mapping.generatedColumn\" with \"lastMapping\"\n var nextLine = remainingLines[remainingLinesIndex] || '';\n var code = nextLine.substr(0, mapping.generatedColumn -\n lastGeneratedColumn);\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n lastGeneratedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n addMappingWithCode(lastMapping, code);\n // No more remaining code, continue\n lastMapping = mapping;\n return;\n }\n }\n // We add the generated code until the first mapping\n // to the SourceNode without any mapping.\n // Each line is added as separate string.\n while (lastGeneratedLine < mapping.generatedLine) {\n node.add(shiftNextLine());\n lastGeneratedLine++;\n }\n if (lastGeneratedColumn < mapping.generatedColumn) {\n var nextLine = remainingLines[remainingLinesIndex] || '';\n node.add(nextLine.substr(0, mapping.generatedColumn));\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n }\n lastMapping = mapping;\n }, this);\n // We have processed all mappings.\n if (remainingLinesIndex < remainingLines.length) {\n if (lastMapping) {\n // Associate the remaining code in the current line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n }\n // and add the remaining lines without any mapping\n node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n }\n\n // Copy sourcesContent into SourceNode\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aRelativePath != null) {\n sourceFile = util.join(aRelativePath, sourceFile);\n }\n node.setSourceContent(sourceFile, content);\n }\n });\n\n return node;\n\n function addMappingWithCode(mapping, code) {\n if (mapping === null || mapping.source === undefined) {\n node.add(code);\n } else {\n var source = aRelativePath\n ? util.join(aRelativePath, mapping.source)\n : mapping.source;\n node.add(new SourceNode(mapping.originalLine,\n mapping.originalColumn,\n source,\n code,\n mapping.name));\n }\n }\n };\n\n/**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.add = function SourceNode_add(aChunk) {\n if (Array.isArray(aChunk)) {\n aChunk.forEach(function (chunk) {\n this.add(chunk);\n }, this);\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n if (aChunk) {\n this.children.push(aChunk);\n }\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n if (Array.isArray(aChunk)) {\n for (var i = aChunk.length-1; i >= 0; i--) {\n this.prepend(aChunk[i]);\n }\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n this.children.unshift(aChunk);\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n var chunk;\n for (var i = 0, len = this.children.length; i < len; i++) {\n chunk = this.children[i];\n if (chunk[isSourceNode]) {\n chunk.walk(aFn);\n }\n else {\n if (chunk !== '') {\n aFn(chunk, { source: this.source,\n line: this.line,\n column: this.column,\n name: this.name });\n }\n }\n }\n};\n\n/**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\nSourceNode.prototype.join = function SourceNode_join(aSep) {\n var newChildren;\n var i;\n var len = this.children.length;\n if (len > 0) {\n newChildren = [];\n for (i = 0; i < len-1; i++) {\n newChildren.push(this.children[i]);\n newChildren.push(aSep);\n }\n newChildren.push(this.children[i]);\n this.children = newChildren;\n }\n return this;\n};\n\n/**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\nSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n var lastChild = this.children[this.children.length - 1];\n if (lastChild[isSourceNode]) {\n lastChild.replaceRight(aPattern, aReplacement);\n }\n else if (typeof lastChild === 'string') {\n this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n }\n else {\n this.children.push(''.replace(aPattern, aReplacement));\n }\n return this;\n};\n\n/**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\nSourceNode.prototype.setSourceContent =\n function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n };\n\n/**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walkSourceContents =\n function SourceNode_walkSourceContents(aFn) {\n for (var i = 0, len = this.children.length; i < len; i++) {\n if (this.children[i][isSourceNode]) {\n this.children[i].walkSourceContents(aFn);\n }\n }\n\n var sources = Object.keys(this.sourceContents);\n for (var i = 0, len = sources.length; i < len; i++) {\n aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n }\n };\n\n/**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\nSourceNode.prototype.toString = function SourceNode_toString() {\n var str = \"\";\n this.walk(function (chunk) {\n str += chunk;\n });\n return str;\n};\n\n/**\n * Returns the string representation of this source node along with a source\n * map.\n */\nSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n var generated = {\n code: \"\",\n line: 1,\n column: 0\n };\n var map = new SourceMapGenerator(aArgs);\n var sourceMappingActive = false;\n var lastOriginalSource = null;\n var lastOriginalLine = null;\n var lastOriginalColumn = null;\n var lastOriginalName = null;\n this.walk(function (chunk, original) {\n generated.code += chunk;\n if (original.source !== null\n && original.line !== null\n && original.column !== null) {\n if(lastOriginalSource !== original.source\n || lastOriginalLine !== original.line\n || lastOriginalColumn !== original.column\n || lastOriginalName !== original.name) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n lastOriginalSource = original.source;\n lastOriginalLine = original.line;\n lastOriginalColumn = original.column;\n lastOriginalName = original.name;\n sourceMappingActive = true;\n } else if (sourceMappingActive) {\n map.addMapping({\n generated: {\n line: generated.line,\n column: generated.column\n }\n });\n lastOriginalSource = null;\n sourceMappingActive = false;\n }\n for (var idx = 0, length = chunk.length; idx < length; idx++) {\n if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n generated.line++;\n generated.column = 0;\n // Mappings end at eol\n if (idx + 1 === length) {\n lastOriginalSource = null;\n sourceMappingActive = false;\n } else if (sourceMappingActive) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n } else {\n generated.column++;\n }\n }\n });\n this.walkSourceContents(function (sourceFile, sourceContent) {\n map.setSourceContent(sourceFile, sourceContent);\n });\n\n return { code: generated.code, map: map };\n};\n\nexports.SourceNode = SourceNode;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-node.js\n// module id = 10\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/source-map/lib/array-set.js b/node_modules/source-map/lib/array-set.js new file mode 100644 index 0000000..fbd5c81 --- /dev/null +++ b/node_modules/source-map/lib/array-set.js @@ -0,0 +1,121 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +exports.ArraySet = ArraySet; diff --git a/node_modules/source-map/lib/base64-vlq.js b/node_modules/source-map/lib/base64-vlq.js new file mode 100644 index 0000000..612b404 --- /dev/null +++ b/node_modules/source-map/lib/base64-vlq.js @@ -0,0 +1,140 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 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. + */ + +var base64 = require('./base64'); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; diff --git a/node_modules/source-map/lib/base64.js b/node_modules/source-map/lib/base64.js new file mode 100644 index 0000000..8aa86b3 --- /dev/null +++ b/node_modules/source-map/lib/base64.js @@ -0,0 +1,67 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; diff --git a/node_modules/source-map/lib/binary-search.js b/node_modules/source-map/lib/binary-search.js new file mode 100644 index 0000000..010ac94 --- /dev/null +++ b/node_modules/source-map/lib/binary-search.js @@ -0,0 +1,111 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; diff --git a/node_modules/source-map/lib/mapping-list.js b/node_modules/source-map/lib/mapping-list.js new file mode 100644 index 0000000..06d1274 --- /dev/null +++ b/node_modules/source-map/lib/mapping-list.js @@ -0,0 +1,79 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +exports.MappingList = MappingList; diff --git a/node_modules/source-map/lib/quick-sort.js b/node_modules/source-map/lib/quick-sort.js new file mode 100644 index 0000000..6a7caad --- /dev/null +++ b/node_modules/source-map/lib/quick-sort.js @@ -0,0 +1,114 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ +exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); +}; diff --git a/node_modules/source-map/lib/source-map-consumer.js b/node_modules/source-map/lib/source-map-consumer.js new file mode 100644 index 0000000..7b99d1d --- /dev/null +++ b/node_modules/source-map/lib/source-map-consumer.js @@ -0,0 +1,1145 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var binarySearch = require('./binary-search'); +var ArraySet = require('./array-set').ArraySet; +var base64VLQ = require('./base64-vlq'); +var quickSort = require('./quick-sort').quickSort; + +function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); +} + +SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; diff --git a/node_modules/source-map/lib/source-map-generator.js b/node_modules/source-map/lib/source-map-generator.js new file mode 100644 index 0000000..508bcfb --- /dev/null +++ b/node_modules/source-map/lib/source-map-generator.js @@ -0,0 +1,425 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ = require('./base64-vlq'); +var util = require('./util'); +var ArraySet = require('./array-set').ArraySet; +var MappingList = require('./mapping-list').MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +exports.SourceMapGenerator = SourceMapGenerator; diff --git a/node_modules/source-map/lib/source-node.js b/node_modules/source-map/lib/source-node.js new file mode 100644 index 0000000..8bcdbe3 --- /dev/null +++ b/node_modules/source-map/lib/source-node.js @@ -0,0 +1,413 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; +var util = require('./util'); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +exports.SourceNode = SourceNode; diff --git a/node_modules/source-map/lib/util.js b/node_modules/source-map/lib/util.js new file mode 100644 index 0000000..3ca92e5 --- /dev/null +++ b/node_modules/source-map/lib/util.js @@ -0,0 +1,488 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +} +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); + +function identity (s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; diff --git a/node_modules/source-map/package.json b/node_modules/source-map/package.json new file mode 100644 index 0000000..2466341 --- /dev/null +++ b/node_modules/source-map/package.json @@ -0,0 +1,73 @@ +{ + "name": "source-map", + "description": "Generates and consumes source maps", + "version": "0.6.1", + "homepage": "https://github.com/mozilla/source-map", + "author": "Nick Fitzgerald ", + "contributors": [ + "Tobias Koppers ", + "Duncan Beevers ", + "Stephen Crane ", + "Ryan Seddon ", + "Miles Elam ", + "Mihai Bazon ", + "Michael Ficarra ", + "Todd Wolfson ", + "Alexander Solovyov ", + "Felix Gnass ", + "Conrad Irwin ", + "usrbincc ", + "David Glasser ", + "Chase Douglas ", + "Evan Wallace ", + "Heather Arthur ", + "Hugh Kennedy ", + "David Glasser ", + "Simon Lydell ", + "Jmeas Smith ", + "Michael Z Goddard ", + "azu ", + "John Gozde ", + "Adam Kirkton ", + "Chris Montgomery ", + "J. Ryan Stinnett ", + "Jack Herrington ", + "Chris Truter ", + "Daniel Espeset ", + "Jamie Wong ", + "Eddy Bruël ", + "Hawken Rives ", + "Gilad Peleg ", + "djchie ", + "Gary Ye ", + "Nicolas Lalevée " + ], + "repository": { + "type": "git", + "url": "http://github.com/mozilla/source-map.git" + }, + "main": "./source-map.js", + "files": [ + "source-map.js", + "source-map.d.ts", + "lib/", + "dist/source-map.debug.js", + "dist/source-map.js", + "dist/source-map.min.js", + "dist/source-map.min.js.map" + ], + "engines": { + "node": ">=0.10.0" + }, + "license": "BSD-3-Clause", + "scripts": { + "test": "npm run build && node test/run-tests.js", + "build": "webpack --color", + "toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md" + }, + "devDependencies": { + "doctoc": "^0.15.0", + "webpack": "^1.12.0" + }, + "typings": "source-map" +} diff --git a/node_modules/source-map/source-map.d.ts b/node_modules/source-map/source-map.d.ts new file mode 100644 index 0000000..8f972b0 --- /dev/null +++ b/node_modules/source-map/source-map.d.ts @@ -0,0 +1,98 @@ +export interface StartOfSourceMap { + file?: string; + sourceRoot?: string; +} + +export interface RawSourceMap extends StartOfSourceMap { + version: string; + sources: string[]; + names: string[]; + sourcesContent?: string[]; + mappings: string; +} + +export interface Position { + line: number; + column: number; +} + +export interface LineRange extends Position { + lastColumn: number; +} + +export interface FindPosition extends Position { + // SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND + bias?: number; +} + +export interface SourceFindPosition extends FindPosition { + source: string; +} + +export interface MappedPosition extends Position { + source: string; + name?: string; +} + +export interface MappingItem { + source: string; + generatedLine: number; + generatedColumn: number; + originalLine: number; + originalColumn: number; + name: string; +} + +export class SourceMapConsumer { + static GENERATED_ORDER: number; + static ORIGINAL_ORDER: number; + + static GREATEST_LOWER_BOUND: number; + static LEAST_UPPER_BOUND: number; + + constructor(rawSourceMap: RawSourceMap); + computeColumnSpans(): void; + originalPositionFor(generatedPosition: FindPosition): MappedPosition; + generatedPositionFor(originalPosition: SourceFindPosition): LineRange; + allGeneratedPositionsFor(originalPosition: MappedPosition): Position[]; + hasContentsOfAllSources(): boolean; + sourceContentFor(source: string, returnNullOnMissing?: boolean): string; + eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; +} + +export interface Mapping { + generated: Position; + original: Position; + source: string; + name?: string; +} + +export class SourceMapGenerator { + constructor(startOfSourceMap?: StartOfSourceMap); + static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator; + addMapping(mapping: Mapping): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; + toString(): string; +} + +export interface CodeWithSourceMap { + code: string; + map: SourceMapGenerator; +} + +export class SourceNode { + constructor(); + constructor(line: number, column: number, source: string); + constructor(line: number, column: number, source: string, chunk?: string, name?: string); + static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode; + add(chunk: string): void; + prepend(chunk: string): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + walkSourceContents(fn: (file: string, content: string) => void): void; + join(sep: string): SourceNode; + replaceRight(pattern: string, replacement: string): SourceNode; + toString(): string; + toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; +} diff --git a/node_modules/source-map/source-map.js b/node_modules/source-map/source-map.js new file mode 100644 index 0000000..bc88fe8 --- /dev/null +++ b/node_modules/source-map/source-map.js @@ -0,0 +1,8 @@ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; diff --git a/node_modules/uglify-js/LICENSE b/node_modules/uglify-js/LICENSE new file mode 100644 index 0000000..122e8fb --- /dev/null +++ b/node_modules/uglify-js/LICENSE @@ -0,0 +1,29 @@ +UglifyJS is released under the BSD license: + +Copyright 2012-2019 (c) Mihai Bazon + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * 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. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. diff --git a/node_modules/uglify-js/README.md b/node_modules/uglify-js/README.md new file mode 100644 index 0000000..ba5f2a2 --- /dev/null +++ b/node_modules/uglify-js/README.md @@ -0,0 +1,1478 @@ +UglifyJS 3 +========== + +UglifyJS is a JavaScript parser, minifier, compressor and beautifier toolkit. + +#### Note: +- `uglify-js` supports JavaScript and most language features in ECMAScript. +- For more exotic parts of ECMAScript, process your source file with transpilers + like [Babel](https://babeljs.io/) before passing onto `uglify-js`. +- `uglify-js@3` has a simplified [API](#api-reference) and [CLI](#command-line-usage) + that is not backwards compatible with [`uglify-js@2`](https://github.com/mishoo/UglifyJS/tree/v2.x). + +Install +------- + +First make sure you have installed the latest version of [node.js](http://nodejs.org/) +(You may need to restart your computer after this step). + +From NPM for use as a command line app: + + npm install uglify-js -g + +From NPM for programmatic use: + + npm install uglify-js + +# Command line usage + + uglifyjs [input files] [options] + +UglifyJS can take multiple input files. It's recommended that you pass the +input files first, then pass the options. UglifyJS will parse input files +in sequence and apply any compression options. The files are parsed in the +same global scope, that is, a reference from a file to some +variable/function declared in another file will be matched properly. + +If no input file is specified, UglifyJS will read from STDIN. + +If you wish to pass your options before the input files, separate the two with +a double dash to prevent input files being used as option arguments: + + uglifyjs --compress --mangle -- input.js + +### Command line options + +``` + -h, --help Print usage information. + `--help options` for details on available options. + -V, --version Print version number. + -p, --parse Specify parser options: + `acorn` Use Acorn for parsing. + `bare_returns` Allow return outside of functions. + Useful when minifying CommonJS + modules and Userscripts that may + be anonymous function wrapped (IIFE) + by the .user.js engine `caller`. + `spidermonkey` Assume input files are SpiderMonkey + AST format (as JSON). + -c, --compress [options] Enable compressor/specify compressor options: + `pure_funcs` List of functions that can be safely + removed when their return values are + not used. + -m, --mangle [options] Mangle names/specify mangler options: + `reserved` List of names that should not be mangled. + --mangle-props [options] Mangle properties/specify mangler options: + `builtins` Mangle property names that overlaps + with standard JavaScript globals. + `debug` Add debug prefix and suffix. + `domprops` Mangle property names that overlaps + with DOM properties. + `keep_quoted` Only mangle unquoted properties. + `regex` Only mangle matched property names. + `reserved` List of names that should not be mangled. + -b, --beautify [options] Beautify output/specify output options: + `beautify` Enabled with `--beautify` by default. + `preamble` Preamble to prepend to the output. You + can use this to insert a comment, for + example for licensing information. + This will not be parsed, but the source + map will adjust for its presence. + `quote_style` Quote style: + 0 - auto + 1 - single + 2 - double + 3 - original + `wrap_iife` Wrap IIFEs in parentheses. Note: you may + want to disable `negate_iife` under + compressor options. + -O, --output-opts [options] Specify output options (`beautify` disabled by default). + -o, --output Output file path (default STDOUT). Specify `ast` or + `spidermonkey` to write UglifyJS or SpiderMonkey AST + as JSON to STDOUT respectively. + --annotations Process and preserve comment annotations. + (`/*@__PURE__*/` or `/*#__PURE__*/`) + --no-annotations Ignore and discard comment annotations. + --comments [filter] Preserve copyright comments in the output. By + default this works like Google Closure, keeping + JSDoc-style comments that contain "@license" or + "@preserve". You can optionally pass one of the + following arguments to this flag: + - "all" to keep all comments + - a valid JS RegExp like `/foo/` or `/^!/` to + keep only matching comments. + Note that currently not *all* comments can be + kept when compression is on, because of dead + code removal or cascading statements into + sequences. + --config-file Read `minify()` options from JSON file. + -d, --define [=value] Global definitions. + -e, --enclose [arg[:value]] Embed everything in a big function, with configurable + argument(s) & value(s). + --expression Parse a single expression, rather than a program + (for parsing JSON). + --ie Support non-standard Internet Explorer. + Equivalent to setting `ie: true` in `minify()` + for `compress`, `mangle` and `output` options. + By default UglifyJS will not try to be IE-proof. + --keep-fargs Do not mangle/drop function arguments. + --keep-fnames Do not mangle/drop function names. Useful for + code relying on Function.prototype.name. + --module Process input as ES module (implies --toplevel) + --name-cache File to hold mangled name mappings. + --self Build UglifyJS as a library (implies --wrap UglifyJS) + --source-map [options] Enable source map/specify source map options: + `base` Path to compute relative paths from input files. + `content` Input source map, useful if you're compressing + JS that was generated from some other original + code. Specify "inline" if the source map is + included within the sources. + `filename` Filename and/or location of the output source + (sets `file` attribute in source map). + `includeSources` Pass this flag if you want to include + the content of source files in the + source map as sourcesContent property. + `names` Include symbol names in the source map. + `root` Path to the original source to be included in + the source map. + `url` If specified, path to the source map to append in + `//# sourceMappingURL`. + --timings Display operations run time on STDERR. + --toplevel Compress and/or mangle variables in top level scope. + --v8 Support non-standard Chrome & Node.js + Equivalent to setting `v8: true` in `minify()` + for `mangle` and `output` options. + By default UglifyJS will not try to be v8-proof. + --verbose Print diagnostic messages. + --warn Print warning messages. + --webkit Support non-standard Safari/Webkit. + Equivalent to setting `webkit: true` in `minify()` + for `compress`, `mangle` and `output` options. + By default UglifyJS will not try to be Safari-proof. + --wrap Embed everything in a big function, making the + “exports” and “global” variables available. You + need to pass an argument to this option to + specify the name that your module will take + when included in, say, a browser. +``` + +Specify `--output` (`-o`) to declare the output file. Otherwise the output +goes to STDOUT. + +## CLI source map options + +UglifyJS can generate a source map file, which is highly useful for +debugging your compressed JavaScript. To get a source map, pass +`--source-map --output output.js` (source map will be written out to +`output.js.map`). + +Additional options: + +- `--source-map "filename=''"` to specify the name of the source map. The value of + `filename` is only used to set `file` attribute (see [the spec][sm-spec]) + in source map file. + +- `--source-map "root=''"` to pass the URL where the original files can be found. + +- `--source-map "names=false"` to omit symbol names if you want to reduce size + of the source map file. + +- `--source-map "url=''"` to specify the URL where the source map can be found. + Otherwise UglifyJS assumes HTTP `X-SourceMap` is being used and will omit the + `//# sourceMappingURL=` directive. + +For example: + + uglifyjs js/file1.js js/file2.js \ + -o foo.min.js -c -m \ + --source-map "root='http://foo.com/src',url='foo.min.js.map'" + +The above will compress and mangle `file1.js` and `file2.js`, will drop the +output in `foo.min.js` and the source map in `foo.min.js.map`. The source +mapping will refer to `http://foo.com/src/js/file1.js` and +`http://foo.com/src/js/file2.js` (in fact it will list `http://foo.com/src` +as the source map root, and the original files as `js/file1.js` and +`js/file2.js`). + +### Composed source map + +When you're compressing JS code that was output by a compiler such as +CoffeeScript, mapping to the JS code won't be too helpful. Instead, you'd +like to map back to the original code (i.e. CoffeeScript). UglifyJS has an +option to take an input source map. Assuming you have a mapping from +CoffeeScript → compiled JS, UglifyJS can generate a map from CoffeeScript → +compressed JS by mapping every token in the compiled JS to its original +location. + +To use this feature pass `--source-map "content='/path/to/input/source.map'"` +or `--source-map "content=inline"` if the source map is included inline with +the sources. + +## CLI compress options + +You need to pass `--compress` (`-c`) to enable the compressor. Optionally +you can pass a comma-separated list of [compress options](#compress-options). + +Options are in the form `foo=bar`, or just `foo` (the latter implies +a boolean option that you want to set `true`; it's effectively a +shortcut for `foo=true`). + +Example: + + uglifyjs file.js -c toplevel,sequences=false + +## CLI mangle options + +To enable the mangler you need to pass `--mangle` (`-m`). The following +(comma-separated) options are supported: + +- `eval` (default: `false`) — mangle names visible in scopes where `eval` or + `with` are used. + +- `reserved` (default: `[]`) — when mangling is enabled but you want to + prevent certain names from being mangled, you can declare those names with + `--mangle reserved` — pass a comma-separated list of names. For example: + + uglifyjs ... -m reserved=['$','require','exports'] + + to prevent the `require`, `exports` and `$` names from being changed. + +### CLI mangling property names (`--mangle-props`) + +**Note:** THIS WILL PROBABLY BREAK YOUR CODE. Mangling property names +is a separate step, different from variable name mangling. Pass +`--mangle-props` to enable it. It will mangle all properties in the +input code with the exception of built in DOM properties and properties +in core JavaScript classes. For example: + +```javascript +// example.js +var x = { + baz_: 0, + foo_: 1, + calc: function() { + return this.foo_ + this.baz_; + } +}; +x.bar_ = 2; +x["baz_"] = 3; +console.log(x.calc()); +``` +Mangle all properties (except for JavaScript `builtins`): +```bash +$ uglifyjs example.js -c -m --mangle-props +``` +```javascript +var x={o:0,_:1,l:function(){return this._+this.o}};x.t=2,x.o=3,console.log(x.l()); +``` +Mangle all properties except for `reserved` properties: +```bash +$ uglifyjs example.js -c -m --mangle-props reserved=[foo_,bar_] +``` +```javascript +var x={o:0,foo_:1,_:function(){return this.foo_+this.o}};x.bar_=2,x.o=3,console.log(x._()); +``` +Mangle all properties matching a `regex`: +```bash +$ uglifyjs example.js -c -m --mangle-props regex=/_$/ +``` +```javascript +var x={o:0,_:1,calc:function(){return this._+this.o}};x.l=2,x.o=3,console.log(x.calc()); +``` + +Combining mangle properties options: +```bash +$ uglifyjs example.js -c -m --mangle-props regex=/_$/,reserved=[bar_] +``` +```javascript +var x={o:0,_:1,calc:function(){return this._+this.o}};x.bar_=2,x.o=3,console.log(x.calc()); +``` + +In order for this to be of any use, we avoid mangling standard JS names by +default (`--mangle-props builtins` to override). + +A default exclusion file is provided in `tools/domprops.json` which should +cover most standard JS and DOM properties defined in various browsers. Pass +`--mangle-props domprops` to disable this feature. + +A regular expression can be used to define which property names should be +mangled. For example, `--mangle-props regex=/^_/` will only mangle property +names that start with an underscore. + +When you compress multiple files using this option, in order for them to +work together in the end we need to ensure somehow that one property gets +mangled to the same name in all of them. For this, pass `--name-cache filename.json` +and UglifyJS will maintain these mappings in a file which can then be reused. +It should be initially empty. Example: + +```bash +$ rm -f /tmp/cache.json # start fresh +$ uglifyjs file1.js file2.js --mangle-props --name-cache /tmp/cache.json -o part1.js +$ uglifyjs file3.js file4.js --mangle-props --name-cache /tmp/cache.json -o part2.js +``` + +Now, `part1.js` and `part2.js` will be consistent with each other in terms +of mangled property names. + +Using the name cache is not necessary if you compress all your files in a +single call to UglifyJS. + +### Mangling unquoted names (`--mangle-props keep_quoted`) + +Using quoted property name (`o["foo"]`) reserves the property name (`foo`) +so that it is not mangled throughout the entire script even when used in an +unquoted style (`o.foo`). Example: + +```javascript +// stuff.js +var o = { + "foo": 1, + bar: 3, +}; +o.foo += o.bar; +console.log(o.foo); +``` +```bash +$ uglifyjs stuff.js --mangle-props keep_quoted -c -m +``` +```javascript +var o={foo:1,o:3};o.foo+=o.o,console.log(o.foo); +``` + +If the minified output will be processed again by UglifyJS, consider specifying +`keep_quoted_props` so the same property names are preserved: + +```bash +$ uglifyjs stuff.js --mangle-props keep_quoted -c -m -O keep_quoted_props +``` +```javascript +var o={"foo":1,o:3};o.foo+=o.o,console.log(o.foo); +``` + +### Debugging property name mangling + +You can also pass `--mangle-props debug` in order to mangle property names +without completely obscuring them. For example the property `o.foo` +would mangle to `o._$foo$_` with this option. This allows property mangling +of a large codebase while still being able to debug the code and identify +where mangling is breaking things. + +```bash +$ uglifyjs stuff.js --mangle-props debug -c -m +``` +```javascript +var o={_$foo$_:1,_$bar$_:3};o._$foo$_+=o._$bar$_,console.log(o._$foo$_); +``` + +You can also pass a custom suffix using `--mangle-props debug=XYZ`. This would then +mangle `o.foo` to `o._$foo$XYZ_`. You can change this each time you compile a +script to identify how a property got mangled. One technique is to pass a +random number on every compile to simulate mangling changing with different +inputs (e.g. as you update the input script with new properties), and to help +identify mistakes like writing mangled keys to storage. + + +# API Reference + +Assuming installation via NPM, you can load UglifyJS in your application +like this: +```javascript +var UglifyJS = require("uglify-js"); +``` + +There is a single high level function, **`minify(code, options)`**, +which will perform all minification [phases](#minify-options) in a configurable +manner. By default `minify()` will enable the options [`compress`](#compress-options) +and [`mangle`](#mangle-options). Example: +```javascript +var code = "function add(first, second) { return first + second; }"; +var result = UglifyJS.minify(code); +console.log(result.error); // runtime error, or `undefined` if no error +console.log(result.code); // minified output: function add(n,d){return n+d} +``` + +You can `minify` more than one JavaScript file at a time by using an object +for the first argument where the keys are file names and the values are source +code: +```javascript +var code = { + "file1.js": "function add(first, second) { return first + second; }", + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}; +var result = UglifyJS.minify(code); +console.log(result.code); +// function add(d,n){return d+n}console.log(add(3,7)); +``` + +The `toplevel` option: +```javascript +var code = { + "file1.js": "function add(first, second) { return first + second; }", + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}; +var options = { toplevel: true }; +var result = UglifyJS.minify(code, options); +console.log(result.code); +// console.log(3+7); +``` + +The `nameCache` option: +```javascript +var options = { + mangle: { + toplevel: true, + }, + nameCache: {} +}; +var result1 = UglifyJS.minify({ + "file1.js": "function add(first, second) { return first + second; }" +}, options); +var result2 = UglifyJS.minify({ + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}, options); +console.log(result1.code); +// function n(n,r){return n+r} +console.log(result2.code); +// console.log(n(3,7)); +``` + +You may persist the name cache to the file system in the following way: +```javascript +var cacheFileName = "/tmp/cache.json"; +var options = { + mangle: { + properties: true, + }, + nameCache: JSON.parse(fs.readFileSync(cacheFileName, "utf8")) +}; +fs.writeFileSync("part1.js", UglifyJS.minify({ + "file1.js": fs.readFileSync("file1.js", "utf8"), + "file2.js": fs.readFileSync("file2.js", "utf8") +}, options).code, "utf8"); +fs.writeFileSync("part2.js", UglifyJS.minify({ + "file3.js": fs.readFileSync("file3.js", "utf8"), + "file4.js": fs.readFileSync("file4.js", "utf8") +}, options).code, "utf8"); +fs.writeFileSync(cacheFileName, JSON.stringify(options.nameCache), "utf8"); +``` + +An example of a combination of `minify()` options: +```javascript +var code = { + "file1.js": "function add(first, second) { return first + second; }", + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}; +var options = { + toplevel: true, + compress: { + global_defs: { + "@console.log": "alert" + }, + passes: 2 + }, + output: { + beautify: false, + preamble: "/* uglified */" + } +}; +var result = UglifyJS.minify(code, options); +console.log(result.code); +// /* uglified */ +// alert(10);" +``` + +To produce warnings: +```javascript +var code = "function f(){ var u; return 2 + 3; }"; +var options = { warnings: true }; +var result = UglifyJS.minify(code, options); +console.log(result.error); // runtime error, `undefined` in this case +console.log(result.warnings); // [ 'Dropping unused variable u [0:1,18]' ] +console.log(result.code); // function f(){return 5} +``` + +An error example: +```javascript +var result = UglifyJS.minify({"foo.js" : "if (0) else console.log(1);"}); +console.log(JSON.stringify(result.error)); +// {"message":"Unexpected token: keyword (else)","filename":"foo.js","line":1,"col":7,"pos":7} +``` +Note: unlike `uglify-js@2.x`, the `3.x` API does not throw errors. To +achieve a similar effect one could do the following: +```javascript +var result = UglifyJS.minify(code, options); +if (result.error) throw result.error; +``` + +## Minify options + +- `annotations` — pass `false` to ignore all comment annotations and elide them + from output. Useful when, for instance, external tools incorrectly applied + `/*@__PURE__*/` or `/*#__PURE__*/`. Pass `true` to both compress and retain + comment annotations in output to allow for further processing downstream. + +- `compress` (default: `{}`) — pass `false` to skip compressing entirely. + Pass an object to specify custom [compress options](#compress-options). + +- `expression` (default: `false`) — parse as a single expression, e.g. JSON. + +- `ie` (default: `false`) — enable workarounds for Internet Explorer bugs. + +- `keep_fargs` (default: `false`) — pass `true` to prevent discarding or mangling + of function arguments. + +- `keep_fnames` (default: `false`) — pass `true` to prevent discarding or mangling + of function names. Useful for code relying on `Function.prototype.name`. + +- `mangle` (default: `true`) — pass `false` to skip mangling names, or pass + an object to specify [mangle options](#mangle-options) (see below). + + - `mangle.properties` (default: `false`) — a subcategory of the mangle option. + Pass an object to specify custom [mangle property options](#mangle-properties-options). + +- `module` (default: `false`) — set to `true` if you wish to process input as + ES module, i.e. implicit `"use strict";` and support for top-level `await`, + alongside with `toplevel` enabled. + +- `nameCache` (default: `null`) — pass an empty object `{}` or a previously + used `nameCache` object if you wish to cache mangled variable and + property names across multiple invocations of `minify()`. Note: this is + a read/write property. `minify()` will read the name cache state of this + object and update it during minification so that it may be + reused or externally persisted by the user. + +- `output` (default: `null`) — pass an object if you wish to specify + additional [output options](#output-options). The defaults are optimized + for best compression. + +- `parse` (default: `{}`) — pass an object if you wish to specify some + additional [parse options](#parse-options). + +- `sourceMap` (default: `false`) — pass an object if you wish to specify + [source map options](#source-map-options). + +- `toplevel` (default: `false`) — set to `true` if you wish to enable top level + variable and function name mangling and to drop unused variables and functions. + +- `v8` (default: `false`) — enable workarounds for Chrome & Node.js bugs. + +- `warnings` (default: `false`) — pass `true` to return compressor warnings + in `result.warnings`. Use the value `"verbose"` for more detailed warnings. + +- `webkit` (default: `false`) — enable workarounds for Safari/WebKit bugs. + PhantomJS users should set this option to `true`. + +## Minify options structure + +```javascript +{ + parse: { + // parse options + }, + compress: { + // compress options + }, + mangle: { + // mangle options + + properties: { + // mangle property options + } + }, + output: { + // output options + }, + sourceMap: { + // source map options + }, + nameCache: null, // or specify a name cache object + toplevel: false, + warnings: false, +} +``` + +### Source map options + +To generate a source map: +```javascript +var result = UglifyJS.minify({"file1.js": "var a = function() {};"}, { + sourceMap: { + filename: "out.js", + url: "out.js.map" + } +}); +console.log(result.code); // minified output +console.log(result.map); // source map +``` + +Note that the source map is not saved in a file, it's just returned in +`result.map`. The value passed for `sourceMap.url` is only used to set +`//# sourceMappingURL=out.js.map` in `result.code`. The value of +`filename` is only used to set `file` attribute (see [the spec][sm-spec]) +in source map file. + +You can set option `sourceMap.url` to be `"inline"` and source map will +be appended to code. + +You can also specify sourceRoot property to be included in source map: +```javascript +var result = UglifyJS.minify({"file1.js": "var a = function() {};"}, { + sourceMap: { + root: "http://example.com/src", + url: "out.js.map" + } +}); +``` + +If you're compressing compiled JavaScript and have a source map for it, you +can use `sourceMap.content`: +```javascript +var result = UglifyJS.minify({"compiled.js": "compiled code"}, { + sourceMap: { + content: "content from compiled.js.map", + url: "minified.js.map" + } +}); +// same as before, it returns `code` and `map` +``` + +If you're using the `X-SourceMap` header instead, you can just omit `sourceMap.url`. + +If you wish to reduce file size of the source map, set option `sourceMap.names` +to be `false` and all symbol names will be omitted. + +## Parse options + +- `bare_returns` (default: `false`) — support top level `return` statements + +- `html5_comments` (default: `true`) — process HTML comment as workaround for + browsers which do not recognize `` in strings + +- `keep_quoted_props` (default: `false`) — when turned on, prevents stripping + quotes from property names in object literals. + +- `max_line_len` (default: `false`) — maximum line length (for uglified code) + +- `preamble` (default: `null`) — when passed it must be a string and + it will be prepended to the output literally. The source map will + adjust for this text. Can be used to insert a comment containing + licensing information, for example. + +- `preserve_line` (default: `false`) — pass `true` to retain line numbering on + a best effort basis. + +- `quote_keys` (default: `false`) — pass `true` to quote all keys in literal + objects + +- `quote_style` (default: `0`) — preferred quote style for strings (affects + quoted property names and directives as well): + - `0` — prefers double quotes, switches to single quotes when there are + more double quotes in the string itself. `0` is best for gzip size. + - `1` — always use single quotes + - `2` — always use double quotes + - `3` — always use the original quotes + +- `semicolons` (default: `true`) — separate statements with semicolons. If + you pass `false` then whenever possible we will use a newline instead of a + semicolon, leading to more readable output of uglified code (size before + gzip could be smaller; size after gzip insignificantly larger). + +- `shebang` (default: `true`) — preserve shebang `#!` in preamble (bash scripts) + +- `width` (default: `80`) — only takes effect when beautification is on, this + specifies an (orientative) line width that the beautifier will try to + obey. It refers to the width of the line text (excluding indentation). + It doesn't work very well currently, but it does make the code generated + by UglifyJS more readable. + +- `wrap_iife` (default: `false`) — pass `true` to wrap immediately invoked + function expressions. See + [#640](https://github.com/mishoo/UglifyJS/issues/640) for more details. + +# Miscellaneous + +### Keeping copyright notices or other comments + +You can pass `--comments` to retain certain comments in the output. By +default it will keep JSDoc-style comments that contain "@preserve", +"@license" or "@cc_on" (conditional compilation for IE). You can pass +`--comments all` to keep all the comments, or a valid JavaScript regexp to +keep only comments that match this regexp. For example `--comments /^!/` +will keep comments like `/*! Copyright Notice */`. + +Note, however, that there might be situations where comments are lost. For +example: +```javascript +function f() { + /** @preserve Foo Bar */ + function g() { + // this function is never called + } + return something(); +} +``` + +Even though it has "@preserve", the comment will be lost because the inner +function `g` (which is the AST node to which the comment is attached to) is +discarded by the compressor as not referenced. + +The safest comments where to place copyright information (or other info that +needs to be kept in the output) are comments attached to toplevel nodes. + +### The `unsafe` `compress` option + +It enables some transformations that *might* break code logic in certain +contrived cases, but should be fine for most code. You might want to try it +on your own code, it should reduce the minified size. Here's what happens +when this flag is on: + +- `new Array(1, 2, 3)` or `Array(1, 2, 3)` → `[ 1, 2, 3 ]` +- `new Object()` → `{}` +- `String(exp)` or `exp.toString()` → `"" + exp` +- `new Object/RegExp/Function/Error/Array (...)` → we discard the `new` + +### Conditional compilation + +You can use the `--define` (`-d`) switch in order to declare global +variables that UglifyJS will assume to be constants (unless defined in +scope). For example if you pass `--define DEBUG=false` then, coupled with +dead code removal UglifyJS will discard the following from the output: +```javascript +if (DEBUG) { + console.log("debug stuff"); +} +``` + +You can specify nested constants in the form of `--define env.DEBUG=false`. + +UglifyJS will warn about the condition being always false and about dropping +unreachable code; for now there is no option to turn off only this specific +warning, you can pass `warnings=false` to turn off *all* warnings. + +Another way of doing that is to declare your globals as constants in a +separate file and include it into the build. For example you can have a +`build/defines.js` file with the following: +```javascript +var DEBUG = false; +var PRODUCTION = true; +// etc. +``` + +and build your code like this: + + uglifyjs build/defines.js js/foo.js js/bar.js... -c + +UglifyJS will notice the constants and, since they cannot be altered, it +will evaluate references to them to the value itself and drop unreachable +code as usual. The build will contain the `const` declarations if you use +them. If you are targeting < ES6 environments which does not support `const`, +using `var` with `reduce_vars` (enabled by default) should suffice. + +### Conditional compilation API + +You can also use conditional compilation via the programmatic API. With the difference that the +property name is `global_defs` and is a compressor property: + +```javascript +var result = UglifyJS.minify(fs.readFileSync("input.js", "utf8"), { + compress: { + dead_code: true, + global_defs: { + DEBUG: false + } + } +}); +``` + +To replace an identifier with an arbitrary non-constant expression it is +necessary to prefix the `global_defs` key with `"@"` to instruct UglifyJS +to parse the value as an expression: +```javascript +UglifyJS.minify("alert('hello');", { + compress: { + global_defs: { + "@alert": "console.log" + } + } +}).code; +// returns: 'console.log("hello");' +``` + +Otherwise it would be replaced as string literal: +```javascript +UglifyJS.minify("alert('hello');", { + compress: { + global_defs: { + "alert": "console.log" + } + } +}).code; +// returns: '"console.log"("hello");' +``` + +### Using native Uglify AST with `minify()` +```javascript +// example: parse only, produce native Uglify AST + +var result = UglifyJS.minify(code, { + parse: {}, + compress: false, + mangle: false, + output: { + ast: true, + code: false // optional - faster if false + } +}); + +// result.ast contains native Uglify AST +``` +```javascript +// example: accept native Uglify AST input and then compress and mangle +// to produce both code and native AST. + +var result = UglifyJS.minify(ast, { + compress: {}, + mangle: {}, + output: { + ast: true, + code: true // optional - faster if false + } +}); + +// result.ast contains native Uglify AST +// result.code contains the minified code in string form. +``` + +### Working with Uglify AST + +Transversal and transformation of the native AST can be performed through +[`TreeWalker`](https://github.com/mishoo/UglifyJS/blob/master/lib/ast.js) and +[`TreeTransformer`](https://github.com/mishoo/UglifyJS/blob/master/lib/transform.js) +respectively. + +### ESTree / SpiderMonkey AST + +UglifyJS has its own abstract syntax tree format; for +[practical reasons](http://lisperator.net/blog/uglifyjs-why-not-switching-to-spidermonkey-ast/) +we can't easily change to using the SpiderMonkey AST internally. However, +UglifyJS now has a converter which can import a SpiderMonkey AST. + +For example [Acorn][acorn] is a super-fast parser that produces a +SpiderMonkey AST. It has a small CLI utility that parses one file and dumps +the AST in JSON on the standard output. To use UglifyJS to mangle and +compress that: + + acorn file.js | uglifyjs -p spidermonkey -m -c + +The `-p spidermonkey` option tells UglifyJS that all input files are not +JavaScript, but JS code described in SpiderMonkey AST in JSON. Therefore we +don't use our own parser in this case, but just transform that AST into our +internal AST. + +### Use Acorn for parsing + +More for fun, I added the `-p acorn` option which will use Acorn to do all +the parsing. If you pass this option, UglifyJS will `require("acorn")`. + +Acorn is really fast (e.g. 250ms instead of 380ms on some 650K code), but +converting the SpiderMonkey tree that Acorn produces takes another 150ms so +in total it's a bit more than just using UglifyJS's own parser. + +[acorn]: https://github.com/ternjs/acorn +[sm-spec]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k + +### Uglify Fast Minify Mode + +It's not well known, but whitespace removal and symbol mangling accounts +for 95% of the size reduction in minified code for most JavaScript - not +elaborate code transforms. One can simply disable `compress` to speed up +Uglify builds by 3 to 5 times. + +| d3.js | minify size | gzip size | minify time (seconds) | +| --- | ---: | ---: | ---: | +| original | 511,371 | 119,932 | - | +| uglify-js@3.13.0 mangle=false, compress=false | 363,988 | 95,695 | 0.56 | +| uglify-js@3.13.0 mangle=true, compress=false | 253,305 | 81,281 | 0.99 | +| uglify-js@3.13.0 mangle=true, compress=true | 244,436 | 79,854 | 5.30 | + +To enable fast minify mode from the CLI use: +``` +uglifyjs file.js -m +``` +To enable fast minify mode with the API use: +```javascript +UglifyJS.minify(code, { compress: false, mangle: true }); +``` + +### Source maps and debugging + +Various `compress` transforms that simplify, rearrange, inline and remove code +are known to have an adverse effect on debugging with source maps. This is +expected as code is optimized and mappings are often simply not possible as +some code no longer exists. For highest fidelity in source map debugging +disable the Uglify `compress` option and just use `mangle`. + +### Compiler assumptions + +To allow for better optimizations, the compiler makes various assumptions: + +- The code does not rely on preserving its runtime performance characteristics. + Typically uglified code will run faster due to less instructions and easier + inlining, but may be slower on rare occasions for a specific platform, e.g. + see [`reduce_funcs`](#compress-options). +- `.toString()` and `.valueOf()` don't have side effects, and for built-in + objects they have not been overridden. +- `undefined`, `NaN` and `Infinity` have not been externally redefined. +- `arguments.callee`, `arguments.caller` and `Function.prototype.caller` are not used. +- The code doesn't expect the contents of `Function.prototype.toString()` or + `Error.prototype.stack` to be anything in particular. +- Getting and setting properties on a plain object does not cause other side effects + (using `.watch()` or `Proxy`). +- Object properties can be added, removed and modified (not prevented with + `Object.defineProperty()`, `Object.defineProperties()`, `Object.freeze()`, + `Object.preventExtensions()` or `Object.seal()`). +- If array destructuring is present, index-like properties in `Array.prototype` + have not been overridden: + ```javascript + Object.prototype[0] = 42; + var [ a ] = []; + var { 0: b } = {}; + // 42 undefined + console.log([][0], a); + // 42 42 + console.log({}[0], b); + ``` +- Earlier versions of JavaScript will throw `SyntaxError` with the following: + ```javascript + ({ + p: 42, + get p() {}, + }); + // SyntaxError: Object literal may not have data and accessor property with + // the same name + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Iteration order of keys over an object which contains spread syntax in later + versions of Chrome and Node.js may be altered. +- When `toplevel` is enabled, UglifyJS effectively assumes input code is wrapped + within `function(){ ... }`, thus forbids aliasing of declared global variables: + ```javascript + A = "FAIL"; + var B = "FAIL"; + // can be `global`, `self`, `window` etc. + var top = function() { + return this; + }(); + // "PASS" + top.A = "PASS"; + console.log(A); + // "FAIL" after compress and/or mangle + top.B = "PASS"; + console.log(B); + ``` +- Use of `arguments` alongside destructuring as function parameters, e.g. + `function({}, arguments) {}` will result in `SyntaxError` in earlier versions + of Chrome and Node.js - UglifyJS may modify the input which in turn may + suppress those errors. +- Earlier versions of Chrome and Node.js will throw `ReferenceError` with the + following: + ```javascript + var a; + try { + throw 42; + } catch ({ + [a]: b, + // ReferenceError: a is not defined + }) { + let a; + } + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Later versions of JavaScript will throw `SyntaxError` with the following: + ```javascript + a => { + let a; + }; + // SyntaxError: Identifier 'a' has already been declared + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Later versions of JavaScript will throw `SyntaxError` with the following: + ```javascript + try { + // ... + } catch ({ message: a }) { + var a; + } + // SyntaxError: Identifier 'a' has already been declared + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Some versions of Chrome and Node.js will throw `ReferenceError` with the + following: + ```javascript + console.log(((a, b = function() { + return a; + // ReferenceError: a is not defined + }()) => b)()); + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Some arithmetic operations with `BigInt` may throw `TypeError`: + ```javascript + 1n + 1; + // TypeError: can't convert BigInt to number + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Some versions of JavaScript will throw `SyntaxError` with the + following: + ```javascript + console.log(String.raw`\uFo`); + // SyntaxError: Invalid Unicode escape sequence + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Some versions of JavaScript will throw `SyntaxError` with the + following: + ```javascript + try {} catch (e) { + for (var e of []); + } + // SyntaxError: Identifier 'e' has already been declared + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Some versions of Chrome and Node.js will give incorrect results with the + following: + ```javascript + console.log({ + ...{ + set 42(v) {}, + 42: "PASS", + }, + }); + // Expected: { '42': 'PASS' } + // Actual: { '42': undefined } + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Later versions of JavaScript will throw `SyntaxError` with the following: + ```javascript + var await; + class A { + static p = await; + } + // SyntaxError: Unexpected reserved word + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Later versions of JavaScript will throw `SyntaxError` with the following: + ```javascript + var async; + for (async of []); + // SyntaxError: The left-hand side of a for-of loop may not be 'async'. + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Some versions of Chrome and Node.js will give incorrect results with the + following: + ```javascript + console.log({ + ...console, + get 42() { + return "FAIL"; + }, + [42]: "PASS", + }[42], { + ...console, + get 42() { + return "FAIL"; + }, + 42: "PASS", + }[42]); + // Expected: "PASS PASS" + // Actual: "PASS FAIL" + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Earlier versions of JavaScript will throw `TypeError` with the following: + ```javascript + (function() { + { + const a = "foo"; + } + { + const a = "bar"; + } + })(); + // TypeError: const 'a' has already been declared + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Later versions of Chrome and Node.js will give incorrect results with the + following: + ```javascript + try { + class A { + static 42; + static get 42() {} + } + console.log("PASS"); + } catch (e) { + console.log("FAIL"); + } + // Expected: "PASS" + // Actual: "FAIL" + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Some versions of Chrome and Node.js will give incorrect results with the + following: + ```javascript + (async function(a) { + (function() { + var b = await => console.log("PASS"); + b(); + })(); + })().catch(console.error); + // Expected: "PASS" + // Actual: SyntaxError: Unexpected reserved word + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Later versions of Chrome and Node.js will give incorrect results with the + following: + ```javascript + try { + f(); + function f() { + throw 42; + } + } catch (e) { + console.log(typeof f, e); + } + // Expected: "function 42" + // Actual: "undefined 42" + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Later versions of JavaScript will throw `SyntaxError` with the following: + ```javascript + "use strict"; + console.log(function f() { + return f = "PASS"; + }()); + // Expected: "PASS" + // Actual: TypeError: invalid assignment to const 'f' + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Adobe ExtendScript will give incorrect results with the following: + ```javascript + alert(true ? "PASS" : false ? "FAIL" : null); + // Expected: "PASS" + // Actual: "FAIL" + ``` + UglifyJS may modify the input which in turn may suppress those errors. +- Adobe ExtendScript will give incorrect results with the following: + ```javascript + alert(42 ? null ? "FAIL" : "PASS" : "FAIL"); + // Expected: "PASS" + // Actual: SyntaxError: Expected: : + ``` + UglifyJS may modify the input which in turn may suppress those errors. diff --git a/node_modules/uglify-js/bin/uglifyjs b/node_modules/uglify-js/bin/uglifyjs new file mode 100755 index 0000000..49e5185 --- /dev/null +++ b/node_modules/uglify-js/bin/uglifyjs @@ -0,0 +1,605 @@ +#! /usr/bin/env node +// -*- js -*- + +"use strict"; + +require("../tools/tty"); + +var fs = require("fs"); +var info = require("../package.json"); +var path = require("path"); +var UglifyJS = require("../tools/node"); + +var skip_keys = [ "cname", "fixed", "in_arg", "inlined", "length_read", "parent_scope", "redef", "scope", "unused" ]; +var truthy_keys = [ "optional", "pure", "terminal", "uses_arguments", "uses_eval", "uses_with" ]; + +var files = {}; +var options = {}; +var short_forms = { + b: "beautify", + c: "compress", + d: "define", + e: "enclose", + h: "help", + m: "mangle", + o: "output", + O: "output-opts", + p: "parse", + v: "version", + V: "version", +}; +var args = process.argv.slice(2); +var paths = []; +var output, nameCache; +var specified = {}; +while (args.length) { + var arg = args.shift(); + if (arg[0] != "-") { + paths.push(arg); + } else if (arg == "--") { + paths = paths.concat(args); + break; + } else if (arg[1] == "-") { + process_option(arg.slice(2)); + } else [].forEach.call(arg.slice(1), function(letter, index, arg) { + if (!(letter in short_forms)) fatal("invalid option -" + letter); + process_option(short_forms[letter], index + 1 < arg.length); + }); +} + +function process_option(name, no_value) { + specified[name] = true; + switch (name) { + case "help": + switch (read_value()) { + case "ast": + print(UglifyJS.describe_ast()); + break; + case "options": + var text = []; + var toplevels = []; + var padding = ""; + var defaults = UglifyJS.default_options(); + for (var name in defaults) { + var option = defaults[name]; + if (option && typeof option == "object") { + text.push("--" + ({ + output: "beautify", + sourceMap: "source-map", + }[name] || name) + " options:"); + text.push(format_object(option)); + text.push(""); + } else { + if (padding.length < name.length) padding = Array(name.length + 1).join(" "); + toplevels.push([ { + keep_fargs: "keep-fargs", + keep_fnames: "keep-fnames", + nameCache: "name-cache", + }[name] || name, option ]); + } + } + toplevels.forEach(function(tokens) { + text.push("--" + tokens[0] + padding.slice(tokens[0].length - 2) + tokens[1]); + }); + print(text.join("\n")); + break; + default: + print([ + "Usage: uglifyjs [files...] [options]", + "", + "Options:", + " -h, --help Print usage information.", + " `--help options` for details on available options.", + " -v, -V, --version Print version number.", + " -p, --parse Specify parser options.", + " -c, --compress [options] Enable compressor/specify compressor options.", + " -m, --mangle [options] Mangle names/specify mangler options.", + " --mangle-props [options] Mangle properties/specify mangler options.", + " -b, --beautify [options] Beautify output/specify output options.", + " -O, --output-opts Output options (beautify disabled).", + " -o, --output Output file (default STDOUT).", + " --annotations Process and preserve comment annotations.", + " --no-annotations Ignore and discard comment annotations.", + " --comments [filter] Preserve copyright comments in the output.", + " --config-file Read minify() options from JSON file.", + " -d, --define [=value] Global definitions.", + " -e, --enclose [arg[,...][:value[,...]]] Embed everything in a big function, with configurable argument(s) & value(s).", + " --expression Parse a single expression, rather than a program.", + " --ie Support non-standard Internet Explorer.", + " --keep-fargs Do not mangle/drop function arguments.", + " --keep-fnames Do not mangle/drop function names. Useful for code relying on Function.prototype.name.", + " --module Process input as ES module (implies --toplevel)", + " --name-cache File to hold mangled name mappings.", + " --rename Force symbol expansion.", + " --no-rename Disable symbol expansion.", + " --self Build UglifyJS as a library (implies --wrap UglifyJS)", + " --source-map [options] Enable source map/specify source map options.", + " --timings Display operations run time on STDERR.", + " --toplevel Compress and/or mangle variables in toplevel scope.", + " --v8 Support non-standard Chrome & Node.js.", + " --validate Perform validation during AST manipulations.", + " --verbose Print diagnostic messages.", + " --warn Print warning messages.", + " --webkit Support non-standard Safari/Webkit.", + " --wrap Embed everything as a function with “exports” corresponding to “name” globally.", + "", + "(internal debug use only)", + " --in-situ Warning: replaces original source files with minified output.", + " --reduce-test Reduce a standalone test case (assumes cloned repository).", + ].join("\n")); + } + process.exit(); + case "version": + print(info.name + " " + info.version); + process.exit(); + case "config-file": + var config = JSON.parse(read_file(read_value(true))); + if (config.mangle && config.mangle.properties && config.mangle.properties.regex) { + config.mangle.properties.regex = UglifyJS.parse(config.mangle.properties.regex, { + expression: true, + }).value; + } + for (var key in config) if (!(key in options)) options[key] = config[key]; + break; + case "compress": + case "mangle": + options[name] = parse_js(read_value(), options[name]); + break; + case "source-map": + options.sourceMap = parse_js(read_value(), options.sourceMap); + break; + case "enclose": + options[name] = read_value(); + break; + case "annotations": + case "expression": + case "ie": + case "ie8": + case "module": + case "timings": + case "toplevel": + case "v8": + case "validate": + case "webkit": + options[name] = true; + break; + case "no-annotations": + options.annotations = false; + break; + case "keep-fargs": + options.keep_fargs = true; + break; + case "keep-fnames": + options.keep_fnames = true; + break; + case "wrap": + options[name] = read_value(true); + break; + case "verbose": + options.warnings = "verbose"; + break; + case "warn": + if (!options.warnings) options.warnings = true; + break; + case "beautify": + options.output = parse_js(read_value(), options.output); + if (!("beautify" in options.output)) options.output.beautify = true; + break; + case "output-opts": + options.output = parse_js(read_value(true), options.output); + break; + case "comments": + if (typeof options.output != "object") options.output = {}; + options.output.comments = read_value(); + if (options.output.comments === true) options.output.comments = "some"; + break; + case "define": + if (typeof options.compress != "object") options.compress = {}; + options.compress.global_defs = parse_js(read_value(true), options.compress.global_defs, "define"); + break; + case "mangle-props": + if (typeof options.mangle != "object") options.mangle = {}; + options.mangle.properties = parse_js(read_value(), options.mangle.properties); + break; + case "name-cache": + nameCache = read_value(true); + options.nameCache = JSON.parse(read_file(nameCache, "{}")); + break; + case "output": + output = read_value(true); + break; + case "parse": + options.parse = parse_js(read_value(true), options.parse); + break; + case "rename": + options.rename = true; + break; + case "no-rename": + options.rename = false; + break; + case "in-situ": + case "reduce-test": + case "self": + break; + default: + fatal("invalid option --" + name); + } + + function read_value(required) { + if (no_value || !args.length || args[0][0] == "-") { + if (required) fatal("missing option argument for --" + name); + return true; + } + return args.shift(); + } +} +if (!output && options.sourceMap && options.sourceMap.url != "inline") fatal("cannot write source map to STDOUT"); +if (specified["beautify"] && specified["output-opts"]) fatal("--beautify cannot be used with --output-opts"); +[ "compress", "mangle" ].forEach(function(name) { + if (!(name in options)) options[name] = false; +}); +if (/^ast|spidermonkey$/.test(output)) { + if (typeof options.output != "object") options.output = {}; + options.output.ast = true; + options.output.code = false; +} +if (options.parse && (options.parse.acorn || options.parse.spidermonkey) + && options.sourceMap && options.sourceMap.content == "inline") { + fatal("inline source map only works with built-in parser"); +} +if (options.warnings) { + UglifyJS.AST_Node.log_function(print_error, options.warnings == "verbose"); + delete options.warnings; +} +var convert_path = function(name) { + return name; +}; +if (typeof options.sourceMap == "object" && "base" in options.sourceMap) { + convert_path = function() { + var base = options.sourceMap.base; + delete options.sourceMap.base; + return function(name) { + return path.relative(base, name); + }; + }(); +} +if (specified["self"]) { + if (paths.length) UglifyJS.AST_Node.warn("Ignoring input files since --self was passed"); + if (!options.wrap) options.wrap = "UglifyJS"; + paths = UglifyJS.FILES; +} else if (paths.length) { + paths = simple_glob(paths); +} +if (specified["in-situ"]) { + if (output && output != "spidermonkey" || specified["reduce-test"] || specified["self"]) { + fatal("incompatible options specified"); + } + paths.forEach(function(name) { + print(name); + if (/^ast|spidermonkey$/.test(name)) fatal("invalid file name specified"); + files = {}; + files[convert_path(name)] = read_file(name); + output = name; + run(); + }); +} else if (paths.length) { + paths.forEach(function(name) { + files[convert_path(name)] = read_file(name); + }); + run(); +} else { + var timerId = process.stdin.isTTY && process.argv.length < 3 && setTimeout(function() { + print_error("Waiting for input... (use `--help` to print usage information)"); + }, 1500); + var chunks = []; + process.stdin.setEncoding("utf8"); + process.stdin.once("data", function() { + clearTimeout(timerId); + }).on("data", function(chunk) { + chunks.push(chunk); + }).on("end", function() { + files = { STDIN: chunks.join("") }; + run(); + }); + process.stdin.resume(); +} + +function convert_ast(fn) { + return UglifyJS.AST_Node.from_mozilla_ast(Object.keys(files).reduce(fn, null)); +} + +function run() { + var content = options.sourceMap && options.sourceMap.content; + if (content && content != "inline") { + UglifyJS.AST_Node.info("Using input source map: {content}", { + content : content, + }); + options.sourceMap.content = read_file(content, content); + } + try { + if (options.parse) { + if (options.parse.acorn) { + var annotations = Object.create(null); + files = convert_ast(function(toplevel, name) { + var content = files[name]; + var list = annotations[name] = []; + var prev = -1; + return require("acorn").parse(content, { + allowHashBang: true, + ecmaVersion: "latest", + locations: true, + onComment: function(block, text, start, end) { + var match = /[@#]__PURE__/.exec(text); + if (!match) { + if (start != prev) return; + match = [ list[prev] ]; + } + while (/\s/.test(content[end])) end++; + list[end] = match[0]; + prev = end; + }, + preserveParens: true, + program: toplevel, + sourceFile: name, + sourceType: "module", + }); + }); + files.walk(new UglifyJS.TreeWalker(function(node) { + if (!(node instanceof UglifyJS.AST_Call)) return; + var list = annotations[node.start.file]; + var pure = list[node.start.pos]; + if (!pure) { + var tokens = node.start.parens; + if (tokens) for (var i = 0; !pure && i < tokens.length; i++) { + pure = list[tokens[i].pos]; + } + } + if (pure) node.pure = pure; + })); + } else if (options.parse.spidermonkey) { + files = convert_ast(function(toplevel, name) { + var obj = JSON.parse(files[name]); + if (!toplevel) return obj; + toplevel.body = toplevel.body.concat(obj.body); + return toplevel; + }); + } + } + } catch (ex) { + fatal(ex); + } + var result; + if (specified["reduce-test"]) { + // load on demand - assumes cloned repository + var reduce_test = require("../test/reduce"); + if (Object.keys(files).length != 1) fatal("can only test on a single file"); + result = reduce_test(files[Object.keys(files)[0]], options, { + log: print_error, + verbose: true, + }); + } else { + result = UglifyJS.minify(files, options); + } + if (result.error) { + var ex = result.error; + if (ex.name == "SyntaxError") { + print_error("Parse error at " + ex.filename + ":" + ex.line + "," + ex.col); + var file = files[ex.filename]; + if (file) { + var col = ex.col; + var lines = file.split(/\r?\n/); + var line = lines[ex.line - 1]; + if (!line && !col) { + line = lines[ex.line - 2]; + col = line.length; + } + if (line) { + var limit = 70; + if (col > limit) { + line = line.slice(col - limit); + col = limit; + } + print_error(line.slice(0, 80)); + print_error(line.slice(0, col).replace(/\S/g, " ") + "^"); + } + } + } else if (ex.defs) { + print_error("Supported options:"); + print_error(format_object(ex.defs)); + } + fatal(ex); + } else if (output == "ast") { + if (!options.compress && !options.mangle) { + var toplevel = result.ast; + if (!(toplevel instanceof UglifyJS.AST_Toplevel)) { + if (!(toplevel instanceof UglifyJS.AST_Statement)) toplevel = new UglifyJS.AST_SimpleStatement({ + body: toplevel, + }); + toplevel = new UglifyJS.AST_Toplevel({ + body: [ toplevel ], + }); + } + toplevel.figure_out_scope({}); + } + print(JSON.stringify(result.ast, function(key, value) { + if (value) switch (key) { + case "enclosed": + return value.length ? value.map(symdef) : undefined; + case "functions": + case "globals": + case "variables": + return value.size() ? value.map(symdef) : undefined; + case "thedef": + return symdef(value); + } + if (skip_property(key, value)) return; + if (value instanceof UglifyJS.AST_Token) return; + if (value instanceof UglifyJS.Dictionary) return; + if (value instanceof UglifyJS.AST_Node) { + var result = { + _class: "AST_" + value.TYPE + }; + value.CTOR.PROPS.forEach(function(prop) { + result[prop] = value[prop]; + }); + return result; + } + return value; + }, 2)); + } else if (output == "spidermonkey") { + print(JSON.stringify(result.ast.to_mozilla_ast(), null, 2)); + } else if (output) { + var code; + if (result.ast) { + var opts = {}; + for (var name in options.output) { + if (!/^ast|code$/.test(name)) opts[name] = options.output[name]; + } + code = UglifyJS.AST_Node.from_mozilla_ast(result.ast.to_mozilla_ast()).print_to_string(opts); + } else { + code = result.code; + } + fs.writeFileSync(output, code); + if (result.map) fs.writeFileSync(output + ".map", result.map); + } else { + print(result.code); + } + if (nameCache) fs.writeFileSync(nameCache, JSON.stringify(options.nameCache)); + if (result.timings) for (var phase in result.timings) { + print_error("- " + phase + ": " + result.timings[phase].toFixed(3) + "s"); + } +} + +function fatal(message) { + if (message instanceof Error) { + message = message.stack.replace(/^\S*?Error:/, "ERROR:") + } else { + message = "ERROR: " + message; + } + print_error(message); + process.exit(1); +} + +// A file glob function that only supports "*" and "?" wildcards in the basename. +// Example: "foo/bar/*baz??.*.js" +// Argument `paths` must be an array of strings. +// Returns an array of strings. Garbage in, garbage out. +function simple_glob(paths) { + return paths.reduce(function(paths, glob) { + if (/\*|\?/.test(glob)) { + var dir = path.dirname(glob); + try { + var entries = fs.readdirSync(dir).filter(function(name) { + try { + return fs.statSync(path.join(dir, name)).isFile(); + } catch (ex) { + return false; + } + }); + } catch (ex) {} + if (entries) { + var pattern = "^" + path.basename(glob) + .replace(/[.+^$[\]\\(){}]/g, "\\$&") + .replace(/\*/g, "[^/\\\\]*") + .replace(/\?/g, "[^/\\\\]") + "$"; + var mod = process.platform === "win32" ? "i" : ""; + var rx = new RegExp(pattern, mod); + var results = entries.filter(function(name) { + return rx.test(name); + }).sort().map(function(name) { + return path.join(dir, name); + }); + if (results.length) { + [].push.apply(paths, results); + return paths; + } + } + } + paths.push(glob); + return paths; + }, []); +} + +function read_file(path, default_value) { + try { + return fs.readFileSync(path, "utf8"); + } catch (ex) { + if (ex.code == "ENOENT" && default_value != null) return default_value; + fatal(ex); + } +} + +function parse_js(value, options, flag) { + if (!options || typeof options != "object") options = Object.create(null); + if (typeof value == "string") try { + UglifyJS.parse(value, { + expression: true + }).walk(new UglifyJS.TreeWalker(function(node) { + if (node instanceof UglifyJS.AST_Assign) { + var name = node.left.print_to_string(); + var value = node.right; + if (flag) { + options[name] = value; + } else if (value instanceof UglifyJS.AST_Array) { + options[name] = value.elements.map(to_string); + } else { + options[name] = to_string(value); + } + return true; + } + if (node instanceof UglifyJS.AST_Symbol || node instanceof UglifyJS.AST_PropAccess) { + var name = node.print_to_string(); + options[name] = true; + return true; + } + if (!(node instanceof UglifyJS.AST_Sequence)) throw node; + + function to_string(value) { + return value instanceof UglifyJS.AST_Constant ? value.value : value.print_to_string({ + quote_keys: true + }); + } + })); + } catch (ex) { + if (flag) { + fatal("cannot parse arguments for '" + flag + "': " + value); + } else { + options[value] = null; + } + } + return options; +} + +function skip_property(key, value) { + return skip_keys.indexOf(key) >= 0 + // only skip truthy_keys if their value is falsy + || truthy_keys.indexOf(key) >= 0 && !value; +} + +function symdef(def) { + var ret = (1e6 + def.id) + " " + def.name; + if (def.mangled_name) ret += " " + def.mangled_name; + return ret; +} + +function format_object(obj) { + var lines = []; + var padding = ""; + Object.keys(obj).map(function(name) { + if (padding.length < name.length) padding = Array(name.length + 1).join(" "); + return [ name, JSON.stringify(obj[name]) ]; + }).forEach(function(tokens) { + lines.push(" " + tokens[0] + padding.slice(tokens[0].length - 2) + tokens[1]); + }); + return lines.join("\n"); +} + +function print_error(msg) { + process.stderr.write(msg); + process.stderr.write("\n"); +} + +function print(txt) { + process.stdout.write(txt); + process.stdout.write("\n"); +} diff --git a/node_modules/uglify-js/lib/ast.js b/node_modules/uglify-js/lib/ast.js new file mode 100644 index 0000000..16ea9c8 --- /dev/null +++ b/node_modules/uglify-js/lib/ast.js @@ -0,0 +1,2356 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function DEFNODE(type, props, methods, base) { + if (typeof base === "undefined") base = AST_Node; + props = props ? props.split(/\s+/) : []; + var self_props = props; + if (base && base.PROPS) props = props.concat(base.PROPS); + var code = [ + "return function AST_", type, "(props){", + // not essential, but speeds up compress by a few percent + "this._bits=0;", + "if(props){", + ]; + props.forEach(function(prop) { + code.push("this.", prop, "=props.", prop, ";"); + }); + code.push("}"); + var proto = Object.create(base && base.prototype); + if (methods.initialize || proto.initialize) code.push("this.initialize();"); + code.push("};"); + var ctor = new Function(code.join(""))(); + ctor.prototype = proto; + ctor.prototype.CTOR = ctor; + ctor.prototype.TYPE = ctor.TYPE = type; + if (base) { + ctor.BASE = base; + base.SUBCLASSES.push(ctor); + } + ctor.DEFMETHOD = function(name, method) { + this.prototype[name] = method; + }; + ctor.PROPS = props; + ctor.SELF_PROPS = self_props; + ctor.SUBCLASSES = []; + for (var name in methods) if (HOP(methods, name)) { + if (/^\$/.test(name)) { + ctor[name.substr(1)] = methods[name]; + } else { + ctor.DEFMETHOD(name, methods[name]); + } + } + if (typeof exports !== "undefined") exports["AST_" + type] = ctor; + return ctor; +} + +var AST_Token = DEFNODE("Token", "type value line col pos endline endcol endpos nlb comments_before comments_after file raw", { +}, null); + +var AST_Node = DEFNODE("Node", "start end", { + _clone: function(deep) { + if (deep) { + var self = this.clone(); + return self.transform(new TreeTransformer(function(node) { + if (node !== self) { + return node.clone(true); + } + })); + } + return new this.CTOR(this); + }, + clone: function(deep) { + return this._clone(deep); + }, + $documentation: "Base class of all AST nodes", + $propdoc: { + start: "[AST_Token] The first token of this node", + end: "[AST_Token] The last token of this node" + }, + equals: function(node) { + return this.TYPE == node.TYPE && this._equals(node); + }, + walk: function(visitor) { + visitor.visit(this); + }, + _validate: function() { + if (this.TYPE == "Node") throw new Error("should not instantiate AST_Node"); + }, + validate: function() { + var ctor = this.CTOR; + do { + ctor.prototype._validate.call(this); + } while (ctor = ctor.BASE); + }, + validate_ast: function() { + var marker = {}; + this.walk(new TreeWalker(function(node) { + if (node.validate_visited === marker) { + throw new Error(string_template("cannot reuse AST_{TYPE} from [{start}]", node)); + } + node.validate_visited = marker; + })); + }, +}, null); + +DEF_BITPROPS(AST_Node, [ + // AST_Node + "_optimized", + "_squeezed", + // AST_Call + "call_only", + // AST_Lambda + "collapse_scanning", + // AST_SymbolRef + "defined", + "evaluating", + "falsy", + // AST_SymbolRef + "in_arg", + // AST_Return + "in_bool", + // AST_SymbolRef + "is_undefined", + // AST_LambdaExpression + // AST_LambdaDefinition + "inlined", + // AST_Lambda + "length_read", + // AST_Yield + "nested", + // AST_Lambda + "new", + // AST_Call + // AST_PropAccess + "optional", + // AST_ClassProperty + "private", + // AST_Call + "pure", + // AST_Assign + "redundant", + // AST_Node + "single_use", + // AST_ClassProperty + "static", + // AST_Call + // AST_PropAccess + "terminal", + "truthy", + // AST_Scope + "uses_eval", + // AST_Scope + "uses_with", +]); + +(AST_Node.log_function = function(fn, verbose) { + if (typeof fn != "function") { + AST_Node.info = AST_Node.warn = noop; + return; + } + var printed = Object.create(null); + AST_Node.info = verbose ? function(text, props) { + log("INFO: " + string_template(text, props)); + } : noop; + AST_Node.warn = function(text, props) { + log("WARN: " + string_template(text, props)); + }; + + function log(msg) { + if (printed[msg]) return; + printed[msg] = true; + fn(msg); + } +})(); + +var restore_transforms = []; +AST_Node.enable_validation = function() { + AST_Node.disable_validation(); + (function validate_transform(ctor) { + ctor.SUBCLASSES.forEach(validate_transform); + if (!HOP(ctor.prototype, "transform")) return; + var transform = ctor.prototype.transform; + ctor.prototype.transform = function(tw, in_list) { + var node = transform.call(this, tw, in_list); + if (node instanceof AST_Node) { + node.validate(); + } else if (!(node === null || in_list && List.is_op(node))) { + throw new Error("invalid transformed value: " + node); + } + return node; + }; + restore_transforms.push(function() { + ctor.prototype.transform = transform; + }); + })(this); +}; + +AST_Node.disable_validation = function() { + var restore; + while (restore = restore_transforms.pop()) restore(); +}; + +function all_equals(k, l) { + return k.length == l.length && all(k, function(m, i) { + return m.equals(l[i]); + }); +} + +function list_equals(s, t) { + return s.length == t.length && all(s, function(u, i) { + return u == t[i]; + }); +} + +function prop_equals(u, v) { + if (u === v) return true; + if (u == null) return v == null; + return u instanceof AST_Node && v instanceof AST_Node && u.equals(v); +} + +/* -----[ statements ]----- */ + +var AST_Statement = DEFNODE("Statement", null, { + $documentation: "Base class of all statements", + _validate: function() { + if (this.TYPE == "Statement") throw new Error("should not instantiate AST_Statement"); + }, +}); + +var AST_Debugger = DEFNODE("Debugger", null, { + $documentation: "Represents a debugger statement", + _equals: return_true, +}, AST_Statement); + +var AST_Directive = DEFNODE("Directive", "quote value", { + $documentation: "Represents a directive, like \"use strict\";", + $propdoc: { + quote: "[string?] the original quote character", + value: "[string] The value of this directive as a plain string (it's not an AST_String!)", + }, + _equals: function(node) { + return this.value == node.value; + }, + _validate: function() { + if (this.quote != null) { + if (typeof this.quote != "string") throw new Error("quote must be string"); + if (!/^["']$/.test(this.quote)) throw new Error("invalid quote: " + this.quote); + } + if (typeof this.value != "string") throw new Error("value must be string"); + }, +}, AST_Statement); + +var AST_EmptyStatement = DEFNODE("EmptyStatement", null, { + $documentation: "The empty statement (empty block or simply a semicolon)", + _equals: return_true, +}, AST_Statement); + +function is_statement(node) { + return node instanceof AST_Statement + && !(node instanceof AST_ClassExpression) + && !(node instanceof AST_LambdaExpression); +} + +function validate_expression(value, prop, multiple, allow_spread, allow_hole) { + multiple = multiple ? "contain" : "be"; + if (!(value instanceof AST_Node)) throw new Error(prop + " must " + multiple + " AST_Node"); + if (value instanceof AST_DefaultValue) throw new Error(prop + " cannot " + multiple + " AST_DefaultValue"); + if (value instanceof AST_Destructured) throw new Error(prop + " cannot " + multiple + " AST_Destructured"); + if (value instanceof AST_Hole && !allow_hole) throw new Error(prop + " cannot " + multiple + " AST_Hole"); + if (value instanceof AST_Spread && !allow_spread) throw new Error(prop + " cannot " + multiple + " AST_Spread"); + if (is_statement(value)) throw new Error(prop + " cannot " + multiple + " AST_Statement"); + if (value instanceof AST_SymbolDeclaration) { + throw new Error(prop + " cannot " + multiple + " AST_SymbolDeclaration"); + } +} + +function must_be_expression(node, prop) { + validate_expression(node[prop], prop); +} + +var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", { + $documentation: "A statement consisting of an expression, i.e. a = 1 + 2", + $propdoc: { + body: "[AST_Node] an expression node (should not be instanceof AST_Statement)", + }, + _equals: function(node) { + return this.body.equals(node.body); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.body.walk(visitor); + }); + }, + _validate: function() { + must_be_expression(this, "body"); + }, +}, AST_Statement); + +var AST_BlockScope = DEFNODE("BlockScope", "_var_names enclosed functions make_def parent_scope variables", { + $documentation: "Base class for all statements introducing a lexical scope", + $propdoc: { + enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any inner scopes", + functions: "[Dictionary/S] like `variables`, but only lists function declarations", + parent_scope: "[AST_Scope?/S] link to the parent scope", + variables: "[Dictionary/S] a map of name ---> SymbolDef for all variables/functions defined in this scope", + }, + clone: function(deep) { + var node = this._clone(deep); + if (this.enclosed) node.enclosed = this.enclosed.slice(); + if (this.functions) node.functions = this.functions.clone(); + if (this.variables) node.variables = this.variables.clone(); + return node; + }, + pinned: function() { + return this.resolve().pinned(); + }, + resolve: function() { + return this.parent_scope.resolve(); + }, + _validate: function() { + if (this.TYPE == "BlockScope") throw new Error("should not instantiate AST_BlockScope"); + if (this.parent_scope == null) return; + if (!(this.parent_scope instanceof AST_BlockScope)) throw new Error("parent_scope must be AST_BlockScope"); + if (!(this.resolve() instanceof AST_Scope)) throw new Error("must be contained within AST_Scope"); + }, +}, AST_Statement); + +function walk_body(node, visitor) { + node.body.forEach(function(node) { + node.walk(visitor); + }); +} + +var AST_Block = DEFNODE("Block", "body", { + $documentation: "A body of statements (usually braced)", + $propdoc: { + body: "[AST_Statement*] an array of statements" + }, + _equals: function(node) { + return all_equals(this.body, node.body); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + walk_body(node, visitor); + }); + }, + _validate: function() { + if (this.TYPE == "Block") throw new Error("should not instantiate AST_Block"); + this.body.forEach(function(node) { + if (!is_statement(node)) throw new Error("body must contain AST_Statement"); + }); + }, +}, AST_BlockScope); + +var AST_BlockStatement = DEFNODE("BlockStatement", null, { + $documentation: "A block statement", +}, AST_Block); + +var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", { + $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`", + $propdoc: { + body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement" + }, + _validate: function() { + if (this.TYPE == "StatementWithBody") throw new Error("should not instantiate AST_StatementWithBody"); + if (!is_statement(this.body)) throw new Error("body must be AST_Statement"); + }, +}, AST_BlockScope); + +var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", { + $documentation: "Statement with a label", + $propdoc: { + label: "[AST_Label] a label definition" + }, + _equals: function(node) { + return this.label.equals(node.label) + && this.body.equals(node.body); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.label.walk(visitor); + node.body.walk(visitor); + }); + }, + clone: function(deep) { + var node = this._clone(deep); + if (deep) { + var label = node.label; + var def = this.label; + node.walk(new TreeWalker(function(node) { + if (node instanceof AST_LoopControl) { + if (!node.label || node.label.thedef !== def) return; + node.label.thedef = label; + label.references.push(node); + return true; + } + if (node instanceof AST_Scope) return true; + })); + } + return node; + }, + _validate: function() { + if (!(this.label instanceof AST_Label)) throw new Error("label must be AST_Label"); + }, +}, AST_StatementWithBody); + +var AST_IterationStatement = DEFNODE("IterationStatement", null, { + $documentation: "Internal class. All loops inherit from it.", + _validate: function() { + if (this.TYPE == "IterationStatement") throw new Error("should not instantiate AST_IterationStatement"); + }, +}, AST_StatementWithBody); + +var AST_DWLoop = DEFNODE("DWLoop", "condition", { + $documentation: "Base class for do/while statements", + $propdoc: { + condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement" + }, + _equals: function(node) { + return this.body.equals(node.body) + && this.condition.equals(node.condition); + }, + _validate: function() { + if (this.TYPE == "DWLoop") throw new Error("should not instantiate AST_DWLoop"); + must_be_expression(this, "condition"); + }, +}, AST_IterationStatement); + +var AST_Do = DEFNODE("Do", null, { + $documentation: "A `do` statement", + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.body.walk(visitor); + node.condition.walk(visitor); + }); + }, +}, AST_DWLoop); + +var AST_While = DEFNODE("While", null, { + $documentation: "A `while` statement", + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.condition.walk(visitor); + node.body.walk(visitor); + }); + }, +}, AST_DWLoop); + +var AST_For = DEFNODE("For", "init condition step", { + $documentation: "A `for` statement", + $propdoc: { + init: "[AST_Node?] the `for` initialization code, or null if empty", + condition: "[AST_Node?] the `for` termination clause, or null if empty", + step: "[AST_Node?] the `for` update clause, or null if empty" + }, + _equals: function(node) { + return prop_equals(this.init, node.init) + && prop_equals(this.condition, node.condition) + && prop_equals(this.step, node.step) + && this.body.equals(node.body); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + if (node.init) node.init.walk(visitor); + if (node.condition) node.condition.walk(visitor); + if (node.step) node.step.walk(visitor); + node.body.walk(visitor); + }); + }, + _validate: function() { + if (this.init != null) { + if (!(this.init instanceof AST_Node)) throw new Error("init must be AST_Node"); + if (is_statement(this.init) && !(this.init instanceof AST_Definitions)) { + throw new Error("init cannot be AST_Statement"); + } + } + if (this.condition != null) must_be_expression(this, "condition"); + if (this.step != null) must_be_expression(this, "step"); + }, +}, AST_IterationStatement); + +var AST_ForEnumeration = DEFNODE("ForEnumeration", "init object", { + $documentation: "Base class for enumeration loops, i.e. `for ... in`, `for ... of` & `for await ... of`", + $propdoc: { + init: "[AST_Node] the assignment target during iteration", + object: "[AST_Node] the object to iterate over" + }, + _equals: function(node) { + return this.init.equals(node.init) + && this.object.equals(node.object) + && this.body.equals(node.body); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.init.walk(visitor); + node.object.walk(visitor); + node.body.walk(visitor); + }); + }, + _validate: function() { + if (this.TYPE == "ForEnumeration") throw new Error("should not instantiate AST_ForEnumeration"); + if (this.init instanceof AST_Definitions) { + if (this.init.definitions.length != 1) throw new Error("init must have single declaration"); + } else { + validate_destructured(this.init, function(node) { + if (!(node instanceof AST_PropAccess || node instanceof AST_SymbolRef)) { + throw new Error("init must be assignable: " + node.TYPE); + } + }); + } + must_be_expression(this, "object"); + }, +}, AST_IterationStatement); + +var AST_ForIn = DEFNODE("ForIn", null, { + $documentation: "A `for ... in` statement", +}, AST_ForEnumeration); + +var AST_ForOf = DEFNODE("ForOf", null, { + $documentation: "A `for ... of` statement", +}, AST_ForEnumeration); + +var AST_ForAwaitOf = DEFNODE("ForAwaitOf", null, { + $documentation: "A `for await ... of` statement", +}, AST_ForOf); + +var AST_With = DEFNODE("With", "expression", { + $documentation: "A `with` statement", + $propdoc: { + expression: "[AST_Node] the `with` expression" + }, + _equals: function(node) { + return this.expression.equals(node.expression) + && this.body.equals(node.body); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.expression.walk(visitor); + node.body.walk(visitor); + }); + }, + _validate: function() { + must_be_expression(this, "expression"); + }, +}, AST_StatementWithBody); + +/* -----[ scope and functions ]----- */ + +var AST_Scope = DEFNODE("Scope", "fn_defs may_call_this uses_eval uses_with", { + $documentation: "Base class for all statements introducing a lambda scope", + $propdoc: { + uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`", + uses_with: "[boolean/S] tells whether this scope uses the `with` statement", + }, + pinned: function() { + return this.uses_eval || this.uses_with; + }, + resolve: return_this, + _validate: function() { + if (this.TYPE == "Scope") throw new Error("should not instantiate AST_Scope"); + }, +}, AST_Block); + +var AST_Toplevel = DEFNODE("Toplevel", "globals", { + $documentation: "The toplevel scope", + $propdoc: { + globals: "[Dictionary/S] a map of name ---> SymbolDef for all undeclared names", + }, + wrap: function(name) { + var body = this.body; + return parse([ + "(function(exports){'$ORIG';})(typeof ", + name, + "=='undefined'?(", + name, + "={}):", + name, + ");" + ].join(""), { + filename: "wrap=" + JSON.stringify(name) + }).transform(new TreeTransformer(function(node) { + if (node instanceof AST_Directive && node.value == "$ORIG") { + return List.splice(body); + } + })); + }, + enclose: function(args_values) { + if (typeof args_values != "string") args_values = ""; + var index = args_values.indexOf(":"); + if (index < 0) index = args_values.length; + var body = this.body; + return parse([ + "(function(", + args_values.slice(0, index), + '){"$ORIG"})(', + args_values.slice(index + 1), + ")" + ].join(""), { + filename: "enclose=" + JSON.stringify(args_values) + }).transform(new TreeTransformer(function(node) { + if (node instanceof AST_Directive && node.value == "$ORIG") { + return List.splice(body); + } + })); + } +}, AST_Scope); + +var AST_ClassInitBlock = DEFNODE("ClassInitBlock", null, { + $documentation: "Value for `class` static initialization blocks", +}, AST_Scope); + +var AST_Lambda = DEFNODE("Lambda", "argnames length_read rest safe_ids uses_arguments", { + $documentation: "Base class for functions", + $propdoc: { + argnames: "[(AST_DefaultValue|AST_Destructured|AST_SymbolFunarg)*] array of function arguments and/or destructured literals", + length_read: "[boolean/S] whether length property of this function is accessed", + rest: "[(AST_Destructured|AST_SymbolFunarg)?] rest parameter, or null if absent", + uses_arguments: "[boolean|number/S] whether this function accesses the arguments array", + }, + each_argname: function(visit) { + var tw = new TreeWalker(function(node) { + if (node instanceof AST_DefaultValue) { + node.name.walk(tw); + return true; + } + if (node instanceof AST_DestructuredKeyVal) { + node.value.walk(tw); + return true; + } + if (node instanceof AST_SymbolFunarg) visit(node); + }); + this.argnames.forEach(function(argname) { + argname.walk(tw); + }); + if (this.rest) this.rest.walk(tw); + }, + _equals: function(node) { + return prop_equals(this.rest, node.rest) + && prop_equals(this.name, node.name) + && prop_equals(this.value, node.value) + && all_equals(this.argnames, node.argnames) + && all_equals(this.body, node.body); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + if (node.name) node.name.walk(visitor); + node.argnames.forEach(function(argname) { + argname.walk(visitor); + }); + if (node.rest) node.rest.walk(visitor); + walk_body(node, visitor); + }); + }, + _validate: function() { + if (this.TYPE == "Lambda") throw new Error("should not instantiate AST_Lambda"); + this.argnames.forEach(function(node) { + validate_destructured(node, function(node) { + if (!(node instanceof AST_SymbolFunarg)) throw new Error("argnames must be AST_SymbolFunarg[]"); + }, true); + }); + if (this.rest != null) validate_destructured(this.rest, function(node) { + if (!(node instanceof AST_SymbolFunarg)) throw new Error("rest must be AST_SymbolFunarg"); + }); + }, +}, AST_Scope); + +var AST_Accessor = DEFNODE("Accessor", null, { + $documentation: "A getter/setter function", + _validate: function() { + if (this.name != null) throw new Error("name must be null"); + }, +}, AST_Lambda); + +var AST_LambdaExpression = DEFNODE("LambdaExpression", "inlined", { + $documentation: "Base class for function expressions", + $propdoc: { + inlined: "[boolean/S] whether this function has been inlined", + }, + _validate: function() { + if (this.TYPE == "LambdaExpression") throw new Error("should not instantiate AST_LambdaExpression"); + }, +}, AST_Lambda); + +function is_arrow(node) { + return node instanceof AST_Arrow || node instanceof AST_AsyncArrow; +} + +function is_async(node) { + return node instanceof AST_AsyncArrow + || node instanceof AST_AsyncDefun + || node instanceof AST_AsyncFunction + || node instanceof AST_AsyncGeneratorDefun + || node instanceof AST_AsyncGeneratorFunction; +} + +function is_generator(node) { + return node instanceof AST_AsyncGeneratorDefun + || node instanceof AST_AsyncGeneratorFunction + || node instanceof AST_GeneratorDefun + || node instanceof AST_GeneratorFunction; +} + +function walk_lambda(node, tw) { + if (is_arrow(node) && node.value) { + node.value.walk(tw); + } else { + walk_body(node, tw); + } +} + +var AST_Arrow = DEFNODE("Arrow", "value", { + $documentation: "An arrow function expression", + $propdoc: { + value: "[AST_Node?] simple return expression, or null if using function body.", + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.argnames.forEach(function(argname) { + argname.walk(visitor); + }); + if (node.rest) node.rest.walk(visitor); + if (node.value) { + node.value.walk(visitor); + } else { + walk_body(node, visitor); + } + }); + }, + _validate: function() { + if (this.name != null) throw new Error("name must be null"); + if (this.uses_arguments) throw new Error("uses_arguments must be false"); + if (this.value != null) { + must_be_expression(this, "value"); + if (this.body.length) throw new Error("body must be empty if value exists"); + } + }, +}, AST_LambdaExpression); + +var AST_AsyncArrow = DEFNODE("AsyncArrow", "value", { + $documentation: "An asynchronous arrow function expression", + $propdoc: { + value: "[AST_Node?] simple return expression, or null if using function body.", + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.argnames.forEach(function(argname) { + argname.walk(visitor); + }); + if (node.rest) node.rest.walk(visitor); + if (node.value) { + node.value.walk(visitor); + } else { + walk_body(node, visitor); + } + }); + }, + _validate: function() { + if (this.name != null) throw new Error("name must be null"); + if (this.uses_arguments) throw new Error("uses_arguments must be false"); + if (this.value != null) { + must_be_expression(this, "value"); + if (this.body.length) throw new Error("body must be empty if value exists"); + } + }, +}, AST_LambdaExpression); + +var AST_AsyncFunction = DEFNODE("AsyncFunction", "name", { + $documentation: "An asynchronous function expression", + $propdoc: { + name: "[AST_SymbolLambda?] the name of this function, or null if not specified", + }, + _validate: function() { + if (this.name != null) { + if (!(this.name instanceof AST_SymbolLambda)) throw new Error("name must be AST_SymbolLambda"); + } + }, +}, AST_LambdaExpression); + +var AST_AsyncGeneratorFunction = DEFNODE("AsyncGeneratorFunction", "name", { + $documentation: "An asynchronous generator function expression", + $propdoc: { + name: "[AST_SymbolLambda?] the name of this function, or null if not specified", + }, + _validate: function() { + if (this.name != null) { + if (!(this.name instanceof AST_SymbolLambda)) throw new Error("name must be AST_SymbolLambda"); + } + }, +}, AST_LambdaExpression); + +var AST_Function = DEFNODE("Function", "name", { + $documentation: "A function expression", + $propdoc: { + name: "[AST_SymbolLambda?] the name of this function, or null if not specified", + }, + _validate: function() { + if (this.name != null) { + if (!(this.name instanceof AST_SymbolLambda)) throw new Error("name must be AST_SymbolLambda"); + } + }, +}, AST_LambdaExpression); + +var AST_GeneratorFunction = DEFNODE("GeneratorFunction", "name", { + $documentation: "A generator function expression", + $propdoc: { + name: "[AST_SymbolLambda?] the name of this function, or null if not specified", + }, + _validate: function() { + if (this.name != null) { + if (!(this.name instanceof AST_SymbolLambda)) throw new Error("name must be AST_SymbolLambda"); + } + }, +}, AST_LambdaExpression); + +var AST_LambdaDefinition = DEFNODE("LambdaDefinition", "inlined name", { + $documentation: "Base class for function definitions", + $propdoc: { + inlined: "[boolean/S] whether this function has been inlined", + name: "[AST_SymbolDefun] the name of this function", + }, + _validate: function() { + if (this.TYPE == "LambdaDefinition") throw new Error("should not instantiate AST_LambdaDefinition"); + if (!(this.name instanceof AST_SymbolDefun)) throw new Error("name must be AST_SymbolDefun"); + }, +}, AST_Lambda); + +var AST_AsyncDefun = DEFNODE("AsyncDefun", null, { + $documentation: "An asynchronous function definition", +}, AST_LambdaDefinition); + +var AST_AsyncGeneratorDefun = DEFNODE("AsyncGeneratorDefun", null, { + $documentation: "An asynchronous generator function definition", +}, AST_LambdaDefinition); + +var AST_Defun = DEFNODE("Defun", null, { + $documentation: "A function definition", +}, AST_LambdaDefinition); + +var AST_GeneratorDefun = DEFNODE("GeneratorDefun", null, { + $documentation: "A generator function definition", +}, AST_LambdaDefinition); + +/* -----[ classes ]----- */ + +var AST_Class = DEFNODE("Class", "extends name properties", { + $documentation: "Base class for class literals", + $propdoc: { + extends: "[AST_Node?] the super class, or null if not specified", + properties: "[AST_ClassProperty*] array of class properties", + }, + _equals: function(node) { + return prop_equals(this.name, node.name) + && prop_equals(this.extends, node.extends) + && all_equals(this.properties, node.properties); + }, + resolve: function(def_class) { + return def_class ? this : this.parent_scope.resolve(); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + if (node.name) node.name.walk(visitor); + if (node.extends) node.extends.walk(visitor); + node.properties.forEach(function(prop) { + prop.walk(visitor); + }); + }); + }, + _validate: function() { + if (this.TYPE == "Class") throw new Error("should not instantiate AST_Class"); + if (this.extends != null) must_be_expression(this, "extends"); + this.properties.forEach(function(node) { + if (!(node instanceof AST_ClassProperty)) throw new Error("properties must contain AST_ClassProperty"); + }); + }, +}, AST_BlockScope); + +var AST_DefClass = DEFNODE("DefClass", null, { + $documentation: "A class definition", + $propdoc: { + name: "[AST_SymbolDefClass] the name of this class", + }, + _validate: function() { + if (!(this.name instanceof AST_SymbolDefClass)) throw new Error("name must be AST_SymbolDefClass"); + }, +}, AST_Class); + +var AST_ClassExpression = DEFNODE("ClassExpression", null, { + $documentation: "A class expression", + $propdoc: { + name: "[AST_SymbolClass?] the name of this class, or null if not specified", + }, + _validate: function() { + if (this.name != null) { + if (!(this.name instanceof AST_SymbolClass)) throw new Error("name must be AST_SymbolClass"); + } + }, +}, AST_Class); + +var AST_ClassProperty = DEFNODE("ClassProperty", "key private static value", { + $documentation: "Base class for `class` properties", + $propdoc: { + key: "[string|AST_Node?] property name (AST_Node for computed property, null for initialization block)", + private: "[boolean] whether this is a private property", + static: "[boolean] whether this is a static property", + value: "[AST_Node?] property value (AST_Accessor for getters/setters, AST_LambdaExpression for methods, null if not specified for fields)", + }, + _equals: function(node) { + return !this.private == !node.private + && !this.static == !node.static + && prop_equals(this.key, node.key) + && prop_equals(this.value, node.value); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + if (node.key instanceof AST_Node) node.key.walk(visitor); + if (node.value) node.value.walk(visitor); + }); + }, + _validate: function() { + if (this.TYPE == "ClassProperty") throw new Error("should not instantiate AST_ClassProperty"); + if (this instanceof AST_ClassInit) { + if (this.key != null) throw new Error("key must be null"); + } else if (typeof this.key != "string") { + if (!(this.key instanceof AST_Node)) throw new Error("key must be string or AST_Node"); + must_be_expression(this, "key"); + } + if(this.value != null) { + if (!(this.value instanceof AST_Node)) throw new Error("value must be AST_Node"); + } + }, +}); + +var AST_ClassField = DEFNODE("ClassField", null, { + $documentation: "A `class` field", + _validate: function() { + if(this.value != null) must_be_expression(this, "value"); + }, +}, AST_ClassProperty); + +var AST_ClassGetter = DEFNODE("ClassGetter", null, { + $documentation: "A `class` getter", + _validate: function() { + if (!(this.value instanceof AST_Accessor)) throw new Error("value must be AST_Accessor"); + }, +}, AST_ClassProperty); + +var AST_ClassSetter = DEFNODE("ClassSetter", null, { + $documentation: "A `class` setter", + _validate: function() { + if (!(this.value instanceof AST_Accessor)) throw new Error("value must be AST_Accessor"); + }, +}, AST_ClassProperty); + +var AST_ClassMethod = DEFNODE("ClassMethod", null, { + $documentation: "A `class` method", + _validate: function() { + if (!(this.value instanceof AST_LambdaExpression)) throw new Error("value must be AST_LambdaExpression"); + if (is_arrow(this.value)) throw new Error("value cannot be AST_Arrow or AST_AsyncArrow"); + if (this.value.name != null) throw new Error("name of class method's lambda must be null"); + }, +}, AST_ClassProperty); + +var AST_ClassInit = DEFNODE("ClassInit", null, { + $documentation: "A `class` static initialization block", + _validate: function() { + if (!this.static) throw new Error("static must be true"); + if (!(this.value instanceof AST_ClassInitBlock)) throw new Error("value must be AST_ClassInitBlock"); + }, + initialize: function() { + this.static = true; + }, +}, AST_ClassProperty); + +/* -----[ JUMPS ]----- */ + +var AST_Jump = DEFNODE("Jump", null, { + $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)", + _validate: function() { + if (this.TYPE == "Jump") throw new Error("should not instantiate AST_Jump"); + }, +}, AST_Statement); + +var AST_Exit = DEFNODE("Exit", "value", { + $documentation: "Base class for “exits” (`return` and `throw`)", + $propdoc: { + value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return" + }, + _equals: function(node) { + return prop_equals(this.value, node.value); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + if (node.value) node.value.walk(visitor); + }); + }, + _validate: function() { + if (this.TYPE == "Exit") throw new Error("should not instantiate AST_Exit"); + }, +}, AST_Jump); + +var AST_Return = DEFNODE("Return", null, { + $documentation: "A `return` statement", + _validate: function() { + if (this.value != null) must_be_expression(this, "value"); + }, +}, AST_Exit); + +var AST_Throw = DEFNODE("Throw", null, { + $documentation: "A `throw` statement", + _validate: function() { + must_be_expression(this, "value"); + }, +}, AST_Exit); + +var AST_LoopControl = DEFNODE("LoopControl", "label", { + $documentation: "Base class for loop control statements (`break` and `continue`)", + $propdoc: { + label: "[AST_LabelRef?] the label, or null if none", + }, + _equals: function(node) { + return prop_equals(this.label, node.label); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + if (node.label) node.label.walk(visitor); + }); + }, + _validate: function() { + if (this.TYPE == "LoopControl") throw new Error("should not instantiate AST_LoopControl"); + if (this.label != null) { + if (!(this.label instanceof AST_LabelRef)) throw new Error("label must be AST_LabelRef"); + } + }, +}, AST_Jump); + +var AST_Break = DEFNODE("Break", null, { + $documentation: "A `break` statement" +}, AST_LoopControl); + +var AST_Continue = DEFNODE("Continue", null, { + $documentation: "A `continue` statement" +}, AST_LoopControl); + +/* -----[ IF ]----- */ + +var AST_If = DEFNODE("If", "condition alternative", { + $documentation: "A `if` statement", + $propdoc: { + condition: "[AST_Node] the `if` condition", + alternative: "[AST_Statement?] the `else` part, or null if not present" + }, + _equals: function(node) { + return this.body.equals(node.body) + && this.condition.equals(node.condition) + && prop_equals(this.alternative, node.alternative); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.condition.walk(visitor); + node.body.walk(visitor); + if (node.alternative) node.alternative.walk(visitor); + }); + }, + _validate: function() { + must_be_expression(this, "condition"); + if (this.alternative != null) { + if (!is_statement(this.alternative)) throw new Error("alternative must be AST_Statement"); + } + }, +}, AST_StatementWithBody); + +/* -----[ SWITCH ]----- */ + +var AST_Switch = DEFNODE("Switch", "expression", { + $documentation: "A `switch` statement", + $propdoc: { + expression: "[AST_Node] the `switch` “discriminant”" + }, + _equals: function(node) { + return this.expression.equals(node.expression) + && all_equals(this.body, node.body); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.expression.walk(visitor); + walk_body(node, visitor); + }); + }, + _validate: function() { + must_be_expression(this, "expression"); + this.body.forEach(function(node) { + if (!(node instanceof AST_SwitchBranch)) throw new Error("body must be AST_SwitchBranch[]"); + }); + }, +}, AST_Block); + +var AST_SwitchBranch = DEFNODE("SwitchBranch", null, { + $documentation: "Base class for `switch` branches", + _validate: function() { + if (this.TYPE == "SwitchBranch") throw new Error("should not instantiate AST_SwitchBranch"); + }, +}, AST_Block); + +var AST_Default = DEFNODE("Default", null, { + $documentation: "A `default` switch branch", +}, AST_SwitchBranch); + +var AST_Case = DEFNODE("Case", "expression", { + $documentation: "A `case` switch branch", + $propdoc: { + expression: "[AST_Node] the `case` expression" + }, + _equals: function(node) { + return this.expression.equals(node.expression) + && all_equals(this.body, node.body); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.expression.walk(visitor); + walk_body(node, visitor); + }); + }, + _validate: function() { + must_be_expression(this, "expression"); + }, +}, AST_SwitchBranch); + +/* -----[ EXCEPTIONS ]----- */ + +var AST_Try = DEFNODE("Try", "bcatch bfinally", { + $documentation: "A `try` statement", + $propdoc: { + bcatch: "[AST_Catch?] the catch block, or null if not present", + bfinally: "[AST_Finally?] the finally block, or null if not present" + }, + _equals: function(node) { + return all_equals(this.body, node.body) + && prop_equals(this.bcatch, node.bcatch) + && prop_equals(this.bfinally, node.bfinally); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + walk_body(node, visitor); + if (node.bcatch) node.bcatch.walk(visitor); + if (node.bfinally) node.bfinally.walk(visitor); + }); + }, + _validate: function() { + if (this.bcatch != null) { + if (!(this.bcatch instanceof AST_Catch)) throw new Error("bcatch must be AST_Catch"); + } + if (this.bfinally != null) { + if (!(this.bfinally instanceof AST_Finally)) throw new Error("bfinally must be AST_Finally"); + } + }, +}, AST_Block); + +var AST_Catch = DEFNODE("Catch", "argname", { + $documentation: "A `catch` node; only makes sense as part of a `try` statement", + $propdoc: { + argname: "[(AST_Destructured|AST_SymbolCatch)?] symbol for the exception, or null if not present", + }, + _equals: function(node) { + return prop_equals(this.argname, node.argname) + && all_equals(this.body, node.body); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + if (node.argname) node.argname.walk(visitor); + walk_body(node, visitor); + }); + }, + _validate: function() { + if (this.argname != null) validate_destructured(this.argname, function(node) { + if (!(node instanceof AST_SymbolCatch)) throw new Error("argname must be AST_SymbolCatch"); + }); + }, +}, AST_Block); + +var AST_Finally = DEFNODE("Finally", null, { + $documentation: "A `finally` node; only makes sense as part of a `try` statement" +}, AST_Block); + +/* -----[ VAR ]----- */ + +var AST_Definitions = DEFNODE("Definitions", "definitions", { + $documentation: "Base class for `var` nodes (variable declarations/initializations)", + $propdoc: { + definitions: "[AST_VarDef*] array of variable definitions" + }, + _equals: function(node) { + return all_equals(this.definitions, node.definitions); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.definitions.forEach(function(defn) { + defn.walk(visitor); + }); + }); + }, + _validate: function() { + if (this.TYPE == "Definitions") throw new Error("should not instantiate AST_Definitions"); + if (this.definitions.length < 1) throw new Error("must have at least one definition"); + }, +}, AST_Statement); + +var AST_Const = DEFNODE("Const", null, { + $documentation: "A `const` statement", + _validate: function() { + this.definitions.forEach(function(node) { + if (!(node instanceof AST_VarDef)) throw new Error("definitions must be AST_VarDef[]"); + validate_destructured(node.name, function(node) { + if (!(node instanceof AST_SymbolConst)) throw new Error("name must be AST_SymbolConst"); + }); + }); + }, +}, AST_Definitions); + +var AST_Let = DEFNODE("Let", null, { + $documentation: "A `let` statement", + _validate: function() { + this.definitions.forEach(function(node) { + if (!(node instanceof AST_VarDef)) throw new Error("definitions must be AST_VarDef[]"); + validate_destructured(node.name, function(node) { + if (!(node instanceof AST_SymbolLet)) throw new Error("name must be AST_SymbolLet"); + }); + }); + }, +}, AST_Definitions); + +var AST_Var = DEFNODE("Var", null, { + $documentation: "A `var` statement", + _validate: function() { + this.definitions.forEach(function(node) { + if (!(node instanceof AST_VarDef)) throw new Error("definitions must be AST_VarDef[]"); + validate_destructured(node.name, function(node) { + if (!(node instanceof AST_SymbolVar)) throw new Error("name must be AST_SymbolVar"); + }); + }); + }, +}, AST_Definitions); + +var AST_VarDef = DEFNODE("VarDef", "name value", { + $documentation: "A variable declaration; only appears in a AST_Definitions node", + $propdoc: { + name: "[AST_Destructured|AST_SymbolVar] name of the variable", + value: "[AST_Node?] initializer, or null of there's no initializer", + }, + _equals: function(node) { + return this.name.equals(node.name) + && prop_equals(this.value, node.value); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.name.walk(visitor); + if (node.value) node.value.walk(visitor); + }); + }, + _validate: function() { + if (this.value != null) must_be_expression(this, "value"); + }, +}); + +/* -----[ OTHER ]----- */ + +var AST_ExportDeclaration = DEFNODE("ExportDeclaration", "body", { + $documentation: "An `export` statement", + $propdoc: { + body: "[AST_DefClass|AST_Definitions|AST_LambdaDefinition] the statement to export", + }, + _equals: function(node) { + return this.body.equals(node.body); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.body.walk(visitor); + }); + }, + _validate: function() { + if (!(this.body instanceof AST_DefClass + || this.body instanceof AST_Definitions + || this.body instanceof AST_LambdaDefinition)) { + throw new Error("body must be AST_DefClass, AST_Definitions or AST_LambdaDefinition"); + } + }, +}, AST_Statement); + +var AST_ExportDefault = DEFNODE("ExportDefault", "body", { + $documentation: "An `export default` statement", + $propdoc: { + body: "[AST_Node] the default export", + }, + _equals: function(node) { + return this.body.equals(node.body); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.body.walk(visitor); + }); + }, + _validate: function() { + if (!(this.body instanceof AST_DefClass || this.body instanceof AST_LambdaDefinition)) { + must_be_expression(this, "body"); + } + }, +}, AST_Statement); + +var AST_ExportForeign = DEFNODE("ExportForeign", "aliases keys path", { + $documentation: "An `export ... from '...'` statement", + $propdoc: { + aliases: "[AST_String*] array of aliases to export", + keys: "[AST_String*] array of keys to import", + path: "[AST_String] the path to import module", + }, + _equals: function(node) { + return this.path.equals(node.path) + && all_equals(this.aliases, node.aliases) + && all_equals(this.keys, node.keys); + }, + _validate: function() { + if (this.aliases.length != this.keys.length) { + throw new Error("aliases:key length mismatch: " + this.aliases.length + " != " + this.keys.length); + } + this.aliases.forEach(function(name) { + if (!(name instanceof AST_String)) throw new Error("aliases must contain AST_String"); + }); + this.keys.forEach(function(name) { + if (!(name instanceof AST_String)) throw new Error("keys must contain AST_String"); + }); + if (!(this.path instanceof AST_String)) throw new Error("path must be AST_String"); + }, +}, AST_Statement); + +var AST_ExportReferences = DEFNODE("ExportReferences", "properties", { + $documentation: "An `export { ... }` statement", + $propdoc: { + properties: "[AST_SymbolExport*] array of aliases to export", + }, + _equals: function(node) { + return all_equals(this.properties, node.properties); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.properties.forEach(function(prop) { + prop.walk(visitor); + }); + }); + }, + _validate: function() { + this.properties.forEach(function(prop) { + if (!(prop instanceof AST_SymbolExport)) throw new Error("properties must contain AST_SymbolExport"); + }); + }, +}, AST_Statement); + +var AST_Import = DEFNODE("Import", "all default path properties", { + $documentation: "An `import` statement", + $propdoc: { + all: "[AST_SymbolImport?] the imported namespace, or null if not specified", + default: "[AST_SymbolImport?] the alias for default `export`, or null if not specified", + path: "[AST_String] the path to import module", + properties: "[(AST_SymbolImport*)?] array of aliases, or null if not specified", + }, + _equals: function(node) { + return this.path.equals(node.path) + && prop_equals(this.all, node.all) + && prop_equals(this.default, node.default) + && !this.properties == !node.properties + && (!this.properties || all_equals(this.properties, node.properties)); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + if (node.all) node.all.walk(visitor); + if (node.default) node.default.walk(visitor); + if (node.properties) node.properties.forEach(function(prop) { + prop.walk(visitor); + }); + }); + }, + _validate: function() { + if (this.all != null) { + if (!(this.all instanceof AST_SymbolImport)) throw new Error("all must be AST_SymbolImport"); + if (this.properties != null) throw new Error("cannot import both * and {} in the same statement"); + } + if (this.default != null) { + if (!(this.default instanceof AST_SymbolImport)) throw new Error("default must be AST_SymbolImport"); + if (this.default.key.value !== "") throw new Error("invalid default key: " + this.default.key.value); + } + if (!(this.path instanceof AST_String)) throw new Error("path must be AST_String"); + if (this.properties != null) this.properties.forEach(function(node) { + if (!(node instanceof AST_SymbolImport)) throw new Error("properties must contain AST_SymbolImport"); + }); + }, +}, AST_Statement); + +var AST_DefaultValue = DEFNODE("DefaultValue", "name value", { + $documentation: "A default value declaration", + $propdoc: { + name: "[AST_Destructured|AST_SymbolDeclaration] name of the variable", + value: "[AST_Node] value to assign if variable is `undefined`", + }, + _equals: function(node) { + return this.name.equals(node.name) + && this.value.equals(node.value); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.name.walk(visitor); + node.value.walk(visitor); + }); + }, + _validate: function() { + must_be_expression(this, "value"); + }, +}); + +function must_be_expressions(node, prop, allow_spread, allow_hole) { + node[prop].forEach(function(node) { + validate_expression(node, prop, true, allow_spread, allow_hole); + }); +} + +var AST_Call = DEFNODE("Call", "args expression optional pure terminal", { + $documentation: "A function call expression", + $propdoc: { + args: "[AST_Node*] array of arguments", + expression: "[AST_Node] expression to invoke as function", + optional: "[boolean] whether the expression is optional chaining", + pure: "[boolean/S] marker for side-effect-free call expression", + terminal: "[boolean] whether the chain has ended", + }, + _equals: function(node) { + return !this.optional == !node.optional + && this.expression.equals(node.expression) + && all_equals(this.args, node.args); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.expression.walk(visitor); + node.args.forEach(function(arg) { + arg.walk(visitor); + }); + }); + }, + _validate: function() { + must_be_expression(this, "expression"); + must_be_expressions(this, "args", true); + }, +}); + +var AST_New = DEFNODE("New", null, { + $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties", + _validate: function() { + if (this.optional) throw new Error("optional must be false"); + if (this.terminal) throw new Error("terminal must be false"); + }, +}, AST_Call); + +var AST_Sequence = DEFNODE("Sequence", "expressions", { + $documentation: "A sequence expression (comma-separated expressions)", + $propdoc: { + expressions: "[AST_Node*] array of expressions (at least two)", + }, + _equals: function(node) { + return all_equals(this.expressions, node.expressions); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.expressions.forEach(function(expr) { + expr.walk(visitor); + }); + }); + }, + _validate: function() { + if (this.expressions.length < 2) throw new Error("expressions must contain multiple elements"); + must_be_expressions(this, "expressions"); + }, +}); + +function root_expr(prop) { + while (prop instanceof AST_PropAccess) prop = prop.expression; + return prop; +} + +var AST_PropAccess = DEFNODE("PropAccess", "expression optional property terminal", { + $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`", + $propdoc: { + expression: "[AST_Node] the “container” expression", + optional: "[boolean] whether the expression is optional chaining", + property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node", + terminal: "[boolean] whether the chain has ended", + }, + _equals: function(node) { + return !this.optional == !node.optional + && prop_equals(this.property, node.property) + && this.expression.equals(node.expression); + }, + get_property: function() { + var p = this.property; + if (p instanceof AST_Constant) return p.value; + if (p instanceof AST_UnaryPrefix && p.operator == "void" && p.expression instanceof AST_Constant) return; + return p; + }, + _validate: function() { + if (this.TYPE == "PropAccess") throw new Error("should not instantiate AST_PropAccess"); + must_be_expression(this, "expression"); + }, +}); + +var AST_Dot = DEFNODE("Dot", "quoted", { + $documentation: "A dotted property access expression", + $propdoc: { + quoted: "[boolean] whether property is transformed from a quoted string", + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.expression.walk(visitor); + }); + }, + _validate: function() { + if (typeof this.property != "string") throw new Error("property must be string"); + }, +}, AST_PropAccess); + +var AST_Sub = DEFNODE("Sub", null, { + $documentation: "Index-style property access, i.e. `a[\"foo\"]`", + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.expression.walk(visitor); + node.property.walk(visitor); + }); + }, + _validate: function() { + must_be_expression(this, "property"); + }, +}, AST_PropAccess); + +var AST_Spread = DEFNODE("Spread", "expression", { + $documentation: "Spread expression in array/object literals or function calls", + $propdoc: { + expression: "[AST_Node] expression to be expanded", + }, + _equals: function(node) { + return this.expression.equals(node.expression); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.expression.walk(visitor); + }); + }, + _validate: function() { + must_be_expression(this, "expression"); + }, +}); + +var AST_Unary = DEFNODE("Unary", "operator expression", { + $documentation: "Base class for unary expressions", + $propdoc: { + operator: "[string] the operator", + expression: "[AST_Node] expression that this unary operator applies to", + }, + _equals: function(node) { + return this.operator == node.operator + && this.expression.equals(node.expression); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.expression.walk(visitor); + }); + }, + _validate: function() { + if (this.TYPE == "Unary") throw new Error("should not instantiate AST_Unary"); + if (typeof this.operator != "string") throw new Error("operator must be string"); + must_be_expression(this, "expression"); + }, +}); + +var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, { + $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`" +}, AST_Unary); + +var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, { + $documentation: "Unary postfix expression, i.e. `i++`" +}, AST_Unary); + +var AST_Binary = DEFNODE("Binary", "operator left right", { + $documentation: "Binary expression, i.e. `a + b`", + $propdoc: { + left: "[AST_Node] left-hand side expression", + operator: "[string] the operator", + right: "[AST_Node] right-hand side expression" + }, + _equals: function(node) { + return this.operator == node.operator + && this.left.equals(node.left) + && this.right.equals(node.right); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.left.walk(visitor); + node.right.walk(visitor); + }); + }, + _validate: function() { + if (!(this instanceof AST_Assign)) must_be_expression(this, "left"); + if (typeof this.operator != "string") throw new Error("operator must be string"); + must_be_expression(this, "right"); + }, +}); + +var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", { + $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`", + $propdoc: { + condition: "[AST_Node]", + consequent: "[AST_Node]", + alternative: "[AST_Node]" + }, + _equals: function(node) { + return this.condition.equals(node.condition) + && this.consequent.equals(node.consequent) + && this.alternative.equals(node.alternative); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.condition.walk(visitor); + node.consequent.walk(visitor); + node.alternative.walk(visitor); + }); + }, + _validate: function() { + must_be_expression(this, "condition"); + must_be_expression(this, "consequent"); + must_be_expression(this, "alternative"); + }, +}); + +var AST_Assign = DEFNODE("Assign", null, { + $documentation: "An assignment expression — `a = b + 5`", + _validate: function() { + if (this.operator.indexOf("=") < 0) throw new Error('operator must contain "="'); + if (this.left instanceof AST_Destructured) { + if (this.operator != "=") throw new Error("invalid destructuring operator: " + this.operator); + validate_destructured(this.left, function(node) { + if (!(node instanceof AST_PropAccess || node instanceof AST_SymbolRef)) { + throw new Error("left must be assignable: " + node.TYPE); + } + }); + } else if (!(this.left instanceof AST_Infinity + || this.left instanceof AST_NaN + || this.left instanceof AST_PropAccess && !this.left.optional + || this.left instanceof AST_SymbolRef + || this.left instanceof AST_Undefined)) { + throw new Error("left must be assignable"); + } + }, +}, AST_Binary); + +var AST_Await = DEFNODE("Await", "expression", { + $documentation: "An await expression", + $propdoc: { + expression: "[AST_Node] expression with Promise to resolve on", + }, + _equals: function(node) { + return this.expression.equals(node.expression); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.expression.walk(visitor); + }); + }, + _validate: function() { + must_be_expression(this, "expression"); + }, +}); + +var AST_Yield = DEFNODE("Yield", "expression nested", { + $documentation: "A yield expression", + $propdoc: { + expression: "[AST_Node?] return value for iterator, or null if undefined", + nested: "[boolean] whether to iterate over expression as generator", + }, + _equals: function(node) { + return !this.nested == !node.nested + && prop_equals(this.expression, node.expression); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + if (node.expression) node.expression.walk(visitor); + }); + }, + _validate: function() { + if (this.expression != null) { + must_be_expression(this, "expression"); + } else if (this.nested) { + throw new Error("yield* must contain expression"); + } + }, +}); + +/* -----[ LITERALS ]----- */ + +var AST_Array = DEFNODE("Array", "elements", { + $documentation: "An array literal", + $propdoc: { + elements: "[AST_Node*] array of elements" + }, + _equals: function(node) { + return all_equals(this.elements, node.elements); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.elements.forEach(function(element) { + element.walk(visitor); + }); + }); + }, + _validate: function() { + must_be_expressions(this, "elements", true, true); + }, +}); + +var AST_Destructured = DEFNODE("Destructured", "rest", { + $documentation: "Base class for destructured literal", + $propdoc: { + rest: "[(AST_Destructured|AST_SymbolDeclaration|AST_SymbolRef)?] rest parameter, or null if absent", + }, + _validate: function() { + if (this.TYPE == "Destructured") throw new Error("should not instantiate AST_Destructured"); + }, +}); + +function validate_destructured(node, check, allow_default) { + if (node instanceof AST_DefaultValue && allow_default) return validate_destructured(node.name, check); + if (node instanceof AST_Destructured) { + if (node.rest != null) validate_destructured(node.rest, check); + if (node instanceof AST_DestructuredArray) return node.elements.forEach(function(node) { + if (!(node instanceof AST_Hole)) validate_destructured(node, check, true); + }); + if (node instanceof AST_DestructuredObject) return node.properties.forEach(function(prop) { + validate_destructured(prop.value, check, true); + }); + } + check(node); +} + +var AST_DestructuredArray = DEFNODE("DestructuredArray", "elements", { + $documentation: "A destructured array literal", + $propdoc: { + elements: "[(AST_DefaultValue|AST_Destructured|AST_SymbolDeclaration|AST_SymbolRef)*] array of elements", + }, + _equals: function(node) { + return prop_equals(this.rest, node.rest) + && all_equals(this.elements, node.elements); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.elements.forEach(function(element) { + element.walk(visitor); + }); + if (node.rest) node.rest.walk(visitor); + }); + }, +}, AST_Destructured); + +var AST_DestructuredKeyVal = DEFNODE("DestructuredKeyVal", "key value", { + $documentation: "A key: value destructured property", + $propdoc: { + key: "[string|AST_Node] property name. For computed property this is an AST_Node.", + value: "[AST_DefaultValue|AST_Destructured|AST_SymbolDeclaration|AST_SymbolRef] property value", + }, + _equals: function(node) { + return prop_equals(this.key, node.key) + && this.value.equals(node.value); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + if (node.key instanceof AST_Node) node.key.walk(visitor); + node.value.walk(visitor); + }); + }, + _validate: function() { + if (typeof this.key != "string") { + if (!(this.key instanceof AST_Node)) throw new Error("key must be string or AST_Node"); + must_be_expression(this, "key"); + } + if (!(this.value instanceof AST_Node)) throw new Error("value must be AST_Node"); + }, +}); + +var AST_DestructuredObject = DEFNODE("DestructuredObject", "properties", { + $documentation: "A destructured object literal", + $propdoc: { + properties: "[AST_DestructuredKeyVal*] array of properties", + }, + _equals: function(node) { + return prop_equals(this.rest, node.rest) + && all_equals(this.properties, node.properties); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.properties.forEach(function(prop) { + prop.walk(visitor); + }); + if (node.rest) node.rest.walk(visitor); + }); + }, + _validate: function() { + this.properties.forEach(function(node) { + if (!(node instanceof AST_DestructuredKeyVal)) throw new Error("properties must be AST_DestructuredKeyVal[]"); + }); + }, +}, AST_Destructured); + +var AST_Object = DEFNODE("Object", "properties", { + $documentation: "An object literal", + $propdoc: { + properties: "[(AST_ObjectProperty|AST_Spread)*] array of properties" + }, + _equals: function(node) { + return all_equals(this.properties, node.properties); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + node.properties.forEach(function(prop) { + prop.walk(visitor); + }); + }); + }, + _validate: function() { + this.properties.forEach(function(node) { + if (!(node instanceof AST_ObjectProperty || node instanceof AST_Spread)) { + throw new Error("properties must contain AST_ObjectProperty and/or AST_Spread only"); + } + }); + }, +}); + +var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", { + $documentation: "Base class for literal object properties", + $propdoc: { + key: "[string|AST_Node] property name. For computed property this is an AST_Node.", + value: "[AST_Node] property value. For getters and setters this is an AST_Accessor.", + }, + _equals: function(node) { + return prop_equals(this.key, node.key) + && this.value.equals(node.value); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + if (node.key instanceof AST_Node) node.key.walk(visitor); + node.value.walk(visitor); + }); + }, + _validate: function() { + if (this.TYPE == "ObjectProperty") throw new Error("should not instantiate AST_ObjectProperty"); + if (typeof this.key != "string") { + if (!(this.key instanceof AST_Node)) throw new Error("key must be string or AST_Node"); + must_be_expression(this, "key"); + } + if (!(this.value instanceof AST_Node)) throw new Error("value must be AST_Node"); + }, +}); + +var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", null, { + $documentation: "A key: value object property", + _validate: function() { + must_be_expression(this, "value"); + }, +}, AST_ObjectProperty); + +var AST_ObjectMethod = DEFNODE("ObjectMethod", null, { + $documentation: "A key(){} object property", + _validate: function() { + if (!(this.value instanceof AST_LambdaExpression)) throw new Error("value must be AST_LambdaExpression"); + if (is_arrow(this.value)) throw new Error("value cannot be AST_Arrow or AST_AsyncArrow"); + if (this.value.name != null) throw new Error("name of object method's lambda must be null"); + }, +}, AST_ObjectKeyVal); + +var AST_ObjectSetter = DEFNODE("ObjectSetter", null, { + $documentation: "An object setter property", + _validate: function() { + if (!(this.value instanceof AST_Accessor)) throw new Error("value must be AST_Accessor"); + }, +}, AST_ObjectProperty); + +var AST_ObjectGetter = DEFNODE("ObjectGetter", null, { + $documentation: "An object getter property", + _validate: function() { + if (!(this.value instanceof AST_Accessor)) throw new Error("value must be AST_Accessor"); + }, +}, AST_ObjectProperty); + +var AST_Symbol = DEFNODE("Symbol", "scope name thedef", { + $documentation: "Base class for all symbols", + $propdoc: { + name: "[string] name of this symbol", + scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)", + thedef: "[SymbolDef/S] the definition of this symbol" + }, + _equals: function(node) { + return this.thedef ? this.thedef === node.thedef : this.name == node.name; + }, + _validate: function() { + if (this.TYPE == "Symbol") throw new Error("should not instantiate AST_Symbol"); + if (typeof this.name != "string") throw new Error("name must be string"); + }, +}); + +var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", { + $documentation: "A declaration symbol (symbol in var, function name or argument, symbol in catch)", +}, AST_Symbol); + +var AST_SymbolConst = DEFNODE("SymbolConst", null, { + $documentation: "Symbol defining a constant", +}, AST_SymbolDeclaration); + +var AST_SymbolImport = DEFNODE("SymbolImport", "key", { + $documentation: "Symbol defined by an `import` statement", + $propdoc: { + key: "[AST_String] the original `export` name", + }, + _equals: function(node) { + return this.name == node.name + && this.key.equals(node.key); + }, + _validate: function() { + if (!(this.key instanceof AST_String)) throw new Error("key must be AST_String"); + }, +}, AST_SymbolConst); + +var AST_SymbolLet = DEFNODE("SymbolLet", null, { + $documentation: "Symbol defining a lexical-scoped variable", +}, AST_SymbolDeclaration); + +var AST_SymbolVar = DEFNODE("SymbolVar", null, { + $documentation: "Symbol defining a variable", +}, AST_SymbolDeclaration); + +var AST_SymbolFunarg = DEFNODE("SymbolFunarg", "unused", { + $documentation: "Symbol naming a function argument", +}, AST_SymbolVar); + +var AST_SymbolDefun = DEFNODE("SymbolDefun", null, { + $documentation: "Symbol defining a function", +}, AST_SymbolDeclaration); + +var AST_SymbolLambda = DEFNODE("SymbolLambda", null, { + $documentation: "Symbol naming a function expression", +}, AST_SymbolDeclaration); + +var AST_SymbolDefClass = DEFNODE("SymbolDefClass", null, { + $documentation: "Symbol defining a class", +}, AST_SymbolConst); + +var AST_SymbolClass = DEFNODE("SymbolClass", null, { + $documentation: "Symbol naming a class expression", +}, AST_SymbolConst); + +var AST_SymbolCatch = DEFNODE("SymbolCatch", null, { + $documentation: "Symbol naming the exception in catch", +}, AST_SymbolDeclaration); + +var AST_Label = DEFNODE("Label", "references", { + $documentation: "Symbol naming a label (declaration)", + $propdoc: { + references: "[AST_LoopControl*] a list of nodes referring to this label" + }, + initialize: function() { + this.references = []; + this.thedef = this; + }, +}, AST_Symbol); + +var AST_SymbolRef = DEFNODE("SymbolRef", "fixed in_arg redef", { + $documentation: "Reference to some symbol (not definition/declaration)", +}, AST_Symbol); + +var AST_SymbolExport = DEFNODE("SymbolExport", "alias", { + $documentation: "Reference in an `export` statement", + $propdoc: { + alias: "[AST_String] the `export` alias", + }, + _equals: function(node) { + return this.name == node.name + && this.alias.equals(node.alias); + }, + _validate: function() { + if (!(this.alias instanceof AST_String)) throw new Error("alias must be AST_String"); + }, +}, AST_SymbolRef); + +var AST_LabelRef = DEFNODE("LabelRef", null, { + $documentation: "Reference to a label symbol", +}, AST_Symbol); + +var AST_ObjectIdentity = DEFNODE("ObjectIdentity", null, { + $documentation: "Base class for `super` & `this`", + _equals: return_true, + _validate: function() { + if (this.TYPE == "ObjectIdentity") throw new Error("should not instantiate AST_ObjectIdentity"); + }, +}, AST_Symbol); + +var AST_Super = DEFNODE("Super", null, { + $documentation: "The `super` symbol", + _validate: function() { + if (this.name !== "super") throw new Error('name must be "super"'); + }, +}, AST_ObjectIdentity); + +var AST_This = DEFNODE("This", null, { + $documentation: "The `this` symbol", + _validate: function() { + if (this.TYPE == "This" && this.name !== "this") throw new Error('name must be "this"'); + }, +}, AST_ObjectIdentity); + +var AST_NewTarget = DEFNODE("NewTarget", null, { + $documentation: "The `new.target` symbol", + initialize: function() { + this.name = "new.target"; + }, + _validate: function() { + if (this.name !== "new.target") throw new Error('name must be "new.target": ' + this.name); + }, +}, AST_This); + +var AST_Template = DEFNODE("Template", "expressions strings tag", { + $documentation: "A template literal, i.e. tag`str1${expr1}...strN${exprN}strN+1`", + $propdoc: { + expressions: "[AST_Node*] the placeholder expressions", + strings: "[string*] the raw text segments", + tag: "[AST_Node?] tag function, or null if absent", + }, + _equals: function(node) { + return prop_equals(this.tag, node.tag) + && list_equals(this.strings, node.strings) + && all_equals(this.expressions, node.expressions); + }, + walk: function(visitor) { + var node = this; + visitor.visit(node, function() { + if (node.tag) node.tag.walk(visitor); + node.expressions.forEach(function(expr) { + expr.walk(visitor); + }); + }); + }, + _validate: function() { + if (this.expressions.length + 1 != this.strings.length) { + throw new Error("malformed template with " + this.expressions.length + " placeholder(s) but " + this.strings.length + " text segment(s)"); + } + must_be_expressions(this, "expressions"); + this.strings.forEach(function(string) { + if (typeof string != "string") throw new Error("strings must contain string"); + }); + if (this.tag != null) must_be_expression(this, "tag"); + }, +}); + +var AST_Constant = DEFNODE("Constant", null, { + $documentation: "Base class for all constants", + _equals: function(node) { + return this.value === node.value; + }, + _validate: function() { + if (this.TYPE == "Constant") throw new Error("should not instantiate AST_Constant"); + }, +}); + +var AST_String = DEFNODE("String", "quote value", { + $documentation: "A string literal", + $propdoc: { + quote: "[string?] the original quote character", + value: "[string] the contents of this string", + }, + _validate: function() { + if (this.quote != null) { + if (typeof this.quote != "string") throw new Error("quote must be string"); + if (!/^["']$/.test(this.quote)) throw new Error("invalid quote: " + this.quote); + } + if (typeof this.value != "string") throw new Error("value must be string"); + }, +}, AST_Constant); + +var AST_Number = DEFNODE("Number", "value", { + $documentation: "A number literal", + $propdoc: { + value: "[number] the numeric value", + }, + _validate: function() { + if (typeof this.value != "number") throw new Error("value must be number"); + if (!isFinite(this.value)) throw new Error("value must be finite"); + if (this.value < 0) throw new Error("value cannot be negative"); + }, +}, AST_Constant); + +var AST_BigInt = DEFNODE("BigInt", "value", { + $documentation: "A BigInt literal", + $propdoc: { + value: "[string] the numeric representation", + }, + _validate: function() { + if (typeof this.value != "string") throw new Error("value must be string"); + if (this.value[0] == "-") throw new Error("value cannot be negative"); + }, +}, AST_Constant); + +var AST_RegExp = DEFNODE("RegExp", "value", { + $documentation: "A regexp literal", + $propdoc: { + value: "[RegExp] the actual regexp" + }, + _equals: function(node) { + return "" + this.value == "" + node.value; + }, + _validate: function() { + if (!(this.value instanceof RegExp)) throw new Error("value must be RegExp"); + }, +}, AST_Constant); + +var AST_Atom = DEFNODE("Atom", null, { + $documentation: "Base class for atoms", + _equals: return_true, + _validate: function() { + if (this.TYPE == "Atom") throw new Error("should not instantiate AST_Atom"); + }, +}, AST_Constant); + +var AST_Null = DEFNODE("Null", null, { + $documentation: "The `null` atom", + value: null, +}, AST_Atom); + +var AST_NaN = DEFNODE("NaN", null, { + $documentation: "The impossible value", + value: 0/0, +}, AST_Atom); + +var AST_Undefined = DEFNODE("Undefined", null, { + $documentation: "The `undefined` value", + value: function(){}(), +}, AST_Atom); + +var AST_Hole = DEFNODE("Hole", null, { + $documentation: "A hole in an array", + value: function(){}(), +}, AST_Atom); + +var AST_Infinity = DEFNODE("Infinity", null, { + $documentation: "The `Infinity` value", + value: 1/0, +}, AST_Atom); + +var AST_Boolean = DEFNODE("Boolean", null, { + $documentation: "Base class for booleans", + _validate: function() { + if (this.TYPE == "Boolean") throw new Error("should not instantiate AST_Boolean"); + }, +}, AST_Atom); + +var AST_False = DEFNODE("False", null, { + $documentation: "The `false` atom", + value: false, +}, AST_Boolean); + +var AST_True = DEFNODE("True", null, { + $documentation: "The `true` atom", + value: true, +}, AST_Boolean); + +/* -----[ TreeWalker ]----- */ + +function TreeWalker(callback) { + this.callback = callback; + this.directives = Object.create(null); + this.stack = []; +} +TreeWalker.prototype = { + visit: function(node, descend) { + this.push(node); + var done = this.callback(node, descend || noop); + if (!done && descend) descend(); + this.pop(); + }, + parent: function(n) { + return this.stack[this.stack.length - 2 - (n || 0)]; + }, + push: function(node) { + var value; + if (node instanceof AST_Class) { + this.directives = Object.create(this.directives); + value = "use strict"; + } else if (node instanceof AST_Directive) { + value = node.value; + } else if (node instanceof AST_Lambda) { + this.directives = Object.create(this.directives); + } + if (value && !this.directives[value]) this.directives[value] = node; + this.stack.push(node); + }, + pop: function() { + var node = this.stack.pop(); + if (node instanceof AST_Class || node instanceof AST_Lambda) { + this.directives = Object.getPrototypeOf(this.directives); + } + }, + self: function() { + return this.stack[this.stack.length - 1]; + }, + find_parent: function(type) { + var stack = this.stack; + for (var i = stack.length - 1; --i >= 0;) { + var x = stack[i]; + if (x instanceof type) return x; + } + }, + has_directive: function(type) { + var dir = this.directives[type]; + if (dir) return dir; + var node = this.stack[this.stack.length - 1]; + if (node instanceof AST_Scope) { + for (var i = 0; i < node.body.length; ++i) { + var st = node.body[i]; + if (!(st instanceof AST_Directive)) break; + if (st.value == type) return st; + } + } + }, + loopcontrol_target: function(node) { + var stack = this.stack; + if (node.label) for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_LabeledStatement && x.label.name == node.label.name) + return x.body; + } else for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_IterationStatement + || node instanceof AST_Break && x instanceof AST_Switch) + return x; + } + }, + in_boolean_context: function() { + for (var drop = true, level = 0, parent, self = this.self(); parent = this.parent(level++); self = parent) { + if (parent instanceof AST_Binary) switch (parent.operator) { + case "&&": + case "||": + if (parent.left === self) drop = false; + continue; + default: + return false; + } + if (parent instanceof AST_Conditional) { + if (parent.condition === self) return true; + continue; + } + if (parent instanceof AST_DWLoop) return parent.condition === self; + if (parent instanceof AST_For) return parent.condition === self; + if (parent instanceof AST_If) return parent.condition === self; + if (parent instanceof AST_Return) { + if (parent.in_bool) return true; + while (parent = this.parent(level++)) { + if (parent instanceof AST_Lambda) { + if (parent.name) return false; + parent = this.parent(level++); + if (parent.TYPE != "Call") return false; + break; + } + } + } + if (parent instanceof AST_Sequence) { + if (parent.tail_node() === self) continue; + return drop ? "d" : true; + } + if (parent instanceof AST_SimpleStatement) return drop ? "d" : true; + if (parent instanceof AST_UnaryPrefix) return parent.operator == "!"; + return false; + } + } +}; diff --git a/node_modules/uglify-js/lib/compress.js b/node_modules/uglify-js/lib/compress.js new file mode 100644 index 0000000..cde397c --- /dev/null +++ b/node_modules/uglify-js/lib/compress.js @@ -0,0 +1,14241 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function Compressor(options, false_by_default) { + if (!(this instanceof Compressor)) + return new Compressor(options, false_by_default); + TreeTransformer.call(this, this.before, this.after); + this.options = defaults(options, { + annotations : !false_by_default, + arguments : !false_by_default, + arrows : !false_by_default, + assignments : !false_by_default, + awaits : !false_by_default, + booleans : !false_by_default, + collapse_vars : !false_by_default, + comparisons : !false_by_default, + conditionals : !false_by_default, + dead_code : !false_by_default, + default_values : !false_by_default, + directives : !false_by_default, + drop_console : false, + drop_debugger : !false_by_default, + evaluate : !false_by_default, + expression : false, + functions : !false_by_default, + global_defs : false, + hoist_exports : !false_by_default, + hoist_funs : false, + hoist_props : !false_by_default, + hoist_vars : false, + ie : false, + if_return : !false_by_default, + imports : !false_by_default, + inline : !false_by_default, + join_vars : !false_by_default, + keep_fargs : false_by_default, + keep_fnames : false, + keep_infinity : false, + loops : !false_by_default, + merge_vars : !false_by_default, + module : false, + negate_iife : !false_by_default, + objects : !false_by_default, + optional_chains : !false_by_default, + passes : 1, + properties : !false_by_default, + pure_funcs : null, + pure_getters : !false_by_default && "strict", + reduce_funcs : !false_by_default, + reduce_vars : !false_by_default, + rests : !false_by_default, + sequences : !false_by_default, + side_effects : !false_by_default, + spreads : !false_by_default, + strings : !false_by_default, + switches : !false_by_default, + templates : !false_by_default, + top_retain : null, + toplevel : !!(options && (options["module"] || options["top_retain"])), + typeofs : !false_by_default, + unsafe : false, + unsafe_comps : false, + unsafe_Function : false, + unsafe_math : false, + unsafe_proto : false, + unsafe_regexp : false, + unsafe_undefined: false, + unused : !false_by_default, + varify : !false_by_default, + webkit : false, + yields : !false_by_default, + }, true); + var evaluate = this.options["evaluate"]; + this.eval_threshold = /eager/.test(evaluate) ? 1 / 0 : +evaluate; + var global_defs = this.options["global_defs"]; + if (typeof global_defs == "object") for (var key in global_defs) { + if (/^@/.test(key) && HOP(global_defs, key)) { + global_defs[key.slice(1)] = parse(global_defs[key], { expression: true }); + } + } + if (this.options["inline"] === true) this.options["inline"] = 4; + this.drop_fargs = this.options["keep_fargs"] ? return_false : function(lambda, parent) { + if (lambda.length_read) return false; + var name = lambda.name; + if (!name) return parent && parent.TYPE == "Call" && parent.expression === lambda; + if (name.fixed_value() !== lambda) return false; + var def = name.definition(); + if (def.direct_access) return false; + var escaped = def.escaped; + return escaped && escaped.depth != 1; + }; + if (this.options["module"]) this.directives["use strict"] = true; + var pure_funcs = this.options["pure_funcs"]; + if (typeof pure_funcs == "function") { + this.pure_funcs = pure_funcs; + } else if (typeof pure_funcs == "string") { + this.pure_funcs = function(node) { + var expr; + if (node instanceof AST_Call) { + expr = node.expression; + } else if (node instanceof AST_Template) { + expr = node.tag; + } + return !(expr && pure_funcs === expr.print_to_string()); + }; + } else if (Array.isArray(pure_funcs)) { + this.pure_funcs = function(node) { + var expr; + if (node instanceof AST_Call) { + expr = node.expression; + } else if (node instanceof AST_Template) { + expr = node.tag; + } + return !(expr && member(expr.print_to_string(), pure_funcs)); + }; + } else { + this.pure_funcs = return_true; + } + var sequences = this.options["sequences"]; + this.sequences_limit = sequences == 1 ? 800 : sequences | 0; + var top_retain = this.options["top_retain"]; + if (top_retain instanceof RegExp) { + this.top_retain = function(def) { + return top_retain.test(def.name); + }; + } else if (typeof top_retain == "function") { + this.top_retain = top_retain; + } else if (top_retain) { + if (typeof top_retain == "string") { + top_retain = top_retain.split(/,/); + } + this.top_retain = function(def) { + return member(def.name, top_retain); + }; + } + var toplevel = this.options["toplevel"]; + this.toplevel = typeof toplevel == "string" ? { + funcs: /funcs/.test(toplevel), + vars: /vars/.test(toplevel) + } : { + funcs: toplevel, + vars: toplevel + }; +} + +Compressor.prototype = new TreeTransformer(function(node, descend, in_list) { + if (node._squeezed) return node; + var is_scope = node instanceof AST_Scope; + if (is_scope) { + if (this.option("arrows") && is_arrow(node) && node.value) { + node.body = [ node.first_statement() ]; + node.value = null; + } + node.hoist_properties(this); + node.hoist_declarations(this); + node.process_returns(this); + } + // Before https://github.com/mishoo/UglifyJS/pull/1602 AST_Node.optimize() + // would call AST_Node.transform() if a different instance of AST_Node is + // produced after OPT(). + // This corrupts TreeWalker.stack, which cause AST look-ups to malfunction. + // Migrate and defer all children's AST_Node.transform() to below, which + // will now happen after this parent AST_Node has been properly substituted + // thus gives a consistent AST snapshot. + descend(node, this); + // Existing code relies on how AST_Node.optimize() worked, and omitting the + // following replacement call would result in degraded efficiency of both + // output and performance. + descend(node, this); + var opt = node.optimize(this); + if (is_scope && opt === node && !this.has_directive("use asm") && !opt.pinned()) { + opt.drop_unused(this); + if (opt.merge_variables(this)) opt.drop_unused(this); + descend(opt, this); + } + if (opt === node) opt._squeezed = true; + return opt; +}); +Compressor.prototype.option = function(key) { + return this.options[key]; +}; +Compressor.prototype.exposed = function(def) { + if (def.exported) return true; + if (def.undeclared) return true; + if (!(def.global || def.scope.resolve() instanceof AST_Toplevel)) return false; + var toplevel = this.toplevel; + return !all(def.orig, function(sym) { + return toplevel[sym instanceof AST_SymbolDefun ? "funcs" : "vars"]; + }); +}; +Compressor.prototype.compress = function(node) { + node = node.resolve_defines(this); + node.hoist_exports(this); + if (this.option("expression")) node.process_expression(true); + var merge_vars = this.options.merge_vars; + var passes = +this.options.passes || 1; + var min_count = 1 / 0; + var stopping = false; + var mangle = { ie: this.option("ie") }; + for (var pass = 0; pass < passes; pass++) { + node.figure_out_scope(mangle); + if (pass > 0 || this.option("reduce_vars")) + node.reset_opt_flags(this); + this.options.merge_vars = merge_vars && (stopping || pass == passes - 1); + node = node.transform(this); + if (passes > 1) { + var count = 0; + node.walk(new TreeWalker(function() { + count++; + })); + AST_Node.info("pass {pass}: last_count: {min_count}, count: {count}", { + pass: pass, + min_count: min_count, + count: count, + }); + if (count < min_count) { + min_count = count; + stopping = false; + } else if (stopping) { + break; + } else { + stopping = true; + } + } + } + if (this.option("expression")) node.process_expression(false); + return node; +}; + +(function(OPT) { + OPT(AST_Node, function(self, compressor) { + return self; + }); + + AST_Toplevel.DEFMETHOD("hoist_exports", function(compressor) { + if (!compressor.option("hoist_exports")) return; + var body = this.body, props = []; + for (var i = 0; i < body.length; i++) { + var stat = body[i]; + if (stat instanceof AST_ExportDeclaration) { + body[i] = stat = stat.body; + if (stat instanceof AST_Definitions) { + stat.definitions.forEach(function(defn) { + defn.name.match_symbol(export_symbol, true); + }); + } else { + export_symbol(stat.name); + } + } else if (stat instanceof AST_ExportReferences) { + body.splice(i--, 1); + [].push.apply(props, stat.properties); + } + } + if (props.length) body.push(make_node(AST_ExportReferences, this, { properties: props })); + + function export_symbol(sym) { + if (!(sym instanceof AST_SymbolDeclaration)) return; + var node = make_node(AST_SymbolExport, sym); + node.alias = make_node(AST_String, node, { value: node.name }); + props.push(node); + } + }); + + AST_Scope.DEFMETHOD("process_expression", function(insert, transform) { + var self = this; + var tt = new TreeTransformer(function(node) { + if (insert) { + if (node instanceof AST_Directive) node = make_node(AST_SimpleStatement, node, { + body: make_node(AST_String, node), + }); + if (node instanceof AST_SimpleStatement) { + return transform ? transform(node) : make_node(AST_Return, node, { value: node.body }); + } + } else if (node instanceof AST_Return) { + if (transform) return transform(node); + var value = node.value; + if (value instanceof AST_String) return make_node(AST_Directive, value); + return make_node(AST_SimpleStatement, node, { + body: value || make_node(AST_UnaryPrefix, node, { + operator: "void", + expression: make_node(AST_Number, node, { value: 0 }), + }), + }); + } + if (node instanceof AST_Block) { + if (node instanceof AST_Lambda) { + if (node !== self) return node; + } else if (insert === "awaits" && node instanceof AST_Try) { + if (node.bfinally) return node; + } + for (var index = node.body.length; --index >= 0;) { + var stat = node.body[index]; + if (!is_declaration(stat, true)) { + node.body[index] = stat.transform(tt); + break; + } + } + } else if (node instanceof AST_If) { + node.body = node.body.transform(tt); + if (node.alternative) node.alternative = node.alternative.transform(tt); + } else if (node instanceof AST_With) { + node.body = node.body.transform(tt); + } + return node; + }); + self.transform(tt); + }); + AST_Toplevel.DEFMETHOD("unwrap_expression", function() { + var self = this; + switch (self.body.length) { + case 0: + return make_node(AST_UnaryPrefix, self, { + operator: "void", + expression: make_node(AST_Number, self, { value: 0 }), + }); + case 1: + var stat = self.body[0]; + if (stat instanceof AST_Directive) return make_node(AST_String, stat); + if (stat instanceof AST_SimpleStatement) return stat.body; + default: + return make_node(AST_Call, self, { + expression: make_node(AST_Function, self, { + argnames: [], + body: self.body, + }).init_vars(self), + args: [], + }); + } + }); + AST_Node.DEFMETHOD("wrap_expression", function() { + var self = this; + if (!is_statement(self)) self = make_node(AST_SimpleStatement, self, { body: self }); + if (!(self instanceof AST_Toplevel)) self = make_node(AST_Toplevel, self, { body: [ self ] }); + return self; + }); + + function read_property(obj, node) { + var key = node.get_property(); + if (key instanceof AST_Node) return; + var value; + if (obj instanceof AST_Array) { + var elements = obj.elements; + if (key == "length") return make_node_from_constant(elements.length, obj); + if (typeof key == "number" && key in elements) value = elements[key]; + } else if (obj instanceof AST_Lambda) { + if (key == "length") { + obj.length_read = true; + return make_node_from_constant(obj.argnames.length, obj); + } + } else if (obj instanceof AST_Object) { + key = "" + key; + var props = obj.properties; + for (var i = props.length; --i >= 0;) { + var prop = props[i]; + if (!can_hoist_property(prop)) return; + if (!value && props[i].key === key) value = props[i].value; + } + } + return value instanceof AST_SymbolRef && value.fixed_value() || value; + } + + function is_read_only_fn(value, name) { + if (value instanceof AST_Boolean) return native_fns.Boolean[name]; + if (value instanceof AST_Number) return native_fns.Number[name]; + if (value instanceof AST_String) return native_fns.String[name]; + if (name == "valueOf") return false; + if (value instanceof AST_Array) return native_fns.Array[name]; + if (value instanceof AST_Lambda) return native_fns.Function[name]; + if (value instanceof AST_Object) return native_fns.Object[name]; + if (value instanceof AST_RegExp) return native_fns.RegExp[name] && !value.value.global; + } + + function is_modified(compressor, tw, node, value, level, immutable, recursive) { + var parent = tw.parent(level); + if (compressor.option("unsafe") && parent instanceof AST_Dot && is_read_only_fn(value, parent.property)) { + return; + } + var lhs = is_lhs(node, parent); + if (lhs) return lhs; + if (level == 0 && value && value.is_constant()) return; + if (parent instanceof AST_Array) return is_modified(compressor, tw, parent, parent, level + 1); + if (parent instanceof AST_Assign) switch (parent.operator) { + case "=": + return is_modified(compressor, tw, parent, value, level + 1, immutable, recursive); + case "&&=": + case "||=": + case "??=": + return is_modified(compressor, tw, parent, parent, level + 1); + default: + return; + } + if (parent instanceof AST_Binary) { + if (!lazy_op[parent.operator]) return; + return is_modified(compressor, tw, parent, parent, level + 1); + } + if (parent instanceof AST_Call) { + return !immutable + && parent.expression === node + && !parent.is_expr_pure(compressor) + && (!(value instanceof AST_LambdaExpression) || !(parent instanceof AST_New) && value.contains_this()); + } + if (parent instanceof AST_Conditional) { + if (parent.condition === node) return; + return is_modified(compressor, tw, parent, parent, level + 1); + } + if (parent instanceof AST_ForEnumeration) return parent.init === node; + if (parent instanceof AST_ObjectKeyVal) { + if (parent.value !== node) return; + var obj = tw.parent(level + 1); + return is_modified(compressor, tw, obj, obj, level + 2); + } + if (parent instanceof AST_PropAccess) { + if (parent.expression !== node) return; + var prop = read_property(value, parent); + return (!immutable || recursive) && is_modified(compressor, tw, parent, prop, level + 1); + } + if (parent instanceof AST_Sequence) { + if (parent.tail_node() !== node) return; + return is_modified(compressor, tw, parent, value, level + 1, immutable, recursive); + } + } + + function is_lambda(node) { + return node instanceof AST_Class || node instanceof AST_Lambda; + } + + function safe_for_extends(node) { + return node instanceof AST_Class || node instanceof AST_Defun || node instanceof AST_Function; + } + + function is_arguments(def) { + return def.name == "arguments" && def.scope.uses_arguments; + } + + function cross_scope(def, sym) { + do { + if (def === sym) return false; + if (sym instanceof AST_Scope) return true; + } while (sym = sym.parent_scope); + } + + function can_drop_symbol(ref, compressor, keep_lambda) { + var def = ref.redef || ref.definition(); + if (ref.in_arg && is_funarg(def)) return false; + return all(def.orig, function(sym) { + if (sym instanceof AST_SymbolConst || sym instanceof AST_SymbolLet) { + if (sym instanceof AST_SymbolImport) return true; + return compressor && can_varify(compressor, sym); + } + return !(keep_lambda && sym instanceof AST_SymbolLambda); + }); + } + + function has_escaped(d, scope, node, parent) { + if (parent instanceof AST_Assign) return parent.operator == "=" && parent.right === node; + if (parent instanceof AST_Call) return parent.expression !== node || parent instanceof AST_New; + if (parent instanceof AST_ClassField) return parent.value === node && !parent.static; + if (parent instanceof AST_Exit) return parent.value === node && scope.resolve() !== d.scope.resolve(); + if (parent instanceof AST_VarDef) return parent.value === node; + } + + function make_ref(ref, fixed) { + var node = make_node(AST_SymbolRef, ref); + node.fixed = fixed || make_node(AST_Undefined, ref); + return node; + } + + function replace_ref(resolve, fixed) { + return function(node) { + var ref = resolve(node); + var node = make_ref(ref, fixed); + var def = ref.definition(); + def.references.push(node); + def.replaced++; + return node; + }; + } + + var RE_POSITIVE_INTEGER = /^(0|[1-9][0-9]*)$/; + (function(def) { + def(AST_Node, noop); + + function reset_def(tw, compressor, def) { + def.assignments = 0; + def.bool_return = 0; + def.drop_return = 0; + def.cross_loop = false; + def.direct_access = false; + def.escaped = []; + def.fixed = !def.const_redefs + && !def.scope.pinned() + && !compressor.exposed(def) + && !(def.init instanceof AST_LambdaExpression && def.init !== def.scope) + && def.init; + def.reassigned = 0; + def.recursive_refs = 0; + def.references = []; + def.single_use = undefined; + } + + function reset_block_variables(tw, compressor, scope) { + scope.variables.each(function(def) { + reset_def(tw, compressor, def); + }); + } + + function reset_variables(tw, compressor, scope) { + scope.fn_defs = []; + scope.variables.each(function(def) { + reset_def(tw, compressor, def); + var init = def.init; + if (init instanceof AST_LambdaDefinition) { + scope.fn_defs.push(init); + init.safe_ids = null; + } + if (def.fixed === null) { + def.safe_ids = tw.safe_ids; + mark(tw, def); + } else if (def.fixed) { + tw.loop_ids[def.id] = tw.in_loop; + mark(tw, def); + } + }); + scope.may_call_this = function() { + scope.may_call_this = scope.contains_this() ? return_true : return_false; + }; + if (scope.uses_arguments) scope.each_argname(function(node) { + node.definition().last_ref = false; + }); + if (compressor.option("ie")) scope.variables.each(function(def) { + var d = def.orig[0].definition(); + if (d !== def) d.fixed = false; + }); + } + + function safe_to_visit(tw, fn) { + var marker = fn.safe_ids; + return marker === undefined || marker === tw.safe_ids; + } + + function walk_fn_def(tw, fn) { + var was_scanning = tw.fn_scanning; + tw.fn_scanning = fn; + fn.walk(tw); + tw.fn_scanning = was_scanning; + } + + function revisit_fn_def(tw, fn) { + fn.enclosed.forEach(function(d) { + if (fn.variables.get(d.name) === d) return; + if (safe_to_read(tw, d)) return; + d.single_use = false; + var fixed = d.fixed; + if (typeof fixed == "function") fixed = fixed(); + if (fixed instanceof AST_Lambda && fixed.safe_ids !== undefined) return; + d.fixed = false; + }); + } + + function mark_fn_def(tw, def, fn) { + var marker = fn.safe_ids; + if (marker === undefined) return; + if (marker === false) return; + if (fn.parent_scope.resolve().may_call_this === return_true) { + if (member(fn, tw.fn_visited)) revisit_fn_def(tw, fn); + } else if (marker) { + var visited = member(fn, tw.fn_visited); + if (marker === tw.safe_ids) { + if (!visited) walk_fn_def(tw, fn); + } else if (visited) { + revisit_fn_def(tw, fn); + } else { + fn.safe_ids = false; + } + } else if (tw.fn_scanning && tw.fn_scanning !== def.scope.resolve()) { + fn.safe_ids = false; + } else { + fn.safe_ids = tw.safe_ids; + walk_fn_def(tw, fn); + } + } + + function pop_scope(tw, scope) { + var fn_defs = scope.fn_defs; + var tangled = scope.may_call_this === return_true ? fn_defs : fn_defs.filter(function(fn) { + if (fn.safe_ids === false) return true; + fn.safe_ids = tw.safe_ids; + walk_fn_def(tw, fn); + return false; + }); + pop(tw); + tangled.forEach(function(fn) { + fn.safe_ids = tw.safe_ids; + walk_fn_def(tw, fn); + }); + fn_defs.forEach(function(fn) { + fn.safe_ids = undefined; + }); + scope.fn_defs = undefined; + scope.may_call_this = undefined; + } + + function push(tw, sequential) { + var safe_ids = Object.create(tw.safe_ids); + if (!sequential) safe_ids.seq = {}; + tw.safe_ids = safe_ids; + } + + function pop(tw) { + tw.safe_ids = Object.getPrototypeOf(tw.safe_ids); + } + + function mark(tw, def) { + tw.safe_ids[def.id] = {}; + } + + function push_ref(def, ref) { + def.references.push(ref); + if (def.last_ref !== false) def.last_ref = ref; + } + + function safe_to_read(tw, def) { + if (def.single_use == "m") return false; + var safe = tw.safe_ids[def.id]; + if (safe) { + var in_order = HOP(tw.safe_ids, def.id); + if (!in_order) { + var seq = tw.safe_ids.seq; + if (!safe.read) { + safe.read = seq; + } else if (safe.read !== seq) { + safe.read = true; + } + } + if (def.fixed == null) { + if (is_arguments(def)) return false; + if (def.global && def.name == "arguments") return false; + tw.loop_ids[def.id] = null; + def.fixed = make_node(AST_Undefined, def.orig[0]); + if (in_order) def.safe_ids = undefined; + return true; + } + return !safe.assign || safe.assign === tw.safe_ids; + } + return def.fixed instanceof AST_LambdaDefinition; + } + + function safe_to_assign(tw, def, declare) { + if (!declare) { + if (is_funarg(def) && def.scope.uses_arguments && !tw.has_directive("use strict")) return false; + if (!all(def.orig, function(sym) { + return !(sym instanceof AST_SymbolConst); + })) return false; + } + if (def.fixed === undefined) return declare || all(def.orig, function(sym) { + return !(sym instanceof AST_SymbolLet); + }); + if (def.fixed === false || def.fixed === 0) return false; + var safe = tw.safe_ids[def.id]; + if (def.safe_ids) { + def.safe_ids[def.id] = false; + def.safe_ids = undefined; + return def.fixed === null || HOP(tw.safe_ids, def.id) && !safe.read; + } + if (!HOP(tw.safe_ids, def.id)) { + if (!safe) return false; + if (safe.read || tw.in_loop) { + var scope = tw.find_parent(AST_BlockScope); + if (scope instanceof AST_Class) return false; + if (def.scope.resolve() !== scope.resolve()) return false; + } + safe.assign = safe.assign && safe.assign !== tw.safe_ids ? true : tw.safe_ids; + } + if (def.fixed != null && safe.read) { + if (safe.read !== tw.safe_ids.seq) return false; + if (tw.loop_ids[def.id] !== tw.in_loop) return false; + } + return safe_to_read(tw, def) && all(def.orig, function(sym) { + return !(sym instanceof AST_SymbolLambda); + }); + } + + function ref_once(compressor, def) { + return compressor.option("unused") + && !def.scope.pinned() + && def.single_use !== false + && def.references.length - def.recursive_refs == 1 + && !(is_funarg(def) && def.scope.uses_arguments); + } + + function is_immutable(value) { + if (!value) return false; + if (value instanceof AST_Assign) { + var op = value.operator; + return op == "=" ? is_immutable(value.right) : !lazy_op[op.slice(0, -1)]; + } + if (value instanceof AST_Sequence) return is_immutable(value.tail_node()); + return value.is_constant() || is_lambda(value) || value instanceof AST_ObjectIdentity; + } + + function value_in_use(node, parent) { + if (parent instanceof AST_Array) return true; + if (parent instanceof AST_Binary) return lazy_op[parent.operator]; + if (parent instanceof AST_Conditional) return parent.condition !== node; + if (parent instanceof AST_Sequence) return parent.tail_node() === node; + if (parent instanceof AST_Spread) return true; + } + + function mark_escaped(tw, d, scope, node, value, level, depth) { + var parent = tw.parent(level); + if (value && value.is_constant()) return; + if (has_escaped(d, scope, node, parent)) { + d.escaped.push(parent); + if (depth > 1 && !(value && value.is_constant_expression(scope))) depth = 1; + if (!d.escaped.depth || d.escaped.depth > depth) d.escaped.depth = depth; + if (d.scope.resolve() !== scope.resolve()) d.escaped.cross_scope = true; + if (d.fixed) d.fixed.escaped = d.escaped; + return; + } else if (value_in_use(node, parent)) { + mark_escaped(tw, d, scope, parent, parent, level + 1, depth); + } else if (parent instanceof AST_ObjectKeyVal && parent.value === node) { + var obj = tw.parent(level + 1); + mark_escaped(tw, d, scope, obj, obj, level + 2, depth); + } else if (parent instanceof AST_PropAccess && parent.expression === node) { + value = read_property(value, parent); + mark_escaped(tw, d, scope, parent, value, level + 1, depth + 1); + if (value) return; + } + if (level > 0) return; + if (parent instanceof AST_Call && parent.expression === node) return; + if (parent instanceof AST_Sequence && parent.tail_node() !== node) return; + if (parent instanceof AST_SimpleStatement) return; + if (parent instanceof AST_Unary && !unary_side_effects[parent.operator]) return; + d.direct_access = true; + if (d.fixed) d.fixed.direct_access = true; + } + + function mark_assignment_to_arguments(node) { + if (!(node instanceof AST_Sub)) return; + var expr = node.expression; + if (!(expr instanceof AST_SymbolRef)) return; + var def = expr.definition(); + if (!is_arguments(def)) return; + var key = node.property; + if (key.is_constant()) key = key.value; + if (!(key instanceof AST_Node) && !RE_POSITIVE_INTEGER.test(key)) return; + def.reassigned++; + (key instanceof AST_Node ? def.scope.argnames : [ def.scope.argnames[key] ]).forEach(function(argname) { + if (argname instanceof AST_SymbolFunarg) argname.definition().fixed = false; + }); + } + + function make_fixed(save, fn) { + var prev_save, prev_value; + return function() { + var current = save(); + if (prev_save !== current) { + prev_save = current; + prev_value = fn(current); + } + return prev_value; + }; + } + + function make_fixed_default(compressor, node, save) { + var prev_save, prev_seq; + return function() { + if (prev_seq === node) return node; + var current = save(); + var ev = fuzzy_eval(compressor, current, true); + if (ev instanceof AST_Node) { + prev_seq = node; + } else if (prev_save !== current) { + prev_save = current; + prev_seq = ev === undefined ? make_sequence(node, [ current, node.value ]) : current; + } + return prev_seq; + }; + } + + function scan_declaration(tw, compressor, lhs, fixed, visit) { + var scanner = new TreeWalker(function(node) { + if (node instanceof AST_DefaultValue) { + reset_flags(node); + push(tw, true); + node.value.walk(tw); + pop(tw); + var save = fixed; + if (save) fixed = make_fixed_default(compressor, node, save); + node.name.walk(scanner); + fixed = save; + return true; + } + if (node instanceof AST_DestructuredArray) { + reset_flags(node); + var save = fixed; + node.elements.forEach(function(node, index) { + if (node instanceof AST_Hole) return reset_flags(node); + if (save) fixed = make_fixed(save, function(value) { + return make_node(AST_Sub, node, { + expression: value, + property: make_node(AST_Number, node, { value: index }), + }); + }); + node.walk(scanner); + }); + if (node.rest) { + var fixed_node; + if (save) fixed = compressor.option("rests") && make_fixed(save, function(value) { + if (!(value instanceof AST_Array)) return node; + for (var i = 0, len = node.elements.length; i < len; i++) { + if (value.elements[i] instanceof AST_Spread) return node; + } + if (!fixed_node) fixed_node = make_node(AST_Array, node, {}); + fixed_node.elements = value.elements.slice(len); + return fixed_node; + }); + node.rest.walk(scanner); + } + fixed = save; + return true; + } + if (node instanceof AST_DestructuredObject) { + reset_flags(node); + var save = fixed; + node.properties.forEach(function(node) { + reset_flags(node); + if (node.key instanceof AST_Node) { + push(tw); + node.key.walk(tw); + pop(tw); + } + if (save) fixed = make_fixed(save, function(value) { + var key = node.key; + var type = AST_Sub; + if (typeof key == "string") { + if (is_identifier_string(key)) { + type = AST_Dot; + } else { + key = make_node_from_constant(key, node); + } + } + return make_node(type, node, { + expression: value, + property: key, + }); + }); + node.value.walk(scanner); + }); + if (node.rest) { + fixed = false; + node.rest.walk(scanner); + } + fixed = save; + return true; + } + visit(node, fixed, function() { + var save_len = tw.stack.length; + for (var i = 0, len = scanner.stack.length - 1; i < len; i++) { + tw.stack.push(scanner.stack[i]); + } + node.walk(tw); + tw.stack.length = save_len; + }); + return true; + }); + lhs.walk(scanner); + } + + function reduce_iife(tw, descend, compressor) { + var fn = this; + fn.inlined = false; + var iife = tw.parent(); + var sequential = !is_async(fn) && !is_generator(fn); + var hit = !sequential; + var aborts = false; + fn.walk(new TreeWalker(function(node) { + if (hit) return aborts = true; + if (node instanceof AST_Return) return hit = true; + if (node instanceof AST_Scope && node !== fn) return true; + })); + if (aborts) push(tw, sequential); + reset_variables(tw, compressor, fn); + // Virtually turn IIFE parameters into variable definitions: + // (function(a,b) {...})(c,d) ---> (function() {var a=c,b=d; ...})() + // So existing transformation rules can work on them. + var safe = !fn.uses_arguments || tw.has_directive("use strict"); + fn.argnames.forEach(function(argname, i) { + var value = iife.args[i]; + scan_declaration(tw, compressor, argname, function() { + var j = fn.argnames.indexOf(argname); + var arg = j < 0 ? value : iife.args[j]; + if (arg instanceof AST_Sequence && arg.expressions.length < 2) arg = arg.expressions[0]; + return arg || make_node(AST_Undefined, iife); + }, visit); + }); + var rest = fn.rest, fixed_node; + if (rest) scan_declaration(tw, compressor, rest, compressor.option("rests") && function() { + if (fn.rest !== rest) return rest; + if (!fixed_node) fixed_node = make_node(AST_Array, fn, {}); + fixed_node.elements = iife.args.slice(fn.argnames.length); + return fixed_node; + }, visit); + walk_lambda(fn, tw); + var safe_ids = tw.safe_ids; + pop_scope(tw, fn); + if (!aborts) tw.safe_ids = safe_ids; + return true; + + function visit(node, fixed) { + var d = node.definition(); + if (fixed && safe && d.fixed === undefined) { + mark(tw, d); + tw.loop_ids[d.id] = tw.in_loop; + d.fixed = fixed; + d.fixed.assigns = [ node ]; + } else { + d.fixed = false; + } + } + } + + def(AST_Assign, function(tw, descend, compressor) { + var node = this; + var left = node.left; + var right = node.right; + var ld = left instanceof AST_SymbolRef && left.definition(); + var scan = ld || left instanceof AST_Destructured; + switch (node.operator) { + case "=": + if (left.equals(right) && !left.has_side_effects(compressor)) { + right.walk(tw); + walk_prop(left); + node.redundant = true; + return true; + } + if (ld && right instanceof AST_LambdaExpression) { + walk_assign(); + right.parent_scope.resolve().fn_defs.push(right); + right.safe_ids = null; + if (!ld.fixed || !node.write_only) mark_fn_def(tw, ld, right); + return true; + } + if (scan) { + right.walk(tw); + walk_assign(); + return true; + } + mark_assignment_to_arguments(left); + return; + case "&&=": + case "||=": + case "??=": + var lazy = true; + default: + if (!scan) { + mark_assignment_to_arguments(left); + return walk_lazy(); + } + ld.assignments++; + var fixed = ld.fixed; + if (is_modified(compressor, tw, node, node, 0)) { + ld.fixed = false; + return walk_lazy(); + } + var safe = safe_to_read(tw, ld); + if (lazy) push(tw, true); + right.walk(tw); + if (lazy) pop(tw); + if (safe && !left.in_arg && safe_to_assign(tw, ld)) { + push_ref(ld, left); + mark(tw, ld); + if (ld.single_use) ld.single_use = false; + left.fixed = ld.fixed = function() { + return make_node(AST_Binary, node, { + operator: node.operator.slice(0, -1), + left: make_ref(left, fixed), + right: node.right, + }); + }; + left.fixed.assigns = !fixed || !fixed.assigns ? [ ld.orig[0] ] : fixed.assigns.slice(); + left.fixed.assigns.push(node); + left.fixed.to_binary = replace_ref(function(node) { + return node.left; + }, fixed); + } else { + left.walk(tw); + ld.fixed = false; + } + return true; + } + + function walk_prop(lhs) { + reset_flags(lhs); + if (lhs instanceof AST_Dot) { + walk_prop(lhs.expression); + } else if (lhs instanceof AST_Sub) { + walk_prop(lhs.expression); + lhs.property.walk(tw); + } else if (lhs instanceof AST_SymbolRef) { + var d = lhs.definition(); + push_ref(d, lhs); + if (d.fixed) { + lhs.fixed = d.fixed; + if (lhs.fixed.assigns) { + lhs.fixed.assigns.push(node); + } else { + lhs.fixed.assigns = [ node ]; + } + } + } else { + lhs.walk(tw); + } + } + + function walk_assign() { + var recursive = ld && recursive_ref(tw, ld); + var modified = is_modified(compressor, tw, node, right, 0, is_immutable(right), recursive); + scan_declaration(tw, compressor, left, function() { + return node.right; + }, function(sym, fixed, walk) { + if (!(sym instanceof AST_SymbolRef)) { + mark_assignment_to_arguments(sym); + walk(); + return; + } + var d = sym.definition(); + d.assignments++; + if (!fixed || sym.in_arg || !safe_to_assign(tw, d)) { + walk(); + d.fixed = false; + } else { + push_ref(d, sym); + mark(tw, d); + if (left instanceof AST_Destructured + || d.orig.length == 1 && d.orig[0] instanceof AST_SymbolDefun) { + d.single_use = false; + } + tw.loop_ids[d.id] = tw.in_loop; + d.fixed = modified ? 0 : fixed; + sym.fixed = fixed; + sym.fixed.assigns = [ node ]; + mark_escaped(tw, d, sym.scope, node, right, 0, 1); + } + }); + } + + function walk_lazy() { + if (!lazy) return; + left.walk(tw); + push(tw, true); + right.walk(tw); + pop(tw); + return true; + } + }); + def(AST_Binary, function(tw) { + if (!lazy_op[this.operator]) return; + this.left.walk(tw); + push(tw, true); + this.right.walk(tw); + pop(tw); + return true; + }); + def(AST_BlockScope, function(tw, descend, compressor) { + reset_block_variables(tw, compressor, this); + }); + def(AST_Call, function(tw, descend) { + var node = this; + var exp = node.expression; + if (exp instanceof AST_LambdaExpression) { + var iife = is_iife_single(node); + node.args.forEach(function(arg) { + arg.walk(tw); + if (arg instanceof AST_Spread) iife = false; + }); + if (iife) exp.reduce_vars = reduce_iife; + exp.walk(tw); + if (iife) delete exp.reduce_vars; + return true; + } + if (node.TYPE == "Call") switch (tw.in_boolean_context()) { + case "d": + var drop = true; + case true: + mark_refs(exp, drop); + } + exp.walk(tw); + var optional = node.optional; + if (optional) push(tw, true); + node.args.forEach(function(arg) { + arg.walk(tw); + }); + if (optional) pop(tw); + var fixed = exp instanceof AST_SymbolRef && exp.fixed_value(); + if (fixed instanceof AST_Lambda) { + mark_fn_def(tw, exp.definition(), fixed); + } else { + tw.find_parent(AST_Scope).may_call_this(); + } + return true; + + function mark_refs(node, drop) { + if (node instanceof AST_Assign) { + if (node.operator != "=") return; + mark_refs(node.left, drop); + mark_refs(node.right, drop); + } else if (node instanceof AST_Binary) { + if (!lazy_op[node.operator]) return; + mark_refs(node.left, drop); + mark_refs(node.right, drop); + } else if (node instanceof AST_Conditional) { + mark_refs(node.consequent, drop); + mark_refs(node.alternative, drop); + } else if (node instanceof AST_SymbolRef) { + var def = node.definition(); + def.bool_return++; + if (drop) def.drop_return++; + } + } + }); + def(AST_Class, function(tw, descend, compressor) { + var node = this; + reset_block_variables(tw, compressor, node); + if (node.extends) node.extends.walk(tw); + var props = node.properties.filter(function(prop) { + reset_flags(prop); + if (prop.key instanceof AST_Node) { + tw.push(prop); + prop.key.walk(tw); + tw.pop(); + } + return prop.value; + }); + if (node.name) { + var d = node.name.definition(); + var parent = tw.parent(); + if (parent instanceof AST_ExportDeclaration || parent instanceof AST_ExportDefault) d.single_use = false; + if (safe_to_assign(tw, d, true)) { + mark(tw, d); + tw.loop_ids[d.id] = tw.in_loop; + d.fixed = function() { + return node; + }; + d.fixed.assigns = [ node ]; + if (!is_safe_lexical(d)) d.single_use = false; + } else { + d.fixed = false; + } + } + props.forEach(function(prop) { + tw.push(prop); + if (!prop.static || is_static_field_or_init(prop) && prop.value.contains_this()) { + push(tw); + prop.value.walk(tw); + pop(tw); + } else { + prop.value.walk(tw); + } + tw.pop(); + }); + return true; + }); + def(AST_ClassInitBlock, function(tw, descend, compressor) { + var node = this; + push(tw, true); + reset_variables(tw, compressor, node); + descend(); + pop_scope(tw, node); + return true; + }); + def(AST_Conditional, function(tw) { + this.condition.walk(tw); + push(tw, true); + this.consequent.walk(tw); + pop(tw); + push(tw, true); + this.alternative.walk(tw); + pop(tw); + return true; + }); + def(AST_DefaultValue, function(tw) { + push(tw, true); + this.value.walk(tw); + pop(tw); + this.name.walk(tw); + return true; + }); + def(AST_Do, function(tw) { + var save_loop = tw.in_loop; + tw.in_loop = this; + push(tw); + this.body.walk(tw); + if (has_loop_control(this, tw.parent())) { + pop(tw); + push(tw); + } + this.condition.walk(tw); + pop(tw); + tw.in_loop = save_loop; + return true; + }); + def(AST_For, function(tw, descend, compressor) { + var node = this; + reset_block_variables(tw, compressor, node); + if (node.init) node.init.walk(tw); + var save_loop = tw.in_loop; + tw.in_loop = node; + push(tw); + if (node.condition) node.condition.walk(tw); + node.body.walk(tw); + if (node.step) { + if (has_loop_control(node, tw.parent())) { + pop(tw); + push(tw); + } + node.step.walk(tw); + } + pop(tw); + tw.in_loop = save_loop; + return true; + }); + def(AST_ForEnumeration, function(tw, descend, compressor) { + var node = this; + reset_block_variables(tw, compressor, node); + node.object.walk(tw); + var save_loop = tw.in_loop; + tw.in_loop = node; + push(tw); + var init = node.init; + if (init instanceof AST_Definitions) { + init.definitions[0].name.mark_symbol(function(node) { + if (node instanceof AST_SymbolDeclaration) { + var def = node.definition(); + def.assignments++; + def.fixed = false; + } + }, tw); + } else if (init instanceof AST_Destructured || init instanceof AST_SymbolRef) { + init.mark_symbol(function(node) { + if (node instanceof AST_SymbolRef) { + var def = node.definition(); + push_ref(def, node); + def.assignments++; + if (!node.is_immutable()) def.fixed = false; + } + }, tw); + } else { + init.walk(tw); + } + node.body.walk(tw); + pop(tw); + tw.in_loop = save_loop; + return true; + }); + def(AST_If, function(tw) { + this.condition.walk(tw); + push(tw, true); + this.body.walk(tw); + pop(tw); + if (this.alternative) { + push(tw, true); + this.alternative.walk(tw); + pop(tw); + } + return true; + }); + def(AST_LabeledStatement, function(tw) { + push(tw, true); + this.body.walk(tw); + pop(tw); + return true; + }); + def(AST_Lambda, function(tw, descend, compressor) { + var fn = this; + if (!safe_to_visit(tw, fn)) return true; + if (!push_uniq(tw.fn_visited, fn)) return true; + fn.inlined = false; + push(tw); + reset_variables(tw, compressor, fn); + descend(); + pop_scope(tw, fn); + if (fn.name) mark_escaped(tw, fn.name.definition(), fn, fn.name, fn, 0, 1); + return true; + }); + def(AST_LambdaDefinition, function(tw, descend, compressor) { + var fn = this; + var def = fn.name.definition(); + var parent = tw.parent(); + if (parent instanceof AST_ExportDeclaration || parent instanceof AST_ExportDefault) def.single_use = false; + if (!safe_to_visit(tw, fn)) return true; + if (!push_uniq(tw.fn_visited, fn)) return true; + fn.inlined = false; + push(tw); + reset_variables(tw, compressor, fn); + descend(); + pop_scope(tw, fn); + return true; + }); + def(AST_Sub, function(tw) { + if (!this.optional) return; + this.expression.walk(tw); + push(tw, true); + this.property.walk(tw); + pop(tw); + return true; + }); + def(AST_Switch, function(tw, descend, compressor) { + var node = this; + reset_block_variables(tw, compressor, node); + node.expression.walk(tw); + var first = true; + node.body.forEach(function(branch) { + if (branch instanceof AST_Default) return; + branch.expression.walk(tw); + if (first) { + first = false; + push(tw, true); + } + }) + if (!first) pop(tw); + walk_body(node, tw); + return true; + }); + def(AST_SwitchBranch, function(tw) { + push(tw, true); + walk_body(this, tw); + pop(tw); + return true; + }); + def(AST_SymbolCatch, function() { + this.definition().fixed = false; + }); + def(AST_SymbolImport, function() { + this.definition().fixed = false; + }); + def(AST_SymbolRef, function(tw, descend, compressor) { + var ref = this; + var d = ref.definition(); + var fixed = d.fixed || d.last_ref && d.last_ref.fixed; + push_ref(d, ref); + if (d.references.length == 1 && !d.fixed && d.orig[0] instanceof AST_SymbolDefun) { + tw.loop_ids[d.id] = tw.in_loop; + } + var recursive = recursive_ref(tw, d); + if (recursive) recursive.enclosed.forEach(function(def) { + if (d === def) return; + if (def.scope.resolve() === recursive) return; + var assigns = def.fixed && def.fixed.assigns; + if (!assigns) return; + if (assigns[assigns.length - 1] instanceof AST_VarDef) return; + var safe = tw.safe_ids[def.id]; + if (!safe) return; + safe.assign = true; + }); + if (d.single_use == "m" && d.fixed) { + d.fixed = 0; + d.single_use = false; + } + switch (d.fixed) { + case 0: + if (!safe_to_read(tw, d)) d.fixed = false; + case false: + var redef = d.redefined(); + if (redef && cross_scope(d.scope, ref.scope)) redef.single_use = false; + break; + case undefined: + d.fixed = false; + break; + default: + if (!safe_to_read(tw, d)) { + d.fixed = false; + break; + } + if (ref.in_arg && d.orig[0] instanceof AST_SymbolLambda) ref.fixed = d.scope; + var value = ref.fixed_value(); + if (recursive) { + d.recursive_refs++; + } else if (value && ref_once(compressor, d)) { + d.in_loop = tw.loop_ids[d.id] !== tw.in_loop; + d.single_use = is_lambda(value) + && !value.pinned() + && (!d.in_loop || tw.parent() instanceof AST_Call) + || !d.in_loop + && d.scope === ref.scope.resolve() + && value.is_constant_expression(); + } else { + d.single_use = false; + } + if (is_modified(compressor, tw, ref, value, 0, is_immutable(value), recursive)) { + if (d.single_use) { + d.single_use = "m"; + } else { + d.fixed = 0; + } + } + if (d.fixed && tw.loop_ids[d.id] !== tw.in_loop) d.cross_loop = true; + mark_escaped(tw, d, ref.scope, ref, value, 0, 1); + break; + } + if (!ref.fixed) ref.fixed = d.fixed === 0 ? fixed : d.fixed; + var parent; + if (value instanceof AST_Lambda + && !((parent = tw.parent()) instanceof AST_Call && parent.expression === ref)) { + mark_fn_def(tw, d, value); + } + }); + def(AST_Template, function(tw, descend) { + var node = this; + var tag = node.tag; + if (!tag) return; + if (tag instanceof AST_LambdaExpression) { + node.expressions.forEach(function(exp) { + exp.walk(tw); + }); + tag.walk(tw); + return true; + } + tag.walk(tw); + node.expressions.forEach(function(exp) { + exp.walk(tw); + }); + var fixed = tag instanceof AST_SymbolRef && tag.fixed_value(); + if (fixed instanceof AST_Lambda) { + mark_fn_def(tw, tag.definition(), fixed); + } else { + tw.find_parent(AST_Scope).may_call_this(); + } + return true; + }); + def(AST_Toplevel, function(tw, descend, compressor) { + var node = this; + node.globals.each(function(def) { + reset_def(tw, compressor, def); + }); + push(tw, true); + reset_variables(tw, compressor, node); + descend(); + pop_scope(tw, node); + return true; + }); + def(AST_Try, function(tw, descend, compressor) { + var node = this; + reset_block_variables(tw, compressor, node); + push(tw, true); + walk_body(node, tw); + pop(tw); + if (node.bcatch) { + push(tw, true); + node.bcatch.walk(tw); + pop(tw); + } + if (node.bfinally) node.bfinally.walk(tw); + return true; + }); + def(AST_Unary, function(tw, descend) { + var node = this; + if (!UNARY_POSTFIX[node.operator]) return; + var exp = node.expression; + if (!(exp instanceof AST_SymbolRef)) { + mark_assignment_to_arguments(exp); + return; + } + var d = exp.definition(); + d.assignments++; + var fixed = d.fixed; + if (safe_to_read(tw, d) && !exp.in_arg && safe_to_assign(tw, d)) { + push_ref(d, exp); + mark(tw, d); + if (d.single_use) d.single_use = false; + d.fixed = function() { + return make_node(AST_Binary, node, { + operator: node.operator.slice(0, -1), + left: make_node(AST_UnaryPrefix, node, { + operator: "+", + expression: make_ref(exp, fixed), + }), + right: make_node(AST_Number, node, { value: 1 }), + }); + }; + d.fixed.assigns = fixed && fixed.assigns ? fixed.assigns.slice() : []; + d.fixed.assigns.push(node); + if (node instanceof AST_UnaryPrefix) { + exp.fixed = d.fixed; + } else { + exp.fixed = function() { + return make_node(AST_UnaryPrefix, node, { + operator: "+", + expression: make_ref(exp, fixed), + }); + }; + exp.fixed.assigns = fixed && fixed.assigns; + exp.fixed.to_prefix = replace_ref(function(node) { + return node.expression; + }, d.fixed); + } + } else { + exp.walk(tw); + d.fixed = false; + } + return true; + }); + def(AST_VarDef, function(tw, descend, compressor) { + var node = this; + var value = node.value; + if (value instanceof AST_LambdaExpression && node.name instanceof AST_SymbolDeclaration) { + walk_defn(); + value.parent_scope.resolve().fn_defs.push(value); + value.safe_ids = null; + var ld = node.name.definition(); + if (!ld.fixed) mark_fn_def(tw, ld, value); + } else if (value) { + value.walk(tw); + walk_defn(); + } else if (tw.parent() instanceof AST_Let) { + walk_defn(); + } + return true; + + function walk_defn() { + scan_declaration(tw, compressor, node.name, function() { + return node.value || make_node(AST_Undefined, node); + }, function(name, fixed) { + var d = name.definition(); + if (fixed && safe_to_assign(tw, d, true)) { + mark(tw, d); + tw.loop_ids[d.id] = tw.in_loop; + d.fixed = fixed; + d.fixed.assigns = [ node ]; + if (name instanceof AST_SymbolConst && d.redefined() + || !(can_drop_symbol(name) || is_safe_lexical(d))) { + d.single_use = false; + } + } else { + d.fixed = false; + } + }); + } + }); + def(AST_While, function(tw, descend) { + var save_loop = tw.in_loop; + tw.in_loop = this; + push(tw); + descend(); + pop(tw); + tw.in_loop = save_loop; + return true; + }); + })(function(node, func) { + node.DEFMETHOD("reduce_vars", func); + }); + + function reset_flags(node) { + node._squeezed = false; + node._optimized = false; + if (node instanceof AST_BlockScope) node._var_names = undefined; + if (node instanceof AST_SymbolRef) node.fixed = undefined; + } + + AST_Toplevel.DEFMETHOD("reset_opt_flags", function(compressor) { + var tw = new TreeWalker(compressor.option("reduce_vars") ? function(node, descend) { + reset_flags(node); + return node.reduce_vars(tw, descend, compressor); + } : reset_flags); + // Flow control for visiting lambda definitions + tw.fn_scanning = null; + tw.fn_visited = []; + // Record the loop body in which `AST_SymbolDeclaration` is first encountered + tw.in_loop = null; + tw.loop_ids = Object.create(null); + // Stack of look-up tables to keep track of whether a `SymbolDef` has been + // properly assigned before use: + // - `push()` & `pop()` when visiting conditional branches + // - backup & restore via `save_ids` when visiting out-of-order sections + tw.safe_ids = Object.create(null); + tw.safe_ids.seq = {}; + this.walk(tw); + }); + + AST_Symbol.DEFMETHOD("fixed_value", function(ref_only) { + var def = this.definition(); + var fixed = def.fixed; + if (fixed) { + if (this.fixed) fixed = this.fixed; + return (fixed instanceof AST_Node ? fixed : fixed()).tail_node(); + } + fixed = fixed === 0 && this.fixed; + if (!fixed) return fixed; + var value = (fixed instanceof AST_Node ? fixed : fixed()).tail_node(); + if (ref_only && def.escaped.depth != 1 && is_object(value, true)) return value; + if (value.is_constant()) return value; + }); + + AST_SymbolRef.DEFMETHOD("is_immutable", function() { + var def = this.redef || this.definition(); + if (!(def.orig[0] instanceof AST_SymbolLambda)) return false; + if (def.orig.length == 1) return true; + if (!this.in_arg) return false; + return !(def.orig[1] instanceof AST_SymbolFunarg); + }); + + AST_Node.DEFMETHOD("convert_symbol", noop); + function convert_destructured(type, process) { + return this.transform(new TreeTransformer(function(node, descend) { + if (node instanceof AST_DefaultValue) { + node = node.clone(); + node.name = node.name.transform(this); + return node; + } + if (node instanceof AST_Destructured) { + node = node.clone(); + descend(node, this); + return node; + } + if (node instanceof AST_DestructuredKeyVal) { + node = node.clone(); + node.value = node.value.transform(this); + return node; + } + return node.convert_symbol(type, process); + })); + } + AST_DefaultValue.DEFMETHOD("convert_symbol", convert_destructured); + AST_Destructured.DEFMETHOD("convert_symbol", convert_destructured); + function convert_symbol(type, process) { + var node = make_node(type, this); + return process(node, this) || node; + } + AST_SymbolDeclaration.DEFMETHOD("convert_symbol", convert_symbol); + AST_SymbolRef.DEFMETHOD("convert_symbol", convert_symbol); + + function process_to_assign(ref) { + var def = ref.definition(); + def.assignments++; + def.references.push(ref); + } + + function mark_destructured(process, tw) { + var marker = new TreeWalker(function(node) { + if (node instanceof AST_DefaultValue) { + node.value.walk(tw); + node.name.walk(marker); + return true; + } + if (node instanceof AST_DestructuredKeyVal) { + if (node.key instanceof AST_Node) node.key.walk(tw); + node.value.walk(marker); + return true; + } + return process(node); + }); + this.walk(marker); + } + AST_DefaultValue.DEFMETHOD("mark_symbol", mark_destructured); + AST_Destructured.DEFMETHOD("mark_symbol", mark_destructured); + function mark_symbol(process) { + return process(this); + } + AST_SymbolDeclaration.DEFMETHOD("mark_symbol", mark_symbol); + AST_SymbolRef.DEFMETHOD("mark_symbol", mark_symbol); + + AST_Node.DEFMETHOD("match_symbol", function(predicate) { + return predicate(this); + }); + function match_destructured(predicate, ignore_side_effects) { + var found = false; + var tw = new TreeWalker(function(node) { + if (found) return true; + if (node instanceof AST_DefaultValue) { + if (!ignore_side_effects) return found = true; + node.name.walk(tw); + return true; + } + if (node instanceof AST_DestructuredKeyVal) { + if (!ignore_side_effects && node.key instanceof AST_Node) return found = true; + node.value.walk(tw); + return true; + } + if (predicate(node)) return found = true; + }); + this.walk(tw); + return found; + } + AST_DefaultValue.DEFMETHOD("match_symbol", match_destructured); + AST_Destructured.DEFMETHOD("match_symbol", match_destructured); + + function in_async_generator(scope) { + return scope instanceof AST_AsyncGeneratorDefun || scope instanceof AST_AsyncGeneratorFunction; + } + + function find_scope(compressor) { + var level = 0, node = compressor.self(); + do { + if (node.variables) return node; + } while (node = compressor.parent(level++)); + } + + function find_try(compressor, level, node, scope, may_throw, sync) { + for (var parent; parent = compressor.parent(level++); node = parent) { + if (parent === scope) return false; + if (sync && parent instanceof AST_Lambda) { + if (parent.name || is_async(parent) || is_generator(parent)) return true; + } else if (parent instanceof AST_Try) { + if (parent.bfinally && parent.bfinally !== node) return true; + if (may_throw && parent.bcatch && parent.bcatch !== node) return true; + } + } + return false; + } + + var identifier_atom = makePredicate("Infinity NaN undefined"); + function is_lhs_read_only(lhs, compressor) { + if (lhs instanceof AST_Atom) return true; + if (lhs instanceof AST_ObjectIdentity) return true; + if (lhs instanceof AST_PropAccess) { + if (lhs.property === "__proto__") return true; + lhs = lhs.expression; + if (lhs instanceof AST_SymbolRef) { + if (lhs.is_immutable()) return false; + lhs = lhs.fixed_value(); + } + if (!lhs) return true; + if (lhs.tail_node().is_constant()) return true; + return is_lhs_read_only(lhs, compressor); + } + if (lhs instanceof AST_SymbolRef) { + if (lhs.is_immutable()) return true; + var def = lhs.definition(); + return compressor.exposed(def) && identifier_atom[def.name]; + } + return false; + } + + function make_node(ctor, orig, props) { + if (props) { + props.start = orig.start; + props.end = orig.end; + } else { + props = orig; + } + return new ctor(props); + } + + function make_sequence(orig, expressions) { + if (expressions.length == 1) return expressions[0]; + return make_node(AST_Sequence, orig, { expressions: expressions.reduce(merge_sequence, []) }); + } + + function make_node_from_constant(val, orig) { + switch (typeof val) { + case "string": + return make_node(AST_String, orig, { value: val }); + case "number": + if (isNaN(val)) return make_node(AST_NaN, orig); + if (isFinite(val)) { + return 1 / val < 0 ? make_node(AST_UnaryPrefix, orig, { + operator: "-", + expression: make_node(AST_Number, orig, { value: -val }), + }) : make_node(AST_Number, orig, { value: val }); + } + return val < 0 ? make_node(AST_UnaryPrefix, orig, { + operator: "-", + expression: make_node(AST_Infinity, orig), + }) : make_node(AST_Infinity, orig); + case "boolean": + return make_node(val ? AST_True : AST_False, orig); + case "undefined": + return make_node(AST_Undefined, orig); + default: + if (val === null) { + return make_node(AST_Null, orig); + } + if (val instanceof RegExp) { + return make_node(AST_RegExp, orig, { value: val }); + } + throw new Error(string_template("Can't handle constant of type: {type}", { type: typeof val })); + } + } + + function needs_unbinding(val) { + return val instanceof AST_PropAccess + || is_undeclared_ref(val) && val.name == "eval"; + } + + // we shouldn't compress (1,func)(something) to + // func(something) because that changes the meaning of + // the func (becomes lexical instead of global). + function maintain_this_binding(parent, orig, val) { + var wrap = false; + if (parent.TYPE == "Call") { + wrap = parent.expression === orig && needs_unbinding(val); + } else if (parent instanceof AST_Template) { + wrap = parent.tag === orig && needs_unbinding(val); + } else if (parent instanceof AST_UnaryPrefix) { + wrap = parent.operator == "delete" + || parent.operator == "typeof" && is_undeclared_ref(val); + } + return wrap ? make_sequence(orig, [ make_node(AST_Number, orig, { value: 0 }), val ]) : val; + } + + function merge_expression(base, target) { + var fixed_by_id = new Dictionary(); + base.walk(new TreeWalker(function(node) { + if (!(node instanceof AST_SymbolRef)) return; + var def = node.definition(); + var fixed = node.fixed; + if (!fixed || !fixed_by_id.has(def.id)) { + fixed_by_id.set(def.id, fixed); + } else if (fixed_by_id.get(def.id) !== fixed) { + fixed_by_id.set(def.id, false); + } + })); + if (fixed_by_id.size() > 0) target.walk(new TreeWalker(function(node) { + if (!(node instanceof AST_SymbolRef)) return; + var def = node.definition(); + var fixed = node.fixed; + if (!fixed || !fixed_by_id.has(def.id)) return; + if (fixed_by_id.get(def.id) !== fixed) node.fixed = false; + })); + return target; + } + + function merge_sequence(array, node) { + if (node instanceof AST_Sequence) { + [].push.apply(array, node.expressions); + } else { + array.push(node); + } + return array; + } + + function is_lexical_definition(stat) { + return stat instanceof AST_Const || stat instanceof AST_DefClass || stat instanceof AST_Let; + } + + function safe_to_trim(stat) { + if (stat instanceof AST_LambdaDefinition) { + var def = stat.name.definition(); + var scope = stat.name.scope; + return def.scope === scope || all(def.references, function(ref) { + var s = ref.scope; + do { + if (s === scope) return true; + } while (s = s.parent_scope); + }); + } + return !is_lexical_definition(stat); + } + + function as_statement_array(thing) { + if (thing === null) return []; + if (thing instanceof AST_BlockStatement) return all(thing.body, safe_to_trim) ? thing.body : [ thing ]; + if (thing instanceof AST_EmptyStatement) return []; + if (is_statement(thing)) return [ thing ]; + throw new Error("Can't convert thing to statement array"); + } + + function is_empty(thing) { + if (thing === null) return true; + if (thing instanceof AST_EmptyStatement) return true; + if (thing instanceof AST_BlockStatement) return thing.body.length == 0; + return false; + } + + function has_declarations_only(block) { + return all(block.body, function(stat) { + return is_empty(stat) + || stat instanceof AST_Defun + || stat instanceof AST_Var && declarations_only(stat); + }); + } + + function loop_body(x) { + if (x instanceof AST_IterationStatement) { + return x.body instanceof AST_BlockStatement ? x.body : x; + } + return x; + } + + function is_iife_call(node) { + if (node.TYPE != "Call") return false; + do { + node = node.expression; + } while (node instanceof AST_PropAccess); + return node instanceof AST_LambdaExpression ? !is_arrow(node) : is_iife_call(node); + } + + function is_iife_single(call) { + var exp = call.expression; + if (exp.name) return false; + if (!(call instanceof AST_New)) return true; + var found = false; + exp.walk(new TreeWalker(function(node) { + if (found) return true; + if (node instanceof AST_NewTarget) return found = true; + if (node instanceof AST_Scope && node !== exp) return true; + })); + return !found; + } + + function is_undeclared_ref(node) { + return node instanceof AST_SymbolRef && node.definition().undeclared; + } + + var global_names = makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Map Math Number parseFloat parseInt RangeError ReferenceError RegExp Object Set setInterval setTimeout String SyntaxError TypeError unescape URIError WeakMap WeakSet"); + AST_SymbolRef.DEFMETHOD("is_declared", function(compressor) { + return this.defined + || !this.definition().undeclared + || compressor.option("unsafe") && global_names[this.name]; + }); + + function is_static_field_or_init(prop) { + return prop.static && prop.value && (prop instanceof AST_ClassField || prop instanceof AST_ClassInit); + } + + function declarations_only(node) { + return all(node.definitions, function(var_def) { + return !var_def.value; + }); + } + + function is_declaration(stat, lexical) { + if (stat instanceof AST_DefClass) return lexical && !stat.extends && all(stat.properties, function(prop) { + if (prop.key instanceof AST_Node) return false; + return !is_static_field_or_init(prop); + }); + if (stat instanceof AST_Definitions) return (lexical || stat instanceof AST_Var) && declarations_only(stat); + if (stat instanceof AST_ExportDeclaration) return is_declaration(stat.body, lexical); + if (stat instanceof AST_ExportDefault) return is_declaration(stat.body, lexical); + return stat instanceof AST_LambdaDefinition; + } + + function is_last_statement(body, stat) { + var index = body.lastIndexOf(stat); + if (index < 0) return false; + while (++index < body.length) { + if (!is_declaration(body[index], true)) return false; + } + return true; + } + + // Certain combination of unused name + side effect leads to invalid AST: + // https://github.com/mishoo/UglifyJS/issues/44 + // https://github.com/mishoo/UglifyJS/issues/1838 + // https://github.com/mishoo/UglifyJS/issues/3371 + // We fix it at this stage by moving the `var` outside the `for`. + function patch_for_init(node, in_list) { + var block; + if (node.init instanceof AST_BlockStatement) { + block = node.init; + node.init = block.body.pop(); + block.body.push(node); + } + if (node.init instanceof AST_Defun) { + if (!block) block = make_node(AST_BlockStatement, node, { body: [ node ] }); + block.body.splice(-1, 0, node.init); + node.init = null; + } else if (node.init instanceof AST_SimpleStatement) { + node.init = node.init.body; + } else if (is_empty(node.init)) { + node.init = null; + } + if (!block) return; + return in_list ? List.splice(block.body) : block; + } + + function tighten_body(statements, compressor) { + var in_lambda = last_of(compressor, function(node) { + return node instanceof AST_Lambda; + }); + var block_scope, iife_in_try, in_iife_single, in_loop, in_try, scope; + find_loop_scope_try(); + var changed, last_changed, max_iter = 10; + do { + last_changed = changed; + changed = 0; + if (eliminate_spurious_blocks(statements)) changed = 1; + if (!changed && last_changed == 1) break; + if (compressor.option("dead_code")) { + if (eliminate_dead_code(statements, compressor)) changed = 2; + if (!changed && last_changed == 2) break; + } + if (compressor.option("if_return")) { + if (handle_if_return(statements, compressor)) changed = 3; + if (!changed && last_changed == 3) break; + } + if (compressor.option("awaits") && compressor.option("side_effects")) { + if (trim_awaits(statements, compressor)) changed = 4; + if (!changed && last_changed == 4) break; + } + if (compressor.option("inline") >= 4) { + if (inline_iife(statements, compressor)) changed = 5; + if (!changed && last_changed == 5) break; + } + if (compressor.sequences_limit > 0) { + if (sequencesize(statements, compressor)) changed = 6; + if (!changed && last_changed == 6) break; + if (sequencesize_2(statements, compressor)) changed = 7; + if (!changed && last_changed == 7) break; + } + if (compressor.option("join_vars")) { + if (join_consecutive_vars(statements)) changed = 8; + if (!changed && last_changed == 8) break; + } + if (compressor.option("collapse_vars")) { + if (collapse(statements, compressor)) changed = 9; + } + } while (changed && max_iter-- > 0); + return statements; + + function last_of(compressor, predicate) { + var block = compressor.self(), level = 0, stat; + do { + if (block instanceof AST_Catch) { + block = compressor.parent(level++); + } else if (block instanceof AST_LabeledStatement) { + block = block.body; + } else if (block instanceof AST_SwitchBranch) { + var branches = compressor.parent(level); + if (branches.body[branches.body.length - 1] === block || has_break(block.body)) { + level++; + block = branches; + } + } + do { + stat = block; + if (predicate(stat)) return stat; + block = compressor.parent(level++); + } while (block instanceof AST_If); + } while (stat + && (block instanceof AST_BlockStatement + || block instanceof AST_Catch + || block instanceof AST_Scope + || block instanceof AST_SwitchBranch + || block instanceof AST_Try) + && is_last_statement(block.body, stat)); + + function has_break(stats) { + for (var i = stats.length; --i >= 0;) { + if (stats[i] instanceof AST_Break) return true; + } + return false; + } + } + + function find_loop_scope_try() { + var node = compressor.self(), level = 0; + do { + if (!block_scope && node.variables) block_scope = node; + if (node instanceof AST_Catch) { + if (compressor.parent(level).bfinally) { + if (!in_try) in_try = {}; + in_try.bfinally = true; + } + level++; + } else if (node instanceof AST_Finally) { + level++; + } else if (node instanceof AST_IterationStatement) { + in_loop = true; + } else if (node instanceof AST_Scope) { + scope = node; + break; + } else if (node instanceof AST_Try) { + if (!in_try) in_try = {}; + if (node.bcatch) in_try.bcatch = true; + if (node.bfinally) in_try.bfinally = true; + } + } while (node = compressor.parent(level++)); + } + + // Search from right to left for assignment-like expressions: + // - `var a = x;` + // - `a = x;` + // - `++a` + // For each candidate, scan from left to right for first usage, then try + // to fold assignment into the site for compression. + // Will not attempt to collapse assignments into or past code blocks + // which are not sequentially executed, e.g. loops and conditionals. + function collapse(statements, compressor) { + if (scope.pinned()) return; + var args; + var assignments = new Dictionary(); + var candidates = []; + var changed = false; + var declare_only = new Dictionary(); + var force_single; + var stat_index = statements.length; + var scanner = new TreeTransformer(function(node, descend) { + if (abort) return node; + // Skip nodes before `candidate` as quickly as possible + if (!hit) { + if (node !== hit_stack[hit_index]) return node; + hit_index++; + if (hit_index < hit_stack.length) return handle_custom_scan_order(node, scanner); + hit = true; + stop_after = (value_def ? find_stop_value : find_stop)(node, 0); + if (stop_after === node) abort = true; + return node; + } + var parent = scanner.parent(); + // Stop only if candidate is found within conditional branches + if (!stop_if_hit && in_conditional(node, parent)) { + stop_if_hit = parent; + } + // Cascade compound assignments + if (compound && scan_lhs && can_replace && !stop_if_hit + && node instanceof AST_Assign && node.operator != "=" && node.left.equals(lhs)) { + replaced++; + changed = true; + AST_Node.info("Cascading {this} [{start}]", node); + can_replace = false; + lvalues = get_lvalues(lhs); + node.right.transform(scanner); + clear_write_only(candidate); + var folded; + if (abort) { + folded = candidate; + } else { + abort = true; + folded = make_node(AST_Binary, candidate, { + operator: compound, + left: lhs.fixed && lhs.definition().fixed ? lhs.fixed.to_binary(candidate) : lhs, + right: rvalue, + }); + } + return make_node(AST_Assign, node, { + operator: "=", + left: node.left, + right: make_node(AST_Binary, node, { + operator: node.operator.slice(0, -1), + left: folded, + right: node.right, + }), + }); + } + // Stop immediately if these node types are encountered + if (should_stop(node, parent)) { + abort = true; + return node; + } + // Skip transient nodes caused by single-use variable replacement + if (node.single_use) return node; + // Replace variable with assignment when found + var hit_rhs; + if (!(node instanceof AST_SymbolDeclaration) + && (scan_lhs && lhs.equals(node) + || scan_rhs && (hit_rhs = scan_rhs(node, this)))) { + if (!can_replace || stop_if_hit && (hit_rhs || !lhs_local || !replace_all)) { + if (!hit_rhs && !value_def) abort = true; + return node; + } + if (is_lhs(node, parent)) { + if (value_def && !hit_rhs) assign_used = true; + return node; + } + if (!hit_rhs && verify_ref && node.fixed !== lhs.fixed) { + abort = true; + return node; + } + if (value_def) { + if (stop_if_hit && assign_pos == 0) assign_pos = remaining - replaced; + if (!hit_rhs) replaced++; + return node; + } + replaced++; + changed = abort = true; + AST_Node.info("Collapsing {this} [{start}]", node); + if (candidate.TYPE == "Binary") { + update_symbols(candidate, node); + return make_node(AST_Assign, candidate, { + operator: "=", + left: candidate.right.left, + right: candidate.operator == "&&" ? make_node(AST_Conditional, candidate, { + condition: candidate.left, + consequent: candidate.right.right, + alternative: node, + }) : make_node(AST_Conditional, candidate, { + condition: candidate.left, + consequent: node, + alternative: candidate.right.right, + }), + }); + } + if (candidate instanceof AST_UnaryPostfix) return make_node(AST_UnaryPrefix, candidate, { + operator: candidate.operator, + expression: lhs.fixed && lhs.definition().fixed ? lhs.fixed.to_prefix(candidate) : lhs, + }); + if (candidate instanceof AST_UnaryPrefix) { + clear_write_only(candidate); + return candidate; + } + update_symbols(rvalue, node); + if (candidate instanceof AST_VarDef) { + var def = candidate.name.definition(); + if (def.references.length - def.replaced == 1 && !compressor.exposed(def)) { + def.replaced++; + return maintain_this_binding(parent, node, rvalue); + } + return make_node(AST_Assign, candidate, { + operator: "=", + left: node, + right: rvalue, + }); + } + clear_write_only(rvalue); + var assign = candidate.clone(); + assign.right = rvalue; + return assign; + } + // Stop signals related to AST_SymbolRef + if (should_stop_ref(node, parent)) { + abort = true; + return node; + } + // These node types have child nodes that execute sequentially, + // but are otherwise not safe to scan into or beyond them. + if (is_last_node(node, parent) || may_throw(node)) { + stop_after = node; + if (node instanceof AST_Scope) abort = true; + } + // Scan but don't replace inside getter/setter + if (node instanceof AST_Accessor) { + var replace = can_replace; + can_replace = false; + descend(node, scanner); + can_replace = replace; + return signal_abort(node); + } + // Scan but don't replace inside destructuring expression + if (node instanceof AST_Destructured) { + var replace = can_replace; + can_replace = false; + descend(node, scanner); + can_replace = replace; + return signal_abort(node); + } + // Scan but don't replace inside default value + if (node instanceof AST_DefaultValue) { + node.name = node.name.transform(scanner); + var replace = can_replace; + can_replace = false; + node.value = node.value.transform(scanner); + can_replace = replace; + return signal_abort(node); + } + // Scan but don't replace inside block scope with colliding variable + if (node instanceof AST_BlockScope + && !(node instanceof AST_Scope) + && !(node.variables && node.variables.all(function(def) { + return !enclosed.has(def.name) && !lvalues.has(def.name); + }))) { + var replace = can_replace; + can_replace = false; + if (!handle_custom_scan_order(node, scanner)) descend(node, scanner); + can_replace = replace; + return signal_abort(node); + } + if (handle_custom_scan_order(node, scanner)) return signal_abort(node); + }, signal_abort); + var multi_replacer = new TreeTransformer(function(node) { + if (abort) return node; + // Skip nodes before `candidate` as quickly as possible + if (!hit) { + if (node !== hit_stack[hit_index]) return node; + hit_index++; + switch (hit_stack.length - hit_index) { + case 0: + hit = true; + if (assign_used) return node; + if (node !== candidate) return node; + if (node instanceof AST_VarDef) return node; + def.replaced++; + var parent = multi_replacer.parent(); + if (parent instanceof AST_Sequence && parent.tail_node() !== node) { + value_def.replaced++; + if (rvalue === rhs_value) return List.skip; + return make_sequence(rhs_value, rhs_value.expressions.slice(0, -1)); + } + return rvalue; + case 1: + if (!assign_used && node.body === candidate) { + hit = true; + def.replaced++; + value_def.replaced++; + return null; + } + default: + return handle_custom_scan_order(node, multi_replacer); + } + } + // Replace variable when found + if (node instanceof AST_SymbolRef && node.definition() === def) { + if (is_lhs(node, multi_replacer.parent())) return node; + if (!--replaced) abort = true; + AST_Node.info("Replacing {this} [{start}]", node); + var ref = rvalue.clone(); + ref.scope = node.scope; + ref.reference(); + if (replaced == assign_pos) { + abort = true; + return make_node(AST_Assign, candidate, { + operator: "=", + left: node, + right: ref, + }); + } + def.replaced++; + return ref; + } + // Skip (non-executed) functions and (leading) default case in switch statements + if (node instanceof AST_Default || node instanceof AST_Scope) return node; + }, function(node) { + return patch_sequence(node, multi_replacer); + }); + while (--stat_index >= 0) { + // Treat parameters as collapsible in IIFE, i.e. + // function(a, b){ ... }(x()); + // would be translated into equivalent assignments: + // var a = x(), b = undefined; + if (stat_index == 0 && compressor.option("unused")) extract_args(); + // Find collapsible assignments + var hit_stack = []; + extract_candidates(statements[stat_index]); + while (candidates.length > 0) { + hit_stack = candidates.pop(); + var hit_index = 0; + var candidate = hit_stack[hit_stack.length - 1]; + var assign_pos = -1; + var assign_used = false; + var verify_ref = false; + var remaining; + var value_def = null; + var stop_after = null; + var stop_if_hit = null; + var lhs = get_lhs(candidate); + var side_effects = lhs && lhs.has_side_effects(compressor); + var scan_lhs = lhs && (!side_effects || lhs instanceof AST_SymbolRef) + && !is_lhs_read_only(lhs, compressor); + var scan_rhs = foldable(candidate); + if (!scan_lhs && !scan_rhs) continue; + var compound = candidate instanceof AST_Assign && candidate.operator.slice(0, -1); + var funarg = candidate.name instanceof AST_SymbolFunarg; + var may_throw = return_false; + if (candidate.may_throw(compressor)) { + if (funarg && is_async(scope)) continue; + may_throw = in_try ? function(node) { + return node.has_side_effects(compressor); + } : side_effects_external; + } + var read_toplevel = false; + var modify_toplevel = false; + // Locate symbols which may execute code outside of scanning range + var enclosed = new Dictionary(); + var well_defined = true; + var lvalues = get_lvalues(candidate); + var lhs_local = is_lhs_local(lhs); + var rhs_value = get_rvalue(candidate); + var rvalue = rhs_value; + if (!side_effects) { + if (!compound && rvalue instanceof AST_Sequence) rvalue = rvalue.tail_node(); + side_effects = value_has_side_effects(); + } + var check_destructured = in_try || !lhs_local ? function(node) { + return node instanceof AST_Destructured; + } : return_false; + var replace_all = replace_all_symbols(candidate); + var hit = funarg; + var abort = false; + var replaced = 0; + var can_replace = !args || !hit; + if (!can_replace) { + for (var j = candidate.arg_index + 1; !abort && j < args.length; j++) { + if (args[j]) args[j].transform(scanner); + } + can_replace = true; + } + for (var i = stat_index; !abort && i < statements.length; i++) { + statements[i].transform(scanner); + } + if (value_def) { + if (!replaced || remaining > replaced + assign_used) { + candidates.push(hit_stack); + force_single = true; + continue; + } + if (replaced == assign_pos) assign_used = true; + var def = lhs.definition(); + abort = false; + hit_index = 0; + hit = funarg; + for (var i = stat_index; !abort && i < statements.length; i++) { + if (!statements[i].transform(multi_replacer)) statements.splice(i--, 1); + } + replaced = candidate instanceof AST_VarDef + && candidate === hit_stack[hit_stack.length - 1] + && def.references.length == def.replaced + && !compressor.exposed(def); + value_def.last_ref = false; + value_def.single_use = false; + changed = true; + } + if (replaced) remove_candidate(candidate); + } + } + return changed; + + function signal_abort(node) { + if (abort) return node; + if (stop_after === node) abort = true; + if (stop_if_hit === node) stop_if_hit = null; + return node; + } + + function handle_custom_scan_order(node, tt) { + if (!(node instanceof AST_BlockScope)) return; + // Skip (non-executed) functions + if (node instanceof AST_Scope) return node; + // Scan computed keys, static fields & initializers in class + if (node instanceof AST_Class) { + if (node.name) node.name = node.name.transform(tt); + if (!abort && node.extends) node.extends = node.extends.transform(tt); + var fields = [], stats = []; + for (var i = 0; !abort && i < node.properties.length; i++) { + var prop = node.properties[i]; + if (prop.key instanceof AST_Node) prop.key = prop.key.transform(tt); + if (!prop.static) continue; + if (prop instanceof AST_ClassField) { + if (prop.value) fields.push(prop); + } else if (prop instanceof AST_ClassInit) { + [].push.apply(stats, prop.value.body); + } + } + for (var i = 0; !abort && i < stats.length; i++) { + stats[i].transform(tt); + } + for (var i = 0; !abort && i < fields.length; i++) { + var prop = fields[i]; + prop.value = prop.value.transform(tt); + } + return node; + } + // Scan object only in a for-in/of statement + if (node instanceof AST_ForEnumeration) { + node.object = node.object.transform(tt); + abort = true; + return node; + } + // Scan first case expression only in a switch statement + if (node instanceof AST_Switch) { + node.expression = node.expression.transform(tt); + for (var i = 0; !abort && i < node.body.length; i++) { + var branch = node.body[i]; + if (branch instanceof AST_Case) { + if (!hit) { + if (branch !== hit_stack[hit_index]) continue; + hit_index++; + } + branch.expression = branch.expression.transform(tt); + if (!replace_all) break; + scan_rhs = false; + } + } + abort = true; + return node; + } + } + + function is_direct_assignment(node, parent) { + if (parent instanceof AST_Assign) return parent.operator == "=" && parent.left === node; + if (parent instanceof AST_DefaultValue) return parent.name === node; + if (parent instanceof AST_DestructuredArray) return true; + if (parent instanceof AST_DestructuredKeyVal) return parent.value === node; + } + + function should_stop(node, parent) { + if (node === rvalue) return true; + if (parent instanceof AST_For) { + if (node !== parent.init) return true; + } + if (node instanceof AST_Assign) { + return node.operator != "=" && lhs.equals(node.left); + } + if (node instanceof AST_Call) { + if (!(lhs instanceof AST_PropAccess)) return false; + if (!lhs.equals(node.expression)) return false; + return !(rvalue instanceof AST_LambdaExpression && !rvalue.contains_this()); + } + if (node instanceof AST_Class) return !compressor.has_directive("use strict"); + if (node instanceof AST_Debugger) return true; + if (node instanceof AST_Defun) return funarg && lhs.name === node.name.name; + if (node instanceof AST_DestructuredKeyVal) return node.key instanceof AST_Node; + if (node instanceof AST_DWLoop) return true; + if (node instanceof AST_LoopControl) return true; + if (node instanceof AST_Try) return true; + if (node instanceof AST_With) return true; + return false; + } + + function should_stop_ref(node, parent) { + if (!(node instanceof AST_SymbolRef)) return false; + if (node.is_declared(compressor)) { + if (node.fixed_value()) return false; + if (can_drop_symbol(node)) { + return !(parent instanceof AST_PropAccess && parent.expression === node) + && is_arguments(node.definition()); + } + } else if (is_direct_assignment(node, parent)) { + return false; + } + if (!replace_all) return true; + scan_rhs = false; + return false; + } + + function in_conditional(node, parent) { + if (parent instanceof AST_Assign) return parent.left !== node && lazy_op[parent.operator.slice(0, -1)]; + if (parent instanceof AST_Binary) return parent.left !== node && lazy_op[parent.operator]; + if (parent instanceof AST_Call) return parent.optional && parent.expression !== node; + if (parent instanceof AST_Case) return parent.expression !== node; + if (parent instanceof AST_Conditional) return parent.condition !== node; + if (parent instanceof AST_If) return parent.condition !== node; + if (parent instanceof AST_Sub) return parent.optional && parent.expression !== node; + } + + function is_last_node(node, parent) { + if (node instanceof AST_Await) return true; + if (node.TYPE == "Binary") return !can_drop_op(node.operator, node.right, compressor); + if (node instanceof AST_Call) { + var def, fn = node.expression; + if (fn instanceof AST_SymbolRef) { + def = fn.definition(); + fn = fn.fixed_value(); + } + if (!(fn instanceof AST_Lambda)) return !node.is_expr_pure(compressor); + if (def && recursive_ref(compressor, def, fn)) return true; + if (fn.collapse_scanning) return false; + fn.collapse_scanning = true; + var replace = can_replace; + can_replace = false; + var after = stop_after; + var if_hit = stop_if_hit; + for (var i = 0; !abort && i < fn.argnames.length; i++) { + if (arg_may_throw(reject, fn.argnames[i], node.args[i])) abort = true; + } + if (!abort) { + if (fn.rest && arg_may_throw(reject, fn.rest, make_node(AST_Array, node, { + elements: node.args.slice(i), + }))) { + abort = true; + } else if (is_arrow(fn) && fn.value) { + fn.value.transform(scanner); + } else for (var i = 0; !abort && i < fn.body.length; i++) { + var stat = fn.body[i]; + if (stat instanceof AST_Return) { + if (stat.value) stat.value.transform(scanner); + break; + } + stat.transform(scanner); + } + } + stop_if_hit = if_hit; + stop_after = after; + can_replace = replace; + fn.collapse_scanning = false; + if (!abort) return false; + abort = false; + return true; + } + if (node instanceof AST_Class) { + if (!in_try) return false; + var base = node.extends; + if (!base) return false; + if (base instanceof AST_SymbolRef) base = base.fixed_value(); + return !safe_for_extends(base); + } + if (node instanceof AST_Exit) { + if (in_try) { + if (in_try.bfinally) return true; + if (in_try.bcatch && node instanceof AST_Throw) return true; + } + return side_effects || lhs instanceof AST_PropAccess || may_modify(lhs); + } + if (node instanceof AST_Function) { + return compressor.option("ie") && node.name && lvalues.has(node.name.name); + } + if (node instanceof AST_ObjectIdentity) return symbol_in_lvalues(node, parent); + if (node instanceof AST_PropAccess) { + if (side_effects) return true; + var exp = node.expression; + if (exp instanceof AST_SymbolRef && is_arguments(exp.definition())) return true; + if (compressor.option("unsafe")) { + if (is_undeclared_ref(exp) && global_names[exp.name]) return false; + if (is_static_fn(exp)) return false; + } + if (!well_defined) return true; + if (value_def) return false; + if (!in_try && lhs_local) return false; + if (node.optional) return false; + return exp.may_throw_on_access(compressor); + } + if (node instanceof AST_Spread) return true; + if (node instanceof AST_SymbolRef) { + if (symbol_in_lvalues(node, parent)) return !is_direct_assignment(node, parent); + if (side_effects && may_modify(node)) return true; + var def = node.definition(); + return (in_try || def.scope.resolve() !== scope) && !can_drop_symbol(node); + } + if (node instanceof AST_Template) return !node.is_expr_pure(compressor); + if (node instanceof AST_VarDef) { + if (check_destructured(node.name)) return true; + return (node.value || parent instanceof AST_Let) && node.name.match_symbol(function(node) { + return node instanceof AST_SymbolDeclaration + && (lvalues.has(node.name) || side_effects && may_modify(node)); + }, true); + } + if (node instanceof AST_Yield) return true; + var sym = is_lhs(node.left, node); + if (!sym) return false; + if (sym instanceof AST_PropAccess) return true; + if (check_destructured(sym)) return true; + return sym.match_symbol(function(node) { + return node instanceof AST_SymbolRef + && (lvalues.has(node.name) || read_toplevel && compressor.exposed(node.definition())); + }, true); + + function reject(node) { + node.transform(scanner); + return abort; + } + } + + function arg_may_throw(reject, node, value) { + if (node instanceof AST_DefaultValue) { + return reject(node.value) + || arg_may_throw(reject, node.name, node.value) + || !is_undefined(value) && arg_may_throw(reject, node.name, value); + } + if (!value) return !(node instanceof AST_Symbol); + if (node instanceof AST_Destructured) { + if (node.rest && arg_may_throw(reject, node.rest)) return true; + if (node instanceof AST_DestructuredArray) { + if (value instanceof AST_Array) return !all(node.elements, function(element, index) { + return !arg_may_throw(reject, element, value[index]); + }); + if (!value.is_string(compressor)) return true; + return !all(node.elements, function(element) { + return !arg_may_throw(reject, element); + }); + } + if (node instanceof AST_DestructuredObject) { + if (value.may_throw_on_access(compressor)) return true; + return !all(node.properties, function(prop) { + if (prop.key instanceof AST_Node && reject(prop.key)) return false; + return !arg_may_throw(reject, prop.value); + }); + } + } + } + + function extract_args() { + if (in_iife_single === false) return; + var iife = compressor.parent(), fn = compressor.self(); + if (in_iife_single === undefined) { + if (!(fn instanceof AST_LambdaExpression) + || is_generator(fn) + || fn.uses_arguments + || fn.pinned() + || !(iife instanceof AST_Call) + || iife.expression !== fn + || !all(iife.args, function(arg) { + return !(arg instanceof AST_Spread); + })) { + in_iife_single = false; + return; + } + if (!is_iife_single(iife)) return; + in_iife_single = true; + } + var fn_strict = fn.in_strict_mode(compressor) + && !fn.parent_scope.resolve(true).in_strict_mode(compressor); + var has_await; + if (is_async(fn)) { + has_await = function(node) { + return node instanceof AST_Symbol && node.name == "await"; + }; + iife_in_try = true; + } else { + has_await = function(node) { + return node instanceof AST_Await && !tw.find_parent(AST_Scope); + }; + if (iife_in_try === undefined) iife_in_try = find_try(compressor, 1, iife, null, true, true); + } + var arg_scope = null; + var tw = new TreeWalker(function(node, descend) { + if (!arg) return true; + if (has_await(node) || node instanceof AST_Yield) { + arg = null; + return true; + } + if (node instanceof AST_ObjectIdentity) { + if (fn_strict || !arg_scope) arg = null; + return true; + } + if (node instanceof AST_SymbolRef) { + var def; + if (node.in_arg && !is_safe_lexical(node.definition()) + || (def = fn.variables.get(node.name)) && def !== node.definition()) { + arg = null; + } + return true; + } + if (node instanceof AST_Scope && !is_arrow(node)) { + var save_scope = arg_scope; + arg_scope = node; + descend(); + arg_scope = save_scope; + return true; + } + }); + args = iife.args.slice(); + var len = args.length; + var names = new Dictionary(); + for (var i = fn.argnames.length; --i >= 0;) { + var sym = fn.argnames[i]; + var arg = args[i]; + var value = null; + if (sym instanceof AST_DefaultValue) { + value = sym.value; + sym = sym.name; + args[len + i] = value; + } + if (sym instanceof AST_Destructured) { + if (iife_in_try && arg_may_throw(function(node) { + return node.has_side_effects(compressor); + }, sym, arg)) { + candidates.length = 0; + break; + } + args[len + i] = fn.argnames[i]; + continue; + } + if (names.has(sym.name)) continue; + names.set(sym.name, true); + if (value) arg = is_undefined(arg) ? value : null; + if (!arg && !value) { + arg = make_node(AST_Undefined, sym).transform(compressor); + } else if (arg instanceof AST_Lambda && arg.pinned()) { + arg = null; + } else if (arg) { + arg.walk(tw); + } + if (!arg) continue; + var candidate = make_node(AST_VarDef, sym, { + name: sym, + value: arg, + }); + candidate.name_index = i; + candidate.arg_index = value ? len + i : i; + candidates.unshift([ candidate ]); + } + if (fn.rest) args.push(fn.rest); + } + + function extract_candidates(expr, unused) { + hit_stack.push(expr); + if (expr instanceof AST_Array) { + expr.elements.forEach(function(node) { + extract_candidates(node, unused); + }); + } else if (expr instanceof AST_Assign) { + var lhs = expr.left; + if (!(lhs instanceof AST_Destructured)) candidates.push(hit_stack.slice()); + extract_candidates(lhs); + extract_candidates(expr.right); + if (lhs instanceof AST_SymbolRef && expr.operator == "=") { + assignments.set(lhs.name, (assignments.get(lhs.name) || 0) + 1); + } + } else if (expr instanceof AST_Await) { + extract_candidates(expr.expression, unused); + } else if (expr instanceof AST_Binary) { + var lazy = lazy_op[expr.operator]; + if (unused + && lazy + && expr.operator != "??" + && expr.right instanceof AST_Assign + && expr.right.operator == "=" + && !(expr.right.left instanceof AST_Destructured)) { + candidates.push(hit_stack.slice()); + } + extract_candidates(expr.left, !lazy && unused); + extract_candidates(expr.right, unused); + } else if (expr instanceof AST_Call) { + extract_candidates(expr.expression); + expr.args.forEach(extract_candidates); + } else if (expr instanceof AST_Case) { + extract_candidates(expr.expression); + } else if (expr instanceof AST_Conditional) { + extract_candidates(expr.condition); + extract_candidates(expr.consequent, unused); + extract_candidates(expr.alternative, unused); + } else if (expr instanceof AST_Definitions) { + expr.definitions.forEach(extract_candidates); + } else if (expr instanceof AST_Dot) { + extract_candidates(expr.expression); + } else if (expr instanceof AST_DWLoop) { + extract_candidates(expr.condition); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + } else if (expr instanceof AST_Exit) { + if (expr.value) extract_candidates(expr.value); + } else if (expr instanceof AST_For) { + if (expr.init) extract_candidates(expr.init, true); + if (expr.condition) extract_candidates(expr.condition); + if (expr.step) extract_candidates(expr.step, true); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + } else if (expr instanceof AST_ForEnumeration) { + extract_candidates(expr.object); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + } else if (expr instanceof AST_If) { + extract_candidates(expr.condition); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + if (expr.alternative && !(expr.alternative instanceof AST_Block)) { + extract_candidates(expr.alternative); + } + } else if (expr instanceof AST_Object) { + expr.properties.forEach(function(prop) { + hit_stack.push(prop); + if (prop.key instanceof AST_Node) extract_candidates(prop.key); + if (prop instanceof AST_ObjectKeyVal) extract_candidates(prop.value, unused); + hit_stack.pop(); + }); + } else if (expr instanceof AST_Sequence) { + var end = expr.expressions.length - (unused ? 0 : 1); + expr.expressions.forEach(function(node, index) { + extract_candidates(node, index < end); + }); + } else if (expr instanceof AST_SimpleStatement) { + extract_candidates(expr.body, true); + } else if (expr instanceof AST_Spread) { + extract_candidates(expr.expression); + } else if (expr instanceof AST_Sub) { + extract_candidates(expr.expression); + extract_candidates(expr.property); + } else if (expr instanceof AST_Switch) { + extract_candidates(expr.expression); + expr.body.forEach(extract_candidates); + } else if (expr instanceof AST_Unary) { + if (UNARY_POSTFIX[expr.operator]) { + candidates.push(hit_stack.slice()); + } else { + extract_candidates(expr.expression); + } + } else if (expr instanceof AST_VarDef) { + if (expr.name instanceof AST_SymbolVar) { + if (expr.value) { + var def = expr.name.definition(); + if (def.references.length > def.replaced) { + candidates.push(hit_stack.slice()); + } + } else { + declare_only.set(expr.name.name, (declare_only.get(expr.name.name) || 0) + 1); + } + } + if (expr.value) extract_candidates(expr.value); + } else if (expr instanceof AST_Yield) { + if (expr.expression) extract_candidates(expr.expression); + } + hit_stack.pop(); + } + + function find_stop(node, level) { + var parent = scanner.parent(level); + if (parent instanceof AST_Array) return node; + if (parent instanceof AST_Assign) return node; + if (parent instanceof AST_Await) return node; + if (parent instanceof AST_Binary) return node; + if (parent instanceof AST_Call) return node; + if (parent instanceof AST_Case) return node; + if (parent instanceof AST_Conditional) return node; + if (parent instanceof AST_Definitions) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_Exit) return node; + if (parent instanceof AST_If) return node; + if (parent instanceof AST_IterationStatement) return node; + if (parent instanceof AST_ObjectProperty) return node; + if (parent instanceof AST_PropAccess) return node; + if (parent instanceof AST_Sequence) { + return (parent.tail_node() === node ? find_stop : find_stop_unused)(parent, level + 1); + } + if (parent instanceof AST_SimpleStatement) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_Spread) return node; + if (parent instanceof AST_Switch) return node; + if (parent instanceof AST_Unary) return node; + if (parent instanceof AST_VarDef) return node; + if (parent instanceof AST_Yield) return node; + return null; + } + + function find_stop_logical(parent, op, level) { + var node; + do { + node = parent; + parent = scanner.parent(++level); + } while (parent instanceof AST_Assign && parent.operator.slice(0, -1) == op + || parent instanceof AST_Binary && parent.operator == op); + return node; + } + + function find_stop_expr(expr, cont, node, parent, level) { + var replace = can_replace; + can_replace = false; + var after = stop_after; + var if_hit = stop_if_hit; + var stack = scanner.stack; + scanner.stack = [ parent ]; + expr.transform(scanner); + scanner.stack = stack; + stop_if_hit = if_hit; + stop_after = after; + can_replace = replace; + if (abort) { + abort = false; + return node; + } + return cont(parent, level + 1); + } + + function find_stop_value(node, level) { + var parent = scanner.parent(level); + if (parent instanceof AST_Array) return find_stop_value(parent, level + 1); + if (parent instanceof AST_Assign) { + if (may_throw(parent)) return node; + if (parent.left.match_symbol(function(ref) { + return ref instanceof AST_SymbolRef && (lhs.name == ref.name || value_def.name == ref.name); + })) return node; + var op; + if (parent.left === node || !lazy_op[op = parent.operator.slice(0, -1)]) { + return find_stop_value(parent, level + 1); + } + return find_stop_logical(parent, op, level); + } + if (parent instanceof AST_Await) return find_stop_value(parent, level + 1); + if (parent instanceof AST_Binary) { + var op; + if (parent.left === node || !lazy_op[op = parent.operator]) { + return find_stop_value(parent, level + 1); + } + return find_stop_logical(parent, op, level); + } + if (parent instanceof AST_Call) return parent; + if (parent instanceof AST_Case) { + if (parent.expression !== node) return node; + return find_stop_value(parent, level + 1); + } + if (parent instanceof AST_Conditional) { + if (parent.condition !== node) return node; + return find_stop_value(parent, level + 1); + } + if (parent instanceof AST_Definitions) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_Do) return node; + if (parent instanceof AST_Exit) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_For) { + if (parent.init !== node && parent.condition !== node) return node; + return find_stop_value(parent, level + 1); + } + if (parent instanceof AST_ForEnumeration) { + if (parent.init !== node) return node; + return find_stop_value(parent, level + 1); + } + if (parent instanceof AST_If) { + if (parent.condition !== node) return node; + return find_stop_value(parent, level + 1); + } + if (parent instanceof AST_ObjectProperty) { + var obj = scanner.parent(level + 1); + return all(obj.properties, function(prop) { + return prop instanceof AST_ObjectKeyVal; + }) ? find_stop_value(obj, level + 2) : obj; + } + if (parent instanceof AST_PropAccess) { + var exp = parent.expression; + return exp === node ? find_stop_value(parent, level + 1) : node; + } + if (parent instanceof AST_Sequence) { + return (parent.tail_node() === node ? find_stop_value : find_stop_unused)(parent, level + 1); + } + if (parent instanceof AST_SimpleStatement) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_Spread) return find_stop_value(parent, level + 1); + if (parent instanceof AST_Switch) { + if (parent.expression !== node) return node; + return find_stop_value(parent, level + 1); + } + if (parent instanceof AST_Unary) { + if (parent.operator == "delete") return node; + return find_stop_value(parent, level + 1); + } + if (parent instanceof AST_VarDef) return parent.name.match_symbol(function(sym) { + return sym instanceof AST_SymbolDeclaration && (lhs.name == sym.name || value_def.name == sym.name); + }) ? node : find_stop_value(parent, level + 1); + if (parent instanceof AST_While) { + if (parent.condition !== node) return node; + return find_stop_value(parent, level + 1); + } + if (parent instanceof AST_Yield) return find_stop_value(parent, level + 1); + return null; + } + + function find_stop_unused(node, level) { + var parent = scanner.parent(level); + if (is_last_node(node, parent)) return node; + if (in_conditional(node, parent)) return node; + if (parent instanceof AST_Array) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_Assign) return check_assignment(parent.left); + if (parent instanceof AST_Await) return node; + if (parent instanceof AST_Binary) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_Call) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_Case) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_Conditional) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_Definitions) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_Exit) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_If) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_IterationStatement) return node; + if (parent instanceof AST_ObjectProperty) { + var obj = scanner.parent(level + 1); + return all(obj.properties, function(prop) { + return prop instanceof AST_ObjectKeyVal; + }) ? find_stop_unused(obj, level + 2) : obj; + } + if (parent instanceof AST_PropAccess) { + var exp = parent.expression; + if (exp === node) return find_stop_unused(parent, level + 1); + return find_stop_expr(exp, find_stop_unused, node, parent, level); + } + if (parent instanceof AST_Sequence) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_SimpleStatement) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_Spread) return node; + if (parent instanceof AST_Switch) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_Unary) return find_stop_unused(parent, level + 1); + if (parent instanceof AST_VarDef) return check_assignment(parent.name); + if (parent instanceof AST_Yield) return node; + return null; + + function check_assignment(lhs) { + if (may_throw(parent)) return node; + if (lhs !== node && lhs instanceof AST_Destructured) { + return find_stop_expr(lhs, find_stop_unused, node, parent, level); + } + return find_stop_unused(parent, level + 1); + } + } + + function mangleable_var(rhs) { + if (force_single) { + force_single = false; + return; + } + if (remaining < 1) return; + rhs = rhs.tail_node(); + var value = rhs instanceof AST_Assign && rhs.operator == "=" ? rhs.left : rhs; + if (!(value instanceof AST_SymbolRef)) return; + var def = value.definition(); + if (def.undeclared) return; + if (is_arguments(def)) return; + if (value !== rhs) { + if (is_lhs_read_only(value, compressor)) return; + var referenced = def.references.length - def.replaced; + if (referenced < 2) return; + var expr = candidate.clone(); + expr[expr instanceof AST_Assign ? "right" : "value"] = value; + if (candidate.name_index >= 0) { + expr.name_index = candidate.name_index; + expr.arg_index = candidate.arg_index; + } + candidate = expr; + } + return value_def = def; + } + + function remaining_refs(def) { + return def.references.length - def.replaced - (assignments.get(def.name) || 0); + } + + function get_lhs(expr) { + if (expr instanceof AST_Assign) { + var lhs = expr.left; + if (!(lhs instanceof AST_SymbolRef)) return lhs; + var def = lhs.definition(); + if (scope.uses_arguments && is_funarg(def)) return lhs; + if (compressor.exposed(def)) return lhs; + remaining = remaining_refs(def); + if (def.fixed && lhs.fixed) { + var matches = def.references.filter(function(ref) { + return ref.fixed === lhs.fixed; + }).length - 1; + if (matches < remaining) { + remaining = matches; + assign_pos = 0; + verify_ref = true; + } + } + if (expr.operator == "=") mangleable_var(expr.right); + return lhs; + } + if (expr instanceof AST_Binary) return expr.right.left; + if (expr instanceof AST_Unary) return expr.expression; + if (expr instanceof AST_VarDef) { + var lhs = expr.name; + var def = lhs.definition(); + if (def.const_redefs) return; + if (!member(lhs, def.orig)) return; + if (scope.uses_arguments && is_funarg(def)) return; + var declared = def.orig.length - def.eliminated - (declare_only.get(def.name) || 0); + remaining = remaining_refs(def); + if (def.fixed) remaining = Math.min(remaining, def.references.filter(function(ref) { + if (!ref.fixed) return true; + if (!ref.fixed.assigns) return true; + var assign = ref.fixed.assigns[0]; + return assign === lhs || get_rvalue(assign) === expr.value; + }).length); + if (declared > 1 && !(lhs instanceof AST_SymbolFunarg)) { + mangleable_var(expr.value); + return make_node(AST_SymbolRef, lhs); + } + if (mangleable_var(expr.value) || remaining == 1 && !compressor.exposed(def)) { + return make_node(AST_SymbolRef, lhs); + } + return; + } + } + + function get_rvalue(expr) { + if (expr instanceof AST_Assign) return expr.right; + if (expr instanceof AST_Binary) { + var node = expr.clone(); + node.right = expr.right.right; + return node; + } + if (expr instanceof AST_VarDef) return expr.value; + } + + function invariant(expr) { + if (expr instanceof AST_Array) return false; + if (expr instanceof AST_Binary && lazy_op[expr.operator]) { + return invariant(expr.left) && invariant(expr.right); + } + if (expr instanceof AST_Call) return false; + if (expr instanceof AST_Conditional) { + return invariant(expr.consequent) && invariant(expr.alternative); + } + if (expr instanceof AST_Object) return false; + return !expr.has_side_effects(compressor); + } + + function foldable(expr) { + if (expr instanceof AST_Assign && expr.right.single_use) return; + var lhs_ids = Object.create(null); + var marker = new TreeWalker(function(node) { + if (node instanceof AST_SymbolRef) lhs_ids[node.definition().id] = true; + }); + while (expr instanceof AST_Assign && expr.operator == "=") { + expr.left.walk(marker); + expr = expr.right; + } + if (expr instanceof AST_ObjectIdentity) return rhs_exact_match; + if (expr instanceof AST_SymbolRef) { + var value = expr.evaluate(compressor); + if (value === expr) return rhs_exact_match; + return rhs_fuzzy_match(value, rhs_exact_match); + } + if (expr.is_truthy()) return rhs_fuzzy_match(true, return_false); + if (expr.is_constant()) { + var ev = expr.evaluate(compressor); + if (!(ev instanceof AST_Node)) return rhs_fuzzy_match(ev, rhs_exact_match); + } + if (!(lhs instanceof AST_SymbolRef)) return false; + if (!invariant(expr)) return false; + var circular; + expr.walk(new TreeWalker(function(node) { + if (circular) return true; + if (node instanceof AST_SymbolRef && lhs_ids[node.definition().id]) circular = true; + })); + return !circular && rhs_exact_match; + + function rhs_exact_match(node) { + return expr.equals(node); + } + } + + function rhs_fuzzy_match(value, fallback) { + return function(node, tw) { + if (tw.in_boolean_context()) { + if (value && node.is_truthy() && !node.has_side_effects(compressor)) { + return true; + } + if (node.is_constant()) { + var ev = node.evaluate(compressor); + if (!(ev instanceof AST_Node)) return !ev == !value; + } + } + return fallback(node); + }; + } + + function clear_write_only(assign) { + while (assign.write_only) { + assign.write_only = false; + if (!(assign instanceof AST_Assign)) break; + assign = assign.right; + } + } + + function update_symbols(value, node) { + var scope = node.scope || find_scope(scanner) || block_scope; + value.walk(new TreeWalker(function(node) { + if (node instanceof AST_BlockScope) return true; + if (node instanceof AST_Symbol) node.scope = scope; + })); + } + + function may_be_global(node) { + if (node instanceof AST_SymbolRef) { + node = node.fixed_value(); + if (!node) return true; + } + if (node instanceof AST_Assign) return node.operator == "=" && may_be_global(node.right); + return node instanceof AST_PropAccess || node instanceof AST_ObjectIdentity; + } + + function get_lvalues(expr) { + var lvalues = new Dictionary(); + if (expr instanceof AST_VarDef) { + if (!expr.name.definition().fixed) well_defined = false; + lvalues.add(expr.name.name, lhs); + } + var find_arguments = scope.uses_arguments && !compressor.has_directive("use strict"); + var scan_toplevel = scope instanceof AST_Toplevel; + var tw = new TreeWalker(function(node) { + var value; + if (node instanceof AST_SymbolRef) { + value = node.fixed_value(); + if (!value) { + value = node; + var def = node.definition(); + var escaped = node.fixed && node.fixed.escaped || def.escaped; + if (!def.undeclared + && (def.assignments || !escaped || escaped.cross_scope) + && (has_escaped(def, node.scope, node, tw.parent()) || !same_scope(def))) { + well_defined = false; + } + } + } else if (node instanceof AST_ObjectIdentity) { + value = node; + } + if (value) { + lvalues.add(node.name, is_modified(compressor, tw, node, value, 0)); + } else if (node instanceof AST_Lambda) { + for (var level = 0, parent, child = node; parent = tw.parent(level++); child = parent) { + if (parent instanceof AST_Assign) { + if (parent.left === child) break; + if (parent.operator == "=") continue; + if (lazy_op[parent.operator.slice(0, -1)]) continue; + break; + } + if (parent instanceof AST_Binary) { + if (lazy_op[parent.operator]) continue; + break; + } + if (parent instanceof AST_Call) return; + if (parent instanceof AST_Scope) return; + if (parent instanceof AST_Sequence) { + if (parent.tail_node() === child) continue; + break; + } + if (parent instanceof AST_Template) { + if (parent.tag) return; + break; + } + } + node.enclosed.forEach(function(def) { + if (def.scope !== node) enclosed.set(def.name, true); + }); + return true; + } else if (find_arguments && node instanceof AST_Sub) { + scope.each_argname(function(argname) { + if (!compressor.option("reduce_vars") || argname.definition().assignments) { + if (!argname.definition().fixed) well_defined = false; + lvalues.add(argname.name, true); + } + }); + find_arguments = false; + } + if (!scan_toplevel) return; + if (node.TYPE == "Call") { + if (modify_toplevel) return; + var exp = node.expression; + if (exp instanceof AST_PropAccess) return; + if (exp instanceof AST_LambdaExpression && !exp.contains_this()) return; + modify_toplevel = true; + } else if (node instanceof AST_PropAccess && may_be_global(node.expression)) { + if (node === lhs && !(expr instanceof AST_Unary)) { + modify_toplevel = true; + } else { + read_toplevel = true; + } + } + }); + expr.walk(tw); + return lvalues; + } + + function remove_candidate(expr) { + var value = rvalue === rhs_value ? null : make_sequence(rhs_value, rhs_value.expressions.slice(0, -1)); + var index = expr.name_index; + if (index >= 0) { + var args, argname = scope.argnames[index]; + if (argname instanceof AST_DefaultValue) { + scope.argnames[index] = argname = argname.clone(); + argname.value = value || make_node(AST_Number, argname, { value: 0 }); + } else if ((args = compressor.parent().args)[index]) { + scope.argnames[index] = argname.clone(); + args[index] = value || make_node(AST_Number, args[index], { value: 0 }); + } + return; + } + var end = hit_stack.length - 1; + var last = hit_stack[end]; + if (last instanceof AST_VarDef || hit_stack[end - 1].body === last) end--; + var tt = new TreeTransformer(function(node, descend, in_list) { + if (hit) return node; + if (node !== hit_stack[hit_index]) return node; + hit_index++; + if (hit_index <= end) return handle_custom_scan_order(node, tt); + hit = true; + if (node instanceof AST_Definitions) { + declare_only.set(last.name.name, (declare_only.get(last.name.name) || 0) + 1); + if (value_def) value_def.replaced++; + var defns = node.definitions; + var index = defns.indexOf(last); + var defn = last.clone(); + defn.value = null; + if (!value) { + node.definitions[index] = defn; + return node; + } + var body = [ make_node(AST_SimpleStatement, value, { body: value }) ]; + if (index > 0) { + var head = node.clone(); + head.definitions = defns.slice(0, index); + body.unshift(head); + node = node.clone(); + node.definitions = defns.slice(index); + } + body.push(node); + node.definitions[0] = defn; + return in_list ? List.splice(body) : make_node(AST_BlockStatement, node, { body: body }); + } + if (!value) return in_list ? List.skip : null; + return is_statement(node) ? make_node(AST_SimpleStatement, value, { body: value }) : value; + }, function(node, in_list) { + if (node instanceof AST_For) return patch_for_init(node, in_list); + return patch_sequence(node, tt); + }); + abort = false; + hit = false; + hit_index = 0; + if (!(statements[stat_index] = statements[stat_index].transform(tt))) statements.splice(stat_index, 1); + } + + function patch_sequence(node, tt) { + if (node instanceof AST_Sequence) switch (node.expressions.length) { + case 0: return null; + case 1: return maintain_this_binding(tt.parent(), node, node.expressions[0]); + } + } + + function is_lhs_local(lhs) { + var sym = root_expr(lhs); + if (!(sym instanceof AST_SymbolRef)) return false; + if (sym.definition().scope.resolve() !== scope) return false; + if (!in_loop) return true; + if (compound) return false; + if (candidate instanceof AST_Unary) return false; + var lvalue = lvalues.get(sym.name); + return !lvalue || lvalue[0] === lhs; + } + + function value_has_side_effects() { + if (candidate instanceof AST_Unary) return false; + return rvalue.has_side_effects(compressor); + } + + function replace_all_symbols(expr) { + if (expr instanceof AST_Unary) return false; + if (side_effects) return false; + if (value_def) return true; + if (!(lhs instanceof AST_SymbolRef)) return false; + var referenced; + if (expr instanceof AST_VarDef) { + referenced = 1; + } else if (expr.operator == "=") { + referenced = 2; + } else { + return false; + } + var def = lhs.definition(); + if (def.references.length - def.replaced == referenced) return true; + if (!def.fixed) return false; + if (!lhs.fixed) return false; + var assigns = lhs.fixed.assigns; + var matched = 0; + if (!all(def.references, function(ref, index) { + var fixed = ref.fixed; + if (!fixed) return false; + if (fixed.to_binary || fixed.to_prefix) return false; + if (fixed === lhs.fixed) { + matched++; + return true; + } + return assigns && fixed.assigns && assigns[0] !== fixed.assigns[0]; + })) return false; + if (matched != referenced) return false; + verify_ref = true; + return true; + } + + function symbol_in_lvalues(sym, parent) { + var lvalue = lvalues.get(sym.name); + if (!lvalue || all(lvalue, function(lhs) { + return !lhs; + })) return; + if (lvalue[0] !== lhs) return true; + scan_rhs = false; + } + + function may_modify(sym) { + var def = sym.definition(); + if (def.orig.length == 1 && def.orig[0] instanceof AST_SymbolDefun) return false; + if (def.scope.resolve() !== scope) return true; + if (modify_toplevel && compressor.exposed(def)) return true; + return !all(def.references, function(ref) { + return ref.scope.resolve(true) === scope; + }); + } + + function side_effects_external(node, lhs) { + if (node instanceof AST_Assign) return side_effects_external(node.left, true); + if (node instanceof AST_Unary) return side_effects_external(node.expression, true); + if (node instanceof AST_VarDef) return node.value && side_effects_external(node.value); + if (lhs) { + if (node instanceof AST_Dot) return side_effects_external(node.expression, true); + if (node instanceof AST_Sub) return side_effects_external(node.expression, true); + if (node instanceof AST_SymbolRef) return node.definition().scope.resolve() !== scope; + } + return false; + } + } + + function eliminate_spurious_blocks(statements) { + var changed = false, seen_dirs = []; + for (var i = 0; i < statements.length;) { + var stat = statements[i]; + if (stat instanceof AST_BlockStatement) { + if (all(stat.body, safe_to_trim)) { + changed = true; + eliminate_spurious_blocks(stat.body); + [].splice.apply(statements, [i, 1].concat(stat.body)); + i += stat.body.length; + continue; + } + } + if (stat instanceof AST_Directive) { + if (member(stat.value, seen_dirs)) { + changed = true; + statements.splice(i, 1); + continue; + } + seen_dirs.push(stat.value); + } + if (stat instanceof AST_EmptyStatement) { + changed = true; + statements.splice(i, 1); + continue; + } + i++; + } + return changed; + } + + function handle_if_return(statements, compressor) { + var changed = false; + var parent = compressor.parent(); + var self = compressor.self(); + var declare_only, jump, merge_jump; + var in_iife = in_lambda && parent && parent.TYPE == "Call" && parent.expression === self; + var chain_if_returns = in_lambda && compressor.option("conditionals") && compressor.option("sequences"); + var drop_return_void = !(in_try && in_try.bfinally && in_async_generator(scope)); + var multiple_if_returns = has_multiple_if_returns(statements); + for (var i = statements.length; --i >= 0;) { + var stat = statements[i]; + var j = next_index(i); + var next = statements[j]; + + if (in_lambda && declare_only && !next && stat instanceof AST_Return + && drop_return_void && !(self instanceof AST_SwitchBranch)) { + var body = stat.value; + if (!body) { + changed = true; + statements.splice(i, 1); + continue; + } + var tail = body.tail_node(); + if (is_undefined(tail)) { + changed = true; + if (body instanceof AST_UnaryPrefix) { + body = body.expression; + } else if (tail instanceof AST_UnaryPrefix) { + body = body.clone(); + body.expressions[body.expressions.length - 1] = tail.expression; + } + statements[i] = make_node(AST_SimpleStatement, stat, { body: body }); + continue; + } + } + + if (stat instanceof AST_If) { + var ab = aborts(stat.body); + // if (foo()) { bar(); return; } else baz(); moo(); ---> if (foo()) bar(); else { baz(); moo(); } + if (can_merge_flow(ab)) { + if (ab.label) remove(ab.label.thedef.references, ab); + changed = true; + stat = stat.clone(); + stat.body = make_node(AST_BlockStatement, stat, { + body: as_statement_array_with_return(stat.body, ab), + }); + stat.alternative = make_node(AST_BlockStatement, stat, { + body: as_statement_array(stat.alternative).concat(extract_functions(merge_jump, jump)), + }); + adjust_refs(ab.value, merge_jump); + statements[i] = stat; + statements[i] = stat.transform(compressor); + continue; + } + // if (foo()) { bar(); return x; } return y; ---> if (!foo()) return y; bar(); return x; + if (ab && !stat.alternative && next instanceof AST_Jump) { + var cond = stat.condition; + var preference = i + 1 == j && stat.body instanceof AST_BlockStatement; + cond = best_of_expression(cond, cond.negate(compressor), preference); + if (cond !== stat.condition) { + changed = true; + stat = stat.clone(); + stat.condition = cond; + var body = stat.body; + stat.body = make_node(AST_BlockStatement, next, { + body: extract_functions(true, null, j + 1), + }); + statements.splice(i, 1, stat, body); + // proceed further only if `TreeWalker.stack` is in a consistent state + // https://github.com/mishoo/UglifyJS/issues/5595 + // https://github.com/mishoo/UglifyJS/issues/5597 + if (!in_lambda || self instanceof AST_Block && self.body === statements) { + statements[i] = stat.transform(compressor); + } + continue; + } + } + var alt = aborts(stat.alternative); + // if (foo()) bar(); else { baz(); return; } moo(); ---> if (foo()) { bar(); moo(); } else baz(); + if (can_merge_flow(alt)) { + if (alt.label) remove(alt.label.thedef.references, alt); + changed = true; + stat = stat.clone(); + stat.body = make_node(AST_BlockStatement, stat.body, { + body: as_statement_array(stat.body).concat(extract_functions(merge_jump, jump)), + }); + stat.alternative = make_node(AST_BlockStatement, stat.alternative, { + body: as_statement_array_with_return(stat.alternative, alt), + }); + adjust_refs(alt.value, merge_jump); + statements[i] = stat; + statements[i] = stat.transform(compressor); + continue; + } + if (compressor.option("typeofs")) { + if (ab && !alt) { + var stats = make_node(AST_BlockStatement, self, { body: statements.slice(i + 1) }); + mark_locally_defined(stat.condition, null, stats); + } + if (!ab && alt) { + var stats = make_node(AST_BlockStatement, self, { body: statements.slice(i + 1) }); + mark_locally_defined(stat.condition, stats); + } + } + } + + if (stat instanceof AST_If && stat.body instanceof AST_Return) { + var value = stat.body.value; + var in_bool = stat.body.in_bool || next instanceof AST_Return && next.in_bool; + // if (foo()) return x; return y; ---> return foo() ? x : y; + if (!stat.alternative && next instanceof AST_Return + && (drop_return_void || !value == !next.value)) { + changed = true; + stat = stat.clone(); + stat.alternative = make_node(AST_BlockStatement, next, { + body: extract_functions(true, null, j + 1), + }); + statements[i] = stat; + statements[i] = stat.transform(compressor); + continue; + } + // if (foo()) return x; [ return ; ] ---> return foo() ? x : undefined; + // if (foo()) return bar() ? x : void 0; ---> return foo() && bar() ? x : void 0; + // if (foo()) return bar() ? void 0 : x; ---> return !foo() || bar() ? void 0 : x; + if (in_lambda && declare_only && !next && !stat.alternative && (in_bool + || value && multiple_if_returns + || value instanceof AST_Conditional && (is_undefined(value.consequent, compressor) + || is_undefined(value.alternative, compressor)))) { + changed = true; + stat = stat.clone(); + stat.alternative = make_node(AST_Return, stat, { value: null }); + statements[i] = stat; + statements[i] = stat.transform(compressor); + continue; + } + // if (a) return b; if (c) return d; e; ---> return a ? b : c ? d : void e; + // + // if sequences is not enabled, this can lead to an endless loop (issue #866). + // however, with sequences on this helps producing slightly better output for + // the example code. + var prev, prev_stat; + if (chain_if_returns && !stat.alternative + && (!(prev_stat = statements[prev = prev_index(i)]) && in_iife + || prev_stat instanceof AST_If && prev_stat.body instanceof AST_Return) + && (!next ? !declare_only + : next instanceof AST_SimpleStatement && next_index(j) == statements.length)) { + changed = true; + var exprs = []; + stat = stat.clone(); + exprs.push(stat.condition); + stat.condition = make_sequence(stat, exprs); + stat.alternative = make_node(AST_BlockStatement, self, { + body: extract_functions().concat(make_node(AST_Return, self, { value: null })), + }); + statements[i] = stat.transform(compressor); + i = prev + 1; + continue; + } + } + + if (stat instanceof AST_Break || stat instanceof AST_Exit) { + jump = stat; + continue; + } + + if (declare_only && jump && jump === next) eliminate_returns(stat); + } + return changed; + + function has_multiple_if_returns(statements) { + var n = 0; + for (var i = statements.length; --i >= 0;) { + var stat = statements[i]; + if (stat instanceof AST_If && stat.body instanceof AST_Return) { + if (++n > 1) return true; + } + } + return false; + } + + function match_target(target) { + return last_of(compressor, function(node) { + return node === target; + }); + } + + function match_return(ab, exact) { + if (!jump) return false; + if (jump.TYPE != ab.TYPE) return false; + var value = ab.value; + if (!value) return false; + var equals = jump.equals(ab); + if (!equals && value instanceof AST_Sequence) { + value = value.tail_node(); + if (jump.value && jump.value.equals(value)) equals = 2; + } + if (!equals && !exact && jump.value instanceof AST_Sequence) { + if (jump.value.tail_node().equals(value)) equals = 3; + } + return equals; + } + + function can_drop_abort(ab) { + if (ab instanceof AST_Exit) { + if (merge_jump = match_return(ab)) return true; + if (!in_lambda) return false; + if (!(ab instanceof AST_Return)) return false; + var value = ab.value; + if (value && !is_undefined(value.tail_node())) return false; + if (!(self instanceof AST_SwitchBranch)) return true; + if (!jump) return false; + if (jump instanceof AST_Exit && jump.value) return false; + merge_jump = 4; + return true; + } + if (!(ab instanceof AST_LoopControl)) return false; + if (self instanceof AST_SwitchBranch) { + if (jump instanceof AST_Exit) { + if (!in_lambda) return false; + if (jump.value) return false; + merge_jump = true; + } else if (jump) { + if (compressor.loopcontrol_target(jump) !== parent) return false; + merge_jump = true; + } else if (jump === false) { + return false; + } + } + var lct = compressor.loopcontrol_target(ab); + if (ab instanceof AST_Continue) return match_target(loop_body(lct)); + if (lct instanceof AST_IterationStatement) return false; + return match_target(lct); + } + + function can_merge_flow(ab) { + merge_jump = false; + if (!can_drop_abort(ab)) return false; + for (var j = statements.length; --j > i;) { + var stat = statements[j]; + if (stat instanceof AST_DefClass) { + if (stat.name.definition().preinit) return false; + } else if (stat instanceof AST_Const || stat instanceof AST_Let) { + if (!all(stat.definitions, function(defn) { + return !defn.name.match_symbol(function(node) { + return node instanceof AST_SymbolDeclaration && node.definition().preinit; + }); + })) return false; + } + } + return true; + } + + function extract_functions(mode, stop, end) { + var defuns = []; + var lexical = false; + var start = i + 1; + if (!mode) { + end = statements.length; + jump = null; + } else if (stop) { + end = statements.lastIndexOf(stop); + } else { + stop = statements[end]; + if (stop !== jump) jump = false; + } + var tail = statements.splice(start, end - start).filter(function(stat) { + if (stat instanceof AST_LambdaDefinition) { + defuns.push(stat); + return false; + } + if (is_lexical_definition(stat)) lexical = true; + return true; + }); + if (mode === 3) { + tail.push(make_node(AST_SimpleStatement, stop.value, { + body: make_sequence(stop.value, stop.value.expressions.slice(0, -1)), + })); + stop.value = stop.value.tail_node(); + } + [].push.apply(lexical ? tail : statements, defuns); + return tail; + } + + function trim_return(value, mode) { + if (value) switch (mode) { + case 4: + return value; + case 3: + if (!(value instanceof AST_Sequence)) break; + case 2: + return make_sequence(value, value.expressions.slice(0, -1)); + } + } + + function as_statement_array_with_return(node, ab) { + var body = as_statement_array(node); + var block = body, last; + while ((last = block[block.length - 1]) !== ab) { + block = last.body; + } + block.pop(); + var value = ab.value; + if (merge_jump) value = trim_return(value, merge_jump); + if (value) block.push(make_node(AST_SimpleStatement, value, { body: value })); + return body; + } + + function adjust_refs(value, mode) { + if (!mode) return; + if (!value) return; + switch (mode) { + case 4: + return; + case 3: + case 2: + value = value.tail_node(); + } + merge_expression(value, jump.value); + } + + function next_index(i) { + declare_only = true; + for (var j = i; ++j < statements.length;) { + var stat = statements[j]; + if (is_declaration(stat)) continue; + if (stat instanceof AST_Var) { + declare_only = false; + continue; + } + break; + } + return j; + } + + function prev_index(i) { + for (var j = i; --j >= 0;) { + var stat = statements[j]; + if (stat instanceof AST_Var) continue; + if (is_declaration(stat)) continue; + break; + } + return j; + } + + function eliminate_returns(stat, keep_throws, in_block) { + if (stat instanceof AST_Exit) { + var mode = !(keep_throws && stat instanceof AST_Throw) && match_return(stat, true); + if (mode) { + changed = true; + var value = trim_return(stat.value, mode); + if (value) return make_node(AST_SimpleStatement, value, { body: value }); + return in_block ? null : make_node(AST_EmptyStatement, stat); + } + } else if (stat instanceof AST_If) { + stat.body = eliminate_returns(stat.body, keep_throws); + if (stat.alternative) stat.alternative = eliminate_returns(stat.alternative, keep_throws); + } else if (stat instanceof AST_LabeledStatement) { + stat.body = eliminate_returns(stat.body, keep_throws); + } else if (stat instanceof AST_Try) { + if (!stat.bfinally || !jump.value || jump.value.is_constant()) { + if (stat.bcatch) eliminate_returns(stat.bcatch, keep_throws); + var trimmed = eliminate_returns(stat.body.pop(), true, true); + if (trimmed) stat.body.push(trimmed); + } + } else if (stat instanceof AST_Block && !(stat instanceof AST_Scope || stat instanceof AST_Switch)) { + var trimmed = eliminate_returns(stat.body.pop(), keep_throws, true); + if (trimmed) stat.body.push(trimmed); + } + return stat; + } + } + + function eliminate_dead_code(statements, compressor) { + var has_quit; + var self = compressor.self(); + if (self instanceof AST_Catch) { + self = compressor.parent(); + } else if (self instanceof AST_LabeledStatement) { + self = self.body; + } + for (var i = 0, n = 0, len = statements.length; i < len; i++) { + var stat = statements[i]; + if (stat instanceof AST_LoopControl) { + var lct = compressor.loopcontrol_target(stat); + if (loop_body(lct) !== self + || stat instanceof AST_Break && lct instanceof AST_IterationStatement) { + statements[n++] = stat; + } else if (stat.label) { + remove(stat.label.thedef.references, stat); + } + } else { + statements[n++] = stat; + } + if (aborts(stat)) { + has_quit = statements.slice(i + 1); + break; + } + } + statements.length = n; + if (has_quit) has_quit.forEach(function(stat) { + extract_declarations_from_unreachable_code(compressor, stat, statements); + }); + return statements.length != len; + } + + function trim_awaits(statements, compressor) { + if (!in_lambda || in_try && in_try.bfinally) return; + var changed = false; + for (var index = statements.length; --index >= 0;) { + var stat = statements[index]; + if (!(stat instanceof AST_SimpleStatement)) break; + var node = stat.body; + if (!(node instanceof AST_Await)) break; + var exp = node.expression; + if (!needs_enqueuing(compressor, exp)) break; + changed = true; + exp = exp.drop_side_effect_free(compressor, true); + if (exp) { + stat.body = exp; + break; + } + } + statements.length = index + 1; + return changed; + } + + function inline_iife(statements, compressor) { + var changed = false; + var index = statements.length - 1; + if (in_lambda && index >= 0) { + var no_return = in_try && in_try.bfinally && in_async_generator(scope); + var inlined = statements[index].try_inline(compressor, block_scope, no_return); + if (inlined) { + statements[index--] = inlined; + changed = true; + } + } + var loop = in_loop && in_try && in_try.bfinally ? "try" : in_loop; + for (; index >= 0; index--) { + var inlined = statements[index].try_inline(compressor, block_scope, true, loop); + if (!inlined) continue; + statements[index] = inlined; + changed = true; + } + return changed; + } + + function sequencesize(statements, compressor) { + if (statements.length < 2) return; + var seq = [], n = 0; + function push_seq() { + if (!seq.length) return; + var body = make_sequence(seq[0], seq); + statements[n++] = make_node(AST_SimpleStatement, body, { body: body }); + seq = []; + } + for (var i = 0, len = statements.length; i < len; i++) { + var stat = statements[i]; + if (stat instanceof AST_SimpleStatement) { + if (seq.length >= compressor.sequences_limit) push_seq(); + merge_sequence(seq, stat.body); + } else if (is_declaration(stat)) { + statements[n++] = stat; + } else { + push_seq(); + statements[n++] = stat; + } + } + push_seq(); + statements.length = n; + return n != len; + } + + function to_simple_statement(block, decls) { + if (!(block instanceof AST_BlockStatement)) return block; + var stat = null; + for (var i = 0; i < block.body.length; i++) { + var line = block.body[i]; + if (line instanceof AST_Var && declarations_only(line)) { + decls.push(line); + } else if (stat || is_lexical_definition(line)) { + return false; + } else { + stat = line; + } + } + return stat; + } + + function sequencesize_2(statements, compressor) { + var changed = false, n = 0, prev; + for (var i = 0; i < statements.length; i++) { + var stat = statements[i]; + if (prev) { + if (stat instanceof AST_Exit) { + if (stat.value || !in_async_generator(scope)) { + stat.value = cons_seq(stat.value || make_node(AST_Undefined, stat)).optimize(compressor); + } + } else if (stat instanceof AST_For) { + if (!(stat.init instanceof AST_Definitions)) { + var abort = false; + prev.body.walk(new TreeWalker(function(node) { + if (abort || node instanceof AST_Scope) return true; + if (node instanceof AST_Binary && node.operator == "in") { + abort = true; + return true; + } + })); + if (!abort) { + if (stat.init) stat.init = cons_seq(stat.init); + else { + stat.init = prev.body; + n--; + changed = true; + } + } + } + } else if (stat instanceof AST_ForIn) { + if (!is_lexical_definition(stat.init)) stat.object = cons_seq(stat.object); + } else if (stat instanceof AST_If) { + stat.condition = cons_seq(stat.condition); + } else if (stat instanceof AST_Switch) { + stat.expression = cons_seq(stat.expression); + } else if (stat instanceof AST_With) { + stat.expression = cons_seq(stat.expression); + } + } + if (compressor.option("conditionals") && stat instanceof AST_If) { + var decls = []; + var body = to_simple_statement(stat.body, decls); + var alt = to_simple_statement(stat.alternative, decls); + if (body !== false && alt !== false && decls.length > 0) { + var len = decls.length; + decls.push(make_node(AST_If, stat, { + condition: stat.condition, + body: body || make_node(AST_EmptyStatement, stat.body), + alternative: alt, + })); + decls.unshift(n, 1); + [].splice.apply(statements, decls); + i += len; + n += len + 1; + prev = null; + changed = true; + continue; + } + } + statements[n++] = stat; + prev = stat instanceof AST_SimpleStatement ? stat : null; + } + statements.length = n; + return changed; + + function cons_seq(right) { + n--; + changed = true; + var left = prev.body; + return make_sequence(left, [ left, right ]); + } + } + + function extract_exprs(body) { + if (body instanceof AST_Assign) return [ body ]; + if (body instanceof AST_Sequence) return body.expressions.slice(); + } + + function join_assigns(defn, body, keep) { + var exprs = extract_exprs(body); + if (!exprs) return; + keep = keep || 0; + var trimmed = false; + for (var i = exprs.length - keep; --i >= 0;) { + var expr = exprs[i]; + if (!can_trim(expr)) continue; + var tail; + if (expr.left instanceof AST_SymbolRef) { + tail = exprs.slice(i + 1); + } else if (expr.left instanceof AST_PropAccess && can_trim(expr.left.expression)) { + tail = exprs.slice(i + 1); + var flattened = expr.clone(); + expr = expr.left.expression; + flattened.left = flattened.left.clone(); + flattened.left.expression = expr.left.clone(); + tail.unshift(flattened); + } else { + continue; + } + if (tail.length == 0) continue; + if (!trim_assigns(expr.left, expr.right, tail)) continue; + trimmed = true; + exprs = exprs.slice(0, i).concat(expr, tail); + } + if (defn instanceof AST_Definitions) { + for (var i = defn.definitions.length; --i >= 0;) { + var def = defn.definitions[i]; + if (!def.value) continue; + if (trim_assigns(def.name, def.value, exprs)) trimmed = true; + if (merge_conditional_assignments(def, exprs, keep)) trimmed = true; + break; + } + if (defn instanceof AST_Var && join_var_assign(defn.definitions, exprs, keep)) trimmed = true; + } + return trimmed && exprs; + + function can_trim(node) { + return node instanceof AST_Assign && node.operator == "="; + } + } + + function merge_assigns(prev, defn) { + if (!(prev instanceof AST_SimpleStatement)) return; + if (declarations_only(defn)) return; + var exprs = extract_exprs(prev.body); + if (!exprs) return; + var definitions = []; + if (!join_var_assign(definitions, exprs.reverse(), 0)) return; + defn.definitions = definitions.reverse().concat(defn.definitions); + return exprs.reverse(); + } + + function merge_conditional_assignments(var_def, exprs, keep) { + if (!compressor.option("conditionals")) return; + if (var_def.name instanceof AST_Destructured) return; + var trimmed = false; + var def = var_def.name.definition(); + while (exprs.length > keep) { + var cond = to_conditional_assignment(compressor, def, var_def.value, exprs[0]); + if (!cond) break; + var_def.value = cond; + exprs.shift(); + trimmed = true; + } + return trimmed; + } + + function join_var_assign(definitions, exprs, keep) { + var trimmed = false; + while (exprs.length > keep) { + var expr = exprs[0]; + if (!(expr instanceof AST_Assign)) break; + if (expr.operator != "=") break; + var lhs = expr.left; + if (!(lhs instanceof AST_SymbolRef)) break; + if (is_undeclared_ref(lhs)) break; + if (lhs.scope.resolve() !== scope) break; + var def = lhs.definition(); + if (def.scope !== scope) break; + if (def.orig.length > def.eliminated + 1) break; + if (def.orig[0].TYPE != "SymbolVar") break; + var name = make_node(AST_SymbolVar, lhs); + definitions.push(make_node(AST_VarDef, expr, { + name: name, + value: expr.right, + })); + def.orig.push(name); + def.replaced++; + exprs.shift(); + trimmed = true; + } + return trimmed; + } + + function trim_assigns(name, value, exprs) { + var names = new Dictionary(); + names.set(name.name, true); + while (value instanceof AST_Assign && value.operator == "=") { + if (value.left instanceof AST_SymbolRef) names.set(value.left.name, true); + value = value.right; + } + if (!(value instanceof AST_Object)) return; + var trimmed = false; + do { + if (!try_join(exprs[0])) break; + exprs.shift(); + trimmed = true; + } while (exprs.length); + return trimmed; + + function try_join(node) { + if (!(node instanceof AST_Assign)) return; + if (node.operator != "=") return; + if (!(node.left instanceof AST_PropAccess)) return; + var sym = node.left.expression; + if (!(sym instanceof AST_SymbolRef)) return; + if (!names.has(sym.name)) return; + if (!node.right.is_constant_expression(scope)) return; + var prop = node.left.property; + if (prop instanceof AST_Node) { + if (try_join(prop)) prop = node.left.property = prop.right.clone(); + prop = prop.evaluate(compressor); + } + if (prop instanceof AST_Node) return; + prop = "" + prop; + var diff = prop == "__proto__" || compressor.has_directive("use strict") ? function(node) { + var key = node.key; + return typeof key == "string" && key != prop && key != "__proto__"; + } : function(node) { + var key = node.key; + if (node instanceof AST_ObjectGetter || node instanceof AST_ObjectSetter) { + return typeof key == "string" && key != prop; + } + return key !== "__proto__"; + }; + if (!all(value.properties, diff)) return; + value.properties.push(make_node(AST_ObjectKeyVal, node, { + key: prop, + value: node.right, + })); + return true; + } + } + + function join_consecutive_vars(statements) { + var changed = false, defs; + for (var i = 0, j = -1; i < statements.length; i++) { + var stat = statements[i]; + var prev = statements[j]; + if (stat instanceof AST_Definitions) { + if (prev && prev.TYPE == stat.TYPE) { + prev.definitions = prev.definitions.concat(stat.definitions); + changed = true; + } else if (defs && defs.TYPE == stat.TYPE && declarations_only(stat)) { + defs.definitions = defs.definitions.concat(stat.definitions); + changed = true; + } else if (stat instanceof AST_Var) { + var exprs = merge_assigns(prev, stat); + if (exprs) { + if (exprs.length) { + prev.body = make_sequence(prev, exprs); + j++; + } + changed = true; + } else { + j++; + } + statements[j] = defs = stat; + } else { + statements[++j] = stat; + } + continue; + } else if (stat instanceof AST_Exit) { + stat.value = join_assigns_expr(stat.value); + } else if (stat instanceof AST_For) { + var exprs = join_assigns(prev, stat.init); + if (exprs) { + changed = true; + stat.init = exprs.length ? make_sequence(stat.init, exprs) : null; + } else if (prev instanceof AST_Var && (!stat.init || stat.init.TYPE == prev.TYPE)) { + if (stat.init) { + prev.definitions = prev.definitions.concat(stat.init.definitions); + } + stat = stat.clone(); + defs = stat.init = prev; + statements[j] = merge_defns(stat); + changed = true; + continue; + } else if (defs && stat.init && defs.TYPE == stat.init.TYPE && declarations_only(stat.init)) { + defs.definitions = defs.definitions.concat(stat.init.definitions); + stat.init = null; + changed = true; + } else if (stat.init instanceof AST_Var) { + defs = stat.init; + exprs = merge_assigns(prev, stat.init); + if (exprs) { + changed = true; + if (exprs.length == 0) { + statements[j] = merge_defns(stat); + continue; + } + prev.body = make_sequence(prev, exprs); + } + } + } else if (stat instanceof AST_ForEnumeration) { + if (defs && defs.TYPE == stat.init.TYPE) { + var defns = defs.definitions.slice(); + stat.init = stat.init.definitions[0].name.convert_symbol(AST_SymbolRef, function(ref, name) { + defns.push(make_node(AST_VarDef, name, { + name: name, + value: null, + })); + name.definition().references.push(ref); + }); + defs.definitions = defns; + changed = true; + } + stat.object = join_assigns_expr(stat.object); + } else if (stat instanceof AST_If) { + stat.condition = join_assigns_expr(stat.condition); + } else if (stat instanceof AST_SimpleStatement) { + var exprs = join_assigns(prev, stat.body), next; + if (exprs) { + changed = true; + if (!exprs.length) continue; + stat.body = make_sequence(stat.body, exprs); + } else if (prev instanceof AST_Definitions + && (next = statements[i + 1]) + && prev.TYPE == next.TYPE + && (next = next.definitions[0]).value) { + changed = true; + next.value = make_sequence(stat, [ stat.body, next.value ]); + continue; + } + } else if (stat instanceof AST_Switch) { + stat.expression = join_assigns_expr(stat.expression); + } else if (stat instanceof AST_With) { + stat.expression = join_assigns_expr(stat.expression); + } + statements[++j] = defs ? merge_defns(stat) : stat; + } + statements.length = j + 1; + return changed; + + function join_assigns_expr(value) { + var exprs = join_assigns(prev, value, 1); + if (!exprs) return value; + changed = true; + var tail = value.tail_node(); + if (exprs[exprs.length - 1] !== tail) exprs.push(tail.left); + return make_sequence(value, exprs); + } + + function merge_defns(stat) { + return stat.transform(new TreeTransformer(function(node, descend, in_list) { + if (node instanceof AST_Definitions) { + if (defs === node) return node; + if (defs.TYPE != node.TYPE) return node; + var parent = this.parent(); + if (parent instanceof AST_ForEnumeration && parent.init === node) return node; + if (!declarations_only(node)) return node; + defs.definitions = defs.definitions.concat(node.definitions); + changed = true; + if (parent instanceof AST_For && parent.init === node) return null; + return in_list ? List.skip : make_node(AST_EmptyStatement, node); + } + if (node instanceof AST_ExportDeclaration) return node; + if (node instanceof AST_Scope) return node; + if (!is_statement(node)) return node; + })); + } + } + } + + function extract_declarations_from_unreachable_code(compressor, stat, target) { + var block; + var dropped = false; + stat.walk(new TreeWalker(function(node, descend) { + if (node instanceof AST_DefClass) { + node.extends = null; + node.properties = []; + push(node); + return true; + } + if (node instanceof AST_Definitions) { + var defns = []; + if (node.remove_initializers(compressor, defns)) { + AST_Node.warn("Dropping initialization in unreachable code [{start}]", node); + } + if (defns.length > 0) { + node.definitions = defns; + push(node); + } + return true; + } + if (node instanceof AST_LambdaDefinition) { + push(node); + return true; + } + if (node instanceof AST_Scope) return true; + if (node instanceof AST_BlockScope) { + var save = block; + block = []; + descend(); + if (block.required) { + target.push(make_node(AST_BlockStatement, stat, { body: block })); + } else if (block.length) { + [].push.apply(target, block); + } + block = save; + return true; + } + if (!(node instanceof AST_LoopControl)) dropped = true; + })); + if (dropped) AST_Node.warn("Dropping unreachable code [{start}]", stat); + + function push(node) { + if (block) { + block.push(node); + if (!safe_to_trim(node)) block.required = true; + } else { + target.push(node); + } + } + } + + function is_undefined(node, compressor) { + return node == null + || node.is_undefined + || node instanceof AST_Undefined + || node instanceof AST_UnaryPrefix + && node.operator == "void" + && !(compressor && node.expression.has_side_effects(compressor)); + } + + // in_strict_mode() + // return true if scope executes in Strict Mode + (function(def) { + def(AST_Class, return_true); + def(AST_Scope, function(compressor) { + var body = this.body; + for (var i = 0; i < body.length; i++) { + var stat = body[i]; + if (!(stat instanceof AST_Directive)) break; + if (stat.value == "use strict") return true; + } + var parent = this.parent_scope; + if (!parent) return compressor.option("module"); + return parent.resolve(true).in_strict_mode(compressor); + }); + })(function(node, func) { + node.DEFMETHOD("in_strict_mode", func); + }); + + // is_truthy() + // return true if `!!node === true` + (function(def) { + def(AST_Node, return_false); + def(AST_Array, return_true); + def(AST_Assign, function() { + return this.operator == "=" && this.right.is_truthy(); + }); + def(AST_Lambda, return_true); + def(AST_Object, return_true); + def(AST_RegExp, return_true); + def(AST_Sequence, function() { + return this.tail_node().is_truthy(); + }); + def(AST_SymbolRef, function() { + var fixed = this.fixed_value(); + if (!fixed) return false; + this.is_truthy = return_false; + var result = fixed.is_truthy(); + delete this.is_truthy; + return result; + }); + })(function(node, func) { + node.DEFMETHOD("is_truthy", func); + }); + + // is_negative_zero() + // return true if the node may represent -0 + (function(def) { + def(AST_Node, return_true); + def(AST_Array, return_false); + function binary(op, left, right) { + switch (op) { + case "-": + return left.is_negative_zero() + && (!(right instanceof AST_Constant) || right.value == 0); + case "&&": + case "||": + return left.is_negative_zero() || right.is_negative_zero(); + case "*": + case "/": + case "%": + case "**": + return true; + default: + return false; + } + } + def(AST_Assign, function() { + var op = this.operator; + if (op == "=") return this.right.is_negative_zero(); + return binary(op.slice(0, -1), this.left, this.right); + }); + def(AST_Binary, function() { + return binary(this.operator, this.left, this.right); + }); + def(AST_Constant, function() { + return this.value == 0 && 1 / this.value < 0; + }); + def(AST_Lambda, return_false); + def(AST_Object, return_false); + def(AST_RegExp, return_false); + def(AST_Sequence, function() { + return this.tail_node().is_negative_zero(); + }); + def(AST_SymbolRef, function() { + var fixed = this.fixed_value(); + if (!fixed) return true; + this.is_negative_zero = return_true; + var result = fixed.is_negative_zero(); + delete this.is_negative_zero; + return result; + }); + def(AST_UnaryPrefix, function() { + return this.operator == "+" && this.expression.is_negative_zero() + || this.operator == "-"; + }); + })(function(node, func) { + node.DEFMETHOD("is_negative_zero", func); + }); + + // may_throw_on_access() + // returns true if this node may be null, undefined or contain `AST_Accessor` + (function(def) { + AST_Node.DEFMETHOD("may_throw_on_access", function(compressor, force) { + return !compressor.option("pure_getters") || this._dot_throw(compressor, force); + }); + function is_strict(compressor, force) { + return force || /strict/.test(compressor.option("pure_getters")); + } + def(AST_Node, is_strict); + def(AST_Array, return_false); + def(AST_Assign, function(compressor) { + var op = this.operator; + var sym = this.left; + var rhs = this.right; + if (op != "=") { + return lazy_op[op.slice(0, -1)] && (sym._dot_throw(compressor) || rhs._dot_throw(compressor)); + } + if (!rhs._dot_throw(compressor)) return false; + if (!(sym instanceof AST_SymbolRef)) return true; + if (rhs instanceof AST_Binary && rhs.operator == "||" && sym.name == rhs.left.name) { + return rhs.right._dot_throw(compressor); + } + return true; + }); + def(AST_Binary, function(compressor) { + return lazy_op[this.operator] && (this.left._dot_throw(compressor) || this.right._dot_throw(compressor)); + }); + def(AST_Class, function(compressor, force) { + return is_strict(compressor, force) && !all(this.properties, function(prop) { + if (prop.private) return true; + if (!prop.static) return true; + return !(prop instanceof AST_ClassGetter || prop instanceof AST_ClassSetter); + }); + }); + def(AST_Conditional, function(compressor) { + return this.consequent._dot_throw(compressor) || this.alternative._dot_throw(compressor); + }); + def(AST_Constant, return_false); + def(AST_Dot, function(compressor, force) { + if (!is_strict(compressor, force)) return false; + var exp = this.expression; + if (exp instanceof AST_SymbolRef) exp = exp.fixed_value(); + return !(this.property == "prototype" && is_lambda(exp)); + }); + def(AST_Lambda, return_false); + def(AST_Null, return_true); + def(AST_Object, function(compressor, force) { + return is_strict(compressor, force) && !all(this.properties, function(prop) { + if (prop instanceof AST_ObjectGetter || prop instanceof AST_ObjectSetter) return false; + return !(prop.key === "__proto__" && prop.value._dot_throw(compressor, force)); + }); + }); + def(AST_ObjectIdentity, function(compressor, force) { + return is_strict(compressor, force) && !this.scope.resolve().new; + }); + def(AST_Sequence, function(compressor) { + return this.tail_node()._dot_throw(compressor); + }); + def(AST_SymbolRef, function(compressor, force) { + if (this.is_undefined) return true; + if (!is_strict(compressor, force)) return false; + if (is_undeclared_ref(this) && this.is_declared(compressor)) return false; + if (this.is_immutable()) return false; + var def = this.definition(); + if (is_arguments(def) && !def.scope.rest && all(def.scope.argnames, function(argname) { + return argname instanceof AST_SymbolFunarg; + })) return def.scope.uses_arguments > 2; + var fixed = this.fixed_value(true); + if (!fixed) return true; + this._dot_throw = return_true; + if (fixed._dot_throw(compressor)) { + delete this._dot_throw; + return true; + } + this._dot_throw = return_false; + return false; + }); + def(AST_UnaryPrefix, function() { + return this.operator == "void"; + }); + def(AST_UnaryPostfix, return_false); + def(AST_Undefined, return_true); + })(function(node, func) { + node.DEFMETHOD("_dot_throw", func); + }); + + (function(def) { + def(AST_Node, return_false); + def(AST_Array, return_true); + function is_binary_defined(compressor, op, node) { + switch (op) { + case "&&": + return node.left.is_defined(compressor) && node.right.is_defined(compressor); + case "||": + return node.left.is_truthy() || node.right.is_defined(compressor); + case "??": + return node.left.is_defined(compressor) || node.right.is_defined(compressor); + default: + return true; + } + } + def(AST_Assign, function(compressor) { + var op = this.operator; + if (op == "=") return this.right.is_defined(compressor); + return is_binary_defined(compressor, op.slice(0, -1), this); + }); + def(AST_Binary, function(compressor) { + return is_binary_defined(compressor, this.operator, this); + }); + def(AST_Conditional, function(compressor) { + return this.consequent.is_defined(compressor) && this.alternative.is_defined(compressor); + }); + def(AST_Constant, return_true); + def(AST_Hole, return_false); + def(AST_Lambda, return_true); + def(AST_Object, return_true); + def(AST_Sequence, function(compressor) { + return this.tail_node().is_defined(compressor); + }); + def(AST_SymbolRef, function(compressor) { + if (this.is_undefined) return false; + if (is_undeclared_ref(this) && this.is_declared(compressor)) return true; + if (this.is_immutable()) return true; + var fixed = this.fixed_value(); + if (!fixed) return false; + this.is_defined = return_false; + var result = fixed.is_defined(compressor); + delete this.is_defined; + return result; + }); + def(AST_UnaryPrefix, function() { + return this.operator != "void"; + }); + def(AST_UnaryPostfix, return_true); + def(AST_Undefined, return_false); + })(function(node, func) { + node.DEFMETHOD("is_defined", func); + }); + + /* -----[ boolean/negation helpers ]----- */ + + // methods to determine whether an expression has a boolean result type + (function(def) { + def(AST_Node, return_false); + def(AST_Assign, function(compressor) { + return this.operator == "=" && this.right.is_boolean(compressor); + }); + var binary = makePredicate("in instanceof == != === !== < <= >= >"); + def(AST_Binary, function(compressor) { + return binary[this.operator] || lazy_op[this.operator] + && this.left.is_boolean(compressor) + && this.right.is_boolean(compressor); + }); + def(AST_Boolean, return_true); + var fn = makePredicate("every hasOwnProperty isPrototypeOf propertyIsEnumerable some"); + def(AST_Call, function(compressor) { + if (!compressor.option("unsafe")) return false; + var exp = this.expression; + return exp instanceof AST_Dot && (fn[exp.property] + || exp.property == "test" && exp.expression instanceof AST_RegExp); + }); + def(AST_Conditional, function(compressor) { + return this.consequent.is_boolean(compressor) && this.alternative.is_boolean(compressor); + }); + def(AST_New, return_false); + def(AST_Sequence, function(compressor) { + return this.tail_node().is_boolean(compressor); + }); + def(AST_SymbolRef, function(compressor) { + var fixed = this.fixed_value(); + if (!fixed) return false; + this.is_boolean = return_false; + var result = fixed.is_boolean(compressor); + delete this.is_boolean; + return result; + }); + var unary = makePredicate("! delete"); + def(AST_UnaryPrefix, function() { + return unary[this.operator]; + }); + })(function(node, func) { + node.DEFMETHOD("is_boolean", func); + }); + + // methods to determine if an expression has a numeric result type + (function(def) { + def(AST_Node, return_false); + var binary = makePredicate("- * / % ** & | ^ << >> >>>"); + def(AST_Assign, function(compressor) { + return binary[this.operator.slice(0, -1)] + || this.operator == "=" && this.right.is_number(compressor); + }); + def(AST_Binary, function(compressor) { + if (binary[this.operator]) return true; + if (this.operator != "+") return false; + return (this.left.is_boolean(compressor) || this.left.is_number(compressor)) + && (this.right.is_boolean(compressor) || this.right.is_number(compressor)); + }); + var fn = makePredicate([ + "charCodeAt", + "getDate", + "getDay", + "getFullYear", + "getHours", + "getMilliseconds", + "getMinutes", + "getMonth", + "getSeconds", + "getTime", + "getTimezoneOffset", + "getUTCDate", + "getUTCDay", + "getUTCFullYear", + "getUTCHours", + "getUTCMilliseconds", + "getUTCMinutes", + "getUTCMonth", + "getUTCSeconds", + "getYear", + "indexOf", + "lastIndexOf", + "localeCompare", + "push", + "search", + "setDate", + "setFullYear", + "setHours", + "setMilliseconds", + "setMinutes", + "setMonth", + "setSeconds", + "setTime", + "setUTCDate", + "setUTCFullYear", + "setUTCHours", + "setUTCMilliseconds", + "setUTCMinutes", + "setUTCMonth", + "setUTCSeconds", + "setYear", + ]); + def(AST_Call, function(compressor) { + if (!compressor.option("unsafe")) return false; + var exp = this.expression; + return exp instanceof AST_Dot && (fn[exp.property] + || is_undeclared_ref(exp.expression) && exp.expression.name == "Math"); + }); + def(AST_Conditional, function(compressor) { + return this.consequent.is_number(compressor) && this.alternative.is_number(compressor); + }); + def(AST_New, return_false); + def(AST_Number, return_true); + def(AST_Sequence, function(compressor) { + return this.tail_node().is_number(compressor); + }); + def(AST_SymbolRef, function(compressor, keep_unary) { + var fixed = this.fixed_value(); + if (!fixed) return false; + if (keep_unary + && fixed instanceof AST_UnaryPrefix + && fixed.operator == "+" + && fixed.expression.equals(this)) { + return false; + } + this.is_number = return_false; + var result = fixed.is_number(compressor); + delete this.is_number; + return result; + }); + var unary = makePredicate("+ - ~ ++ --"); + def(AST_Unary, function() { + return unary[this.operator]; + }); + })(function(node, func) { + node.DEFMETHOD("is_number", func); + }); + + // methods to determine if an expression has a string result type + (function(def) { + def(AST_Node, return_false); + def(AST_Assign, function(compressor) { + switch (this.operator) { + case "+=": + if (this.left.is_string(compressor)) return true; + case "=": + return this.right.is_string(compressor); + } + }); + def(AST_Binary, function(compressor) { + return this.operator == "+" && + (this.left.is_string(compressor) || this.right.is_string(compressor)); + }); + var fn = makePredicate([ + "charAt", + "substr", + "substring", + "toExponential", + "toFixed", + "toLowerCase", + "toPrecision", + "toString", + "toUpperCase", + "trim", + ]); + def(AST_Call, function(compressor) { + if (!compressor.option("unsafe")) return false; + var exp = this.expression; + return exp instanceof AST_Dot && fn[exp.property]; + }); + def(AST_Conditional, function(compressor) { + return this.consequent.is_string(compressor) && this.alternative.is_string(compressor); + }); + def(AST_Sequence, function(compressor) { + return this.tail_node().is_string(compressor); + }); + def(AST_String, return_true); + def(AST_SymbolRef, function(compressor) { + var fixed = this.fixed_value(); + if (!fixed) return false; + this.is_string = return_false; + var result = fixed.is_string(compressor); + delete this.is_string; + return result; + }); + def(AST_Template, function(compressor) { + return !this.tag || is_raw_tag(compressor, this.tag); + }); + def(AST_UnaryPrefix, function() { + return this.operator == "typeof"; + }); + })(function(node, func) { + node.DEFMETHOD("is_string", func); + }); + + var lazy_op = makePredicate("&& || ??"); + + (function(def) { + function to_node(value, orig) { + if (value instanceof AST_Node) return value.clone(true); + if (Array.isArray(value)) return make_node(AST_Array, orig, { + elements: value.map(function(value) { + return to_node(value, orig); + }) + }); + if (value && typeof value == "object") { + var props = []; + for (var key in value) if (HOP(value, key)) { + props.push(make_node(AST_ObjectKeyVal, orig, { + key: key, + value: to_node(value[key], orig), + })); + } + return make_node(AST_Object, orig, { properties: props }); + } + return make_node_from_constant(value, orig); + } + + function warn(node) { + AST_Node.warn("global_defs {this} redefined [{start}]", node); + } + + AST_Toplevel.DEFMETHOD("resolve_defines", function(compressor) { + if (!compressor.option("global_defs")) return this; + this.figure_out_scope({ ie: compressor.option("ie") }); + return this.transform(new TreeTransformer(function(node) { + var def = node._find_defs(compressor, ""); + if (!def) return; + var level = 0, child = node, parent; + while (parent = this.parent(level++)) { + if (!(parent instanceof AST_PropAccess)) break; + if (parent.expression !== child) break; + child = parent; + } + if (is_lhs(child, parent)) { + warn(node); + return; + } + return def; + })); + }); + def(AST_Node, noop); + def(AST_Dot, function(compressor, suffix) { + return this.expression._find_defs(compressor, "." + this.property + suffix); + }); + def(AST_SymbolDeclaration, function(compressor) { + if (!this.definition().global) return; + if (HOP(compressor.option("global_defs"), this.name)) warn(this); + }); + def(AST_SymbolRef, function(compressor, suffix) { + if (!this.definition().global) return; + var defines = compressor.option("global_defs"); + var name = this.name + suffix; + if (HOP(defines, name)) return to_node(defines[name], this); + }); + })(function(node, func) { + node.DEFMETHOD("_find_defs", func); + }); + + function best_of_expression(ast1, ast2, threshold) { + var delta = ast2.print_to_string().length - ast1.print_to_string().length; + return delta < (threshold || 0) ? ast2 : ast1; + } + + function best_of_statement(ast1, ast2, threshold) { + return best_of_expression(make_node(AST_SimpleStatement, ast1, { + body: ast1, + }), make_node(AST_SimpleStatement, ast2, { + body: ast2, + }), threshold).body; + } + + function best_of(compressor, ast1, ast2, threshold) { + return (first_in_statement(compressor) ? best_of_statement : best_of_expression)(ast1, ast2, threshold); + } + + function convert_to_predicate(obj) { + var map = Object.create(null); + Object.keys(obj).forEach(function(key) { + map[key] = makePredicate(obj[key]); + }); + return map; + } + + function skip_directives(body) { + for (var i = 0; i < body.length; i++) { + var stat = body[i]; + if (!(stat instanceof AST_Directive)) return stat; + } + } + + function arrow_first_statement() { + if (this.value) return make_node(AST_Return, this.value, { value: this.value }); + return skip_directives(this.body); + } + AST_Arrow.DEFMETHOD("first_statement", arrow_first_statement); + AST_AsyncArrow.DEFMETHOD("first_statement", arrow_first_statement); + AST_Lambda.DEFMETHOD("first_statement", function() { + return skip_directives(this.body); + }); + + AST_Lambda.DEFMETHOD("length", function() { + var argnames = this.argnames; + for (var i = 0; i < argnames.length; i++) { + if (argnames[i] instanceof AST_DefaultValue) break; + } + return i; + }); + + function try_evaluate(compressor, node) { + var ev = node.evaluate(compressor); + if (ev === node) return node; + ev = make_node_from_constant(ev, node).optimize(compressor); + return best_of(compressor, node, ev, compressor.eval_threshold); + } + + var object_fns = [ + "constructor", + "toString", + "valueOf", + ]; + var native_fns = convert_to_predicate({ + Array: [ + "indexOf", + "join", + "lastIndexOf", + "slice", + ].concat(object_fns), + Boolean: object_fns, + Function: object_fns, + Number: [ + "toExponential", + "toFixed", + "toPrecision", + ].concat(object_fns), + Object: object_fns, + RegExp: [ + "exec", + "test", + ].concat(object_fns), + String: [ + "charAt", + "charCodeAt", + "concat", + "indexOf", + "italics", + "lastIndexOf", + "match", + "replace", + "search", + "slice", + "split", + "substr", + "substring", + "toLowerCase", + "toUpperCase", + "trim", + ].concat(object_fns), + }); + var static_fns = convert_to_predicate({ + Array: [ + "isArray", + ], + Math: [ + "abs", + "acos", + "asin", + "atan", + "ceil", + "cos", + "exp", + "floor", + "log", + "round", + "sin", + "sqrt", + "tan", + "atan2", + "pow", + "max", + "min", + ], + Number: [ + "isFinite", + "isNaN", + ], + Object: [ + "create", + "getOwnPropertyDescriptor", + "getOwnPropertyNames", + "getPrototypeOf", + "isExtensible", + "isFrozen", + "isSealed", + "keys", + ], + String: [ + "fromCharCode", + "raw", + ], + }); + + function is_static_fn(node) { + if (!(node instanceof AST_Dot)) return false; + var expr = node.expression; + if (!is_undeclared_ref(expr)) return false; + var static_fn = static_fns[expr.name]; + return static_fn && (static_fn[node.property] || expr.name == "Math" && node.property == "random"); + } + + // Accommodate when compress option evaluate=false + // as well as the common constant expressions !0 and -1 + (function(def) { + def(AST_Node, return_false); + def(AST_Constant, return_true); + def(AST_RegExp, return_false); + var unaryPrefix = makePredicate("! ~ - + void"); + def(AST_UnaryPrefix, function() { + return unaryPrefix[this.operator] && this.expression instanceof AST_Constant; + }); + })(function(node, func) { + node.DEFMETHOD("is_constant", func); + }); + + // methods to evaluate a constant expression + (function(def) { + // If the node has been successfully reduced to a constant, + // then its value is returned; otherwise the element itself + // is returned. + // + // They can be distinguished as constant value is never a + // descendant of AST_Node. + // + // When `ignore_side_effects` is `true`, inspect the constant value + // produced without worrying about any side effects caused by said + // expression. + AST_Node.DEFMETHOD("evaluate", function(compressor, ignore_side_effects) { + if (!compressor.option("evaluate")) return this; + var cached = []; + var val = this._eval(compressor, ignore_side_effects, cached, 1); + cached.forEach(function(node) { + delete node._eval; + }); + if (ignore_side_effects) return val; + if (!val || val instanceof RegExp) return val; + if (typeof val == "function" || typeof val == "object") return this; + return val; + }); + var scan_modified = new TreeWalker(function(node) { + if (node instanceof AST_Assign) modified(node.left); + if (node instanceof AST_ForEnumeration) modified(node.init); + if (node instanceof AST_Unary && UNARY_POSTFIX[node.operator]) modified(node.expression); + }); + function modified(node) { + if (node instanceof AST_DestructuredArray) { + node.elements.forEach(modified); + } else if (node instanceof AST_DestructuredObject) { + node.properties.forEach(function(prop) { + modified(prop.value); + }); + } else if (node instanceof AST_PropAccess) { + modified(node.expression); + } else if (node instanceof AST_SymbolRef) { + node.definition().references.forEach(function(ref) { + delete ref._eval; + }); + } + } + def(AST_Statement, function() { + throw new Error(string_template("Cannot evaluate a statement [{start}]", this)); + }); + def(AST_Accessor, return_this); + def(AST_BigInt, return_this); + def(AST_Class, return_this); + def(AST_Node, return_this); + def(AST_Constant, function() { + return this.value; + }); + def(AST_Assign, function(compressor, ignore_side_effects, cached, depth) { + var lhs = this.left; + if (!ignore_side_effects) { + if (!(lhs instanceof AST_SymbolRef)) return this; + if (!HOP(lhs, "_eval")) { + if (!lhs.fixed) return this; + var def = lhs.definition(); + if (!def.fixed) return this; + if (def.undeclared) return this; + if (def.last_ref !== lhs) return this; + if (def.single_use == "m") return this; + if (this.right.has_side_effects(compressor)) return this; + } + } + var op = this.operator; + var node; + if (!HOP(lhs, "_eval") && lhs instanceof AST_SymbolRef && lhs.fixed && lhs.definition().fixed) { + node = lhs; + } else if (op == "=") { + node = this.right; + } else { + node = make_node(AST_Binary, this, { + operator: op.slice(0, -1), + left: lhs, + right: this.right, + }); + } + lhs.walk(scan_modified); + var value = node._eval(compressor, ignore_side_effects, cached, depth); + if (typeof value == "object") return this; + modified(lhs); + return value; + }); + def(AST_Sequence, function(compressor, ignore_side_effects, cached, depth) { + if (!ignore_side_effects) return this; + var exprs = this.expressions; + for (var i = 0, last = exprs.length - 1; i < last; i++) { + exprs[i].walk(scan_modified); + } + var tail = exprs[last]; + var value = tail._eval(compressor, ignore_side_effects, cached, depth); + return value === tail ? this : value; + }); + def(AST_Lambda, function(compressor) { + if (compressor.option("unsafe")) { + var fn = function() {}; + fn.node = this; + fn.toString = function() { + return "function(){}"; + }; + return fn; + } + return this; + }); + def(AST_Array, function(compressor, ignore_side_effects, cached, depth) { + if (compressor.option("unsafe")) { + var elements = []; + for (var i = 0; i < this.elements.length; i++) { + var element = this.elements[i]; + if (element instanceof AST_Hole) return this; + var value = element._eval(compressor, ignore_side_effects, cached, depth); + if (element === value) return this; + elements.push(value); + } + return elements; + } + return this; + }); + def(AST_Object, function(compressor, ignore_side_effects, cached, depth) { + if (compressor.option("unsafe")) { + var val = {}; + for (var i = 0; i < this.properties.length; i++) { + var prop = this.properties[i]; + if (!(prop instanceof AST_ObjectKeyVal)) return this; + var key = prop.key; + if (key instanceof AST_Node) { + key = key._eval(compressor, ignore_side_effects, cached, depth); + if (key === prop.key) return this; + } + switch (key) { + case "__proto__": + case "toString": + case "valueOf": + return this; + } + val[key] = prop.value._eval(compressor, ignore_side_effects, cached, depth); + if (val[key] === prop.value) return this; + } + return val; + } + return this; + }); + var non_converting_unary = makePredicate("! typeof void"); + def(AST_UnaryPrefix, function(compressor, ignore_side_effects, cached, depth) { + var e = this.expression; + var op = this.operator; + // Function would be evaluated to an array and so typeof would + // incorrectly return "object". Hence making is a special case. + if (compressor.option("typeofs") + && op == "typeof" + && (e instanceof AST_Lambda + || e instanceof AST_SymbolRef + && e.fixed_value() instanceof AST_Lambda)) { + return typeof function(){}; + } + var def = e instanceof AST_SymbolRef && e.definition(); + if (!non_converting_unary[op] && !(def && def.fixed)) depth++; + e.walk(scan_modified); + var v = e._eval(compressor, ignore_side_effects, cached, depth); + if (v === e) { + if (ignore_side_effects && op == "void") return; + return this; + } + switch (op) { + case "!": return !v; + case "typeof": + // typeof returns "object" or "function" on different platforms + // so cannot evaluate reliably + if (v instanceof RegExp) return this; + return typeof v; + case "void": return; + case "~": return ~v; + case "-": return -v; + case "+": return +v; + case "++": + case "--": + if (!def) return this; + if (!ignore_side_effects) { + if (def.undeclared) return this; + if (def.last_ref !== e) return this; + } + if (HOP(e, "_eval")) v = +(op[0] + 1) + +v; + modified(e); + return v; + } + return this; + }); + def(AST_UnaryPostfix, function(compressor, ignore_side_effects, cached, depth) { + var e = this.expression; + if (!(e instanceof AST_SymbolRef)) { + if (!ignore_side_effects) return this; + } else if (!HOP(e, "_eval")) { + if (!e.fixed) return this; + if (!ignore_side_effects) { + var def = e.definition(); + if (!def.fixed) return this; + if (def.undeclared) return this; + if (def.last_ref !== e) return this; + } + } + if (!(e instanceof AST_SymbolRef && e.definition().fixed)) depth++; + e.walk(scan_modified); + var v = e._eval(compressor, ignore_side_effects, cached, depth); + if (v === e) return this; + modified(e); + return +v; + }); + var non_converting_binary = makePredicate("&& || === !=="); + def(AST_Binary, function(compressor, ignore_side_effects, cached, depth) { + if (!non_converting_binary[this.operator]) depth++; + var left = this.left._eval(compressor, ignore_side_effects, cached, depth); + if (left === this.left) return this; + if (this.operator == (left ? "||" : "&&")) return left; + var rhs_ignore_side_effects = ignore_side_effects && !(left && typeof left == "object"); + var right = this.right._eval(compressor, rhs_ignore_side_effects, cached, depth); + if (right === this.right) return this; + var result; + switch (this.operator) { + case "&&" : result = left && right; break; + case "||" : result = left || right; break; + case "??" : + result = left == null ? right : left; + break; + case "|" : result = left | right; break; + case "&" : result = left & right; break; + case "^" : result = left ^ right; break; + case "+" : result = left + right; break; + case "-" : result = left - right; break; + case "*" : result = left * right; break; + case "/" : result = left / right; break; + case "%" : result = left % right; break; + case "<<" : result = left << right; break; + case ">>" : result = left >> right; break; + case ">>>": result = left >>> right; break; + case "==" : result = left == right; break; + case "===": result = left === right; break; + case "!=" : result = left != right; break; + case "!==": result = left !== right; break; + case "<" : result = left < right; break; + case "<=" : result = left <= right; break; + case ">" : result = left > right; break; + case ">=" : result = left >= right; break; + case "**": + result = Math.pow(left, right); + break; + case "in": + if (right && typeof right == "object" && HOP(right, left)) { + result = true; + break; + } + default: + return this; + } + if (isNaN(result)) return compressor.find_parent(AST_With) ? this : result; + if (compressor.option("unsafe_math") + && !ignore_side_effects + && result + && typeof result == "number" + && (this.operator == "+" || this.operator == "-")) { + var digits = Math.max(0, decimals(left), decimals(right)); + // 53-bit significand ---> 15.95 decimal places + if (digits < 16) return +result.toFixed(digits); + } + return result; + + function decimals(operand) { + var match = /(\.[0-9]*)?(e[^e]+)?$/.exec(+operand); + return (match[1] || ".").length - 1 - (match[2] || "").slice(1); + } + }); + def(AST_Conditional, function(compressor, ignore_side_effects, cached, depth) { + var condition = this.condition._eval(compressor, ignore_side_effects, cached, depth); + if (condition === this.condition) return this; + var node = condition ? this.consequent : this.alternative; + var value = node._eval(compressor, ignore_side_effects, cached, depth); + return value === node ? this : value; + }); + function verify_escaped(ref, depth) { + var escaped = ref.definition().escaped; + switch (escaped.length) { + case 0: + return true; + case 1: + var found = false; + escaped[0].walk(new TreeWalker(function(node) { + if (found) return true; + if (node === ref) return found = true; + if (node instanceof AST_Scope) return true; + })); + return found; + default: + return depth <= escaped.depth; + } + } + def(AST_SymbolRef, function(compressor, ignore_side_effects, cached, depth) { + var fixed = this.fixed_value(); + if (!fixed) return this; + var value; + if (HOP(fixed, "_eval")) { + value = fixed._eval(); + } else { + this._eval = return_this; + value = fixed._eval(compressor, ignore_side_effects, cached, depth); + delete this._eval; + if (value === fixed) return this; + fixed._eval = function() { + return value; + }; + cached.push(fixed); + } + return value && typeof value == "object" && !verify_escaped(this, depth) ? this : value; + }); + var global_objs = { + Array: Array, + Math: Math, + Number: Number, + Object: Object, + String: String, + }; + var static_values = convert_to_predicate({ + Math: [ + "E", + "LN10", + "LN2", + "LOG2E", + "LOG10E", + "PI", + "SQRT1_2", + "SQRT2", + ], + Number: [ + "MAX_VALUE", + "MIN_VALUE", + "NaN", + "NEGATIVE_INFINITY", + "POSITIVE_INFINITY", + ], + }); + var regexp_props = makePredicate("global ignoreCase multiline source"); + def(AST_PropAccess, function(compressor, ignore_side_effects, cached, depth) { + if (compressor.option("unsafe")) { + var val; + var exp = this.expression; + if (!is_undeclared_ref(exp)) { + val = exp._eval(compressor, ignore_side_effects, cached, depth + 1); + if (val == null || val === exp) return this; + } + var key = this.property; + if (key instanceof AST_Node) { + key = key._eval(compressor, ignore_side_effects, cached, depth); + if (key === this.property) return this; + } + if (val === undefined) { + var static_value = static_values[exp.name]; + if (!static_value || !static_value[key]) return this; + val = global_objs[exp.name]; + } else if (val instanceof RegExp) { + if (!regexp_props[key]) return this; + } else if (typeof val == "object") { + if (!HOP(val, key)) return this; + } else if (typeof val == "function") switch (key) { + case "name": + return val.node.name ? val.node.name.name : ""; + case "length": + return val.node.length(); + default: + return this; + } + return val[key]; + } + return this; + }); + function eval_all(nodes, compressor, ignore_side_effects, cached, depth) { + var values = []; + for (var i = 0; i < nodes.length; i++) { + var node = nodes[i]; + var value = node._eval(compressor, ignore_side_effects, cached, depth); + if (node === value) return; + values.push(value); + } + return values; + } + def(AST_Call, function(compressor, ignore_side_effects, cached, depth) { + var exp = this.expression; + var fn = exp instanceof AST_SymbolRef ? exp.fixed_value() : exp; + if (fn instanceof AST_Arrow || fn instanceof AST_Defun || fn instanceof AST_Function) { + if (fn.evaluating) return this; + if (fn.name && fn.name.definition().recursive_refs > 0) return this; + if (this.is_expr_pure(compressor)) return this; + var args = eval_all(this.args, compressor, ignore_side_effects, cached, depth); + if (!all(fn.argnames, function(sym, index) { + if (sym instanceof AST_DefaultValue) { + if (!args) return false; + if (args[index] === undefined) { + var value = sym.value._eval(compressor, ignore_side_effects, cached, depth); + if (value === sym.value) return false; + args[index] = value; + } + sym = sym.name; + } + return !(sym instanceof AST_Destructured); + })) return this; + if (fn.rest instanceof AST_Destructured) return this; + if (!args && !ignore_side_effects) return this; + var stat = fn.first_statement(); + if (!(stat instanceof AST_Return)) { + if (ignore_side_effects) { + fn.walk(scan_modified); + var found = false; + fn.evaluating = true; + walk_body(fn, new TreeWalker(function(node) { + if (found) return true; + if (node instanceof AST_Return) { + if (node.value && node.value._eval(compressor, true, cached, depth) !== undefined) { + found = true; + } + return true; + } + if (node instanceof AST_Scope && node !== fn) return true; + })); + fn.evaluating = false; + if (!found) return; + } + return this; + } + var val = stat.value; + if (!val) return; + var cached_args = []; + if (!args || all(fn.argnames, function(sym, i) { + return assign(sym, args[i]); + }) && !(fn.rest && !assign(fn.rest, args.slice(fn.argnames.length))) || ignore_side_effects) { + if (ignore_side_effects) fn.argnames.forEach(function(sym) { + if (sym instanceof AST_DefaultValue) sym.value.walk(scan_modified); + }); + fn.evaluating = true; + val = val._eval(compressor, ignore_side_effects, cached, depth); + fn.evaluating = false; + } + cached_args.forEach(function(node) { + delete node._eval; + }); + return val === stat.value ? this : val; + } else if (compressor.option("unsafe") && exp instanceof AST_PropAccess) { + var key = exp.property; + if (key instanceof AST_Node) { + key = key._eval(compressor, ignore_side_effects, cached, depth); + if (key === exp.property) return this; + } + var val; + var e = exp.expression; + if (is_undeclared_ref(e)) { + var static_fn = static_fns[e.name]; + if (!static_fn || !static_fn[key]) return this; + val = global_objs[e.name]; + } else { + val = e._eval(compressor, ignore_side_effects, cached, depth + 1); + if (val == null || val === e) return this; + var native_fn = native_fns[val.constructor.name]; + if (!native_fn || !native_fn[key]) return this; + if (val instanceof RegExp && val.global && !(e instanceof AST_RegExp)) return this; + } + var args = eval_all(this.args, compressor, ignore_side_effects, cached, depth); + if (!args) return this; + if (key == "replace" && typeof args[1] == "function") return this; + try { + return val[key].apply(val, args); + } catch (ex) { + AST_Node.warn("Error evaluating {this} [{start}]", this); + } finally { + if (val instanceof RegExp) val.lastIndex = 0; + } + } + return this; + + function assign(sym, arg) { + if (sym instanceof AST_DefaultValue) sym = sym.name; + var def = sym.definition(); + if (def.orig[def.orig.length - 1] !== sym) return false; + var value = arg; + def.references.forEach(function(node) { + node._eval = function() { + return value; + }; + cached_args.push(node); + }); + return true; + } + }); + def(AST_New, return_this); + def(AST_Template, function(compressor, ignore_side_effects, cached, depth) { + if (!compressor.option("templates")) return this; + if (this.tag) { + if (!is_raw_tag(compressor, this.tag)) return this; + decode = function(str) { + return str; + }; + } + var exprs = eval_all(this.expressions, compressor, ignore_side_effects, cached, depth); + if (!exprs) return this; + var malformed = false; + var ret = decode(this.strings[0]); + for (var i = 0; i < exprs.length; i++) { + ret += exprs[i] + decode(this.strings[i + 1]); + } + if (!malformed) return ret; + this._eval = return_this; + return this; + + function decode(str) { + str = decode_template(str); + if (typeof str != "string") malformed = true; + return str; + } + }); + })(function(node, func) { + node.DEFMETHOD("_eval", func); + }); + + // method to negate an expression + (function(def) { + function basic_negation(exp) { + return make_node(AST_UnaryPrefix, exp, { + operator: "!", + expression: exp, + }); + } + function best(orig, alt, first_in_statement) { + var negated = basic_negation(orig); + if (first_in_statement) return best_of_expression(negated, make_node(AST_SimpleStatement, alt, { + body: alt, + })) === negated ? negated : alt; + return best_of_expression(negated, alt); + } + def(AST_Node, function() { + return basic_negation(this); + }); + def(AST_Statement, function() { + throw new Error("Cannot negate a statement"); + }); + def(AST_Binary, function(compressor, first_in_statement) { + var self = this.clone(), op = this.operator; + if (compressor.option("unsafe_comps")) { + switch (op) { + case "<=" : self.operator = ">" ; return self; + case "<" : self.operator = ">=" ; return self; + case ">=" : self.operator = "<" ; return self; + case ">" : self.operator = "<=" ; return self; + } + } + switch (op) { + case "==" : self.operator = "!="; return self; + case "!=" : self.operator = "=="; return self; + case "===": self.operator = "!=="; return self; + case "!==": self.operator = "==="; return self; + case "&&": + self.operator = "||"; + self.left = self.left.negate(compressor, first_in_statement); + self.right = self.right.negate(compressor); + return best(this, self, first_in_statement); + case "||": + self.operator = "&&"; + self.left = self.left.negate(compressor, first_in_statement); + self.right = self.right.negate(compressor); + return best(this, self, first_in_statement); + } + return basic_negation(this); + }); + def(AST_ClassExpression, function() { + return basic_negation(this); + }); + def(AST_Conditional, function(compressor, first_in_statement) { + var self = this.clone(); + self.consequent = self.consequent.negate(compressor); + self.alternative = self.alternative.negate(compressor); + return best(this, self, first_in_statement); + }); + def(AST_LambdaExpression, function() { + return basic_negation(this); + }); + def(AST_Sequence, function(compressor) { + var expressions = this.expressions.slice(); + expressions.push(expressions.pop().negate(compressor)); + return make_sequence(this, expressions); + }); + def(AST_UnaryPrefix, function() { + if (this.operator == "!") + return this.expression; + return basic_negation(this); + }); + })(function(node, func) { + node.DEFMETHOD("negate", function(compressor, first_in_statement) { + return func.call(this, compressor, first_in_statement); + }); + }); + + var global_pure_fns = makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError"); + var global_pure_constructors = makePredicate("Map Set WeakMap WeakSet"); + AST_Call.DEFMETHOD("is_expr_pure", function(compressor) { + if (compressor.option("unsafe")) { + var expr = this.expression; + if (is_undeclared_ref(expr)) { + if (global_pure_fns[expr.name]) return true; + if (this instanceof AST_New && global_pure_constructors[expr.name]) return true; + } + if (is_static_fn(expr)) return true; + } + return compressor.option("annotations") && this.pure || !compressor.pure_funcs(this); + }); + AST_Template.DEFMETHOD("is_expr_pure", function(compressor) { + var tag = this.tag; + if (!tag) return true; + if (compressor.option("unsafe")) { + if (is_undeclared_ref(tag) && global_pure_fns[tag.name]) return true; + if (tag instanceof AST_Dot && is_undeclared_ref(tag.expression)) { + var static_fn = static_fns[tag.expression.name]; + return static_fn && (static_fn[tag.property] + || tag.expression.name == "Math" && tag.property == "random"); + } + } + return !compressor.pure_funcs(this); + }); + AST_Node.DEFMETHOD("is_call_pure", return_false); + AST_Call.DEFMETHOD("is_call_pure", function(compressor) { + if (!compressor.option("unsafe")) return false; + var dot = this.expression; + if (!(dot instanceof AST_Dot)) return false; + var exp = dot.expression; + var map; + var prop = dot.property; + if (exp instanceof AST_Array) { + map = native_fns.Array; + } else if (exp.is_boolean(compressor)) { + map = native_fns.Boolean; + } else if (exp.is_number(compressor)) { + map = native_fns.Number; + } else if (exp instanceof AST_RegExp) { + map = native_fns.RegExp; + } else if (exp.is_string(compressor)) { + map = native_fns.String; + if (prop == "replace") { + var arg = this.args[1]; + if (arg && !arg.is_string(compressor)) return false; + } + } else if (!dot.may_throw_on_access(compressor)) { + map = native_fns.Object; + } + return map && map[prop]; + }); + + // determine if object spread syntax may cause runtime exception + (function(def) { + def(AST_Node, return_false); + def(AST_Array, return_true); + def(AST_Assign, function() { + switch (this.operator) { + case "=": + return this.right.safe_to_spread(); + case "&&=": + case "||=": + case "??=": + return this.left.safe_to_spread() && this.right.safe_to_spread(); + } + return true; + }); + def(AST_Binary, function() { + return !lazy_op[this.operator] || this.left.safe_to_spread() && this.right.safe_to_spread(); + }); + def(AST_Constant, return_true); + def(AST_Lambda, return_true); + def(AST_Object, function() { + return all(this.properties, function(prop) { + return !(prop instanceof AST_ObjectGetter || prop instanceof AST_Spread); + }); + }); + def(AST_Sequence, function() { + return this.tail_node().safe_to_spread(); + }); + def(AST_SymbolRef, function() { + var fixed = this.fixed_value(); + return fixed && fixed.safe_to_spread(); + }); + def(AST_Unary, return_true); + })(function(node, func) { + node.DEFMETHOD("safe_to_spread", func); + }); + + // determine if expression has side effects + (function(def) { + function any(list, compressor, spread) { + return !all(list, spread ? function(node) { + return node instanceof AST_Spread ? !spread(node, compressor) : !node.has_side_effects(compressor); + } : function(node) { + return !node.has_side_effects(compressor); + }); + } + function array_spread(node, compressor) { + var exp = node.expression; + return !exp.is_string(compressor) || exp.has_side_effects(compressor); + } + def(AST_Node, return_true); + def(AST_Array, function(compressor) { + return any(this.elements, compressor, array_spread); + }); + def(AST_Assign, function(compressor) { + var lhs = this.left; + if (!(lhs instanceof AST_PropAccess)) return true; + var node = lhs.expression; + return !(node instanceof AST_ObjectIdentity) + || !node.scope.resolve().new + || lhs instanceof AST_Sub && lhs.property.has_side_effects(compressor) + || this.right.has_side_effects(compressor); + }); + def(AST_Binary, function(compressor) { + return this.left.has_side_effects(compressor) + || this.right.has_side_effects(compressor) + || !can_drop_op(this.operator, this.right, compressor); + }); + def(AST_Block, function(compressor) { + return any(this.body, compressor); + }); + def(AST_Call, function(compressor) { + if (!this.is_expr_pure(compressor) + && (!this.is_call_pure(compressor) || this.expression.has_side_effects(compressor))) { + return true; + } + return any(this.args, compressor, array_spread); + }); + def(AST_Case, function(compressor) { + return this.expression.has_side_effects(compressor) + || any(this.body, compressor); + }); + def(AST_Class, function(compressor) { + var base = this.extends; + if (base) { + if (base instanceof AST_SymbolRef) base = base.fixed_value(); + if (!safe_for_extends(base)) return true; + } + return any(this.properties, compressor); + }); + def(AST_ClassProperty, function(compressor) { + return this.key instanceof AST_Node && this.key.has_side_effects(compressor) + || this.static && this.value && this.value.has_side_effects(compressor); + }); + def(AST_Conditional, function(compressor) { + return this.condition.has_side_effects(compressor) + || this.consequent.has_side_effects(compressor) + || this.alternative.has_side_effects(compressor); + }); + def(AST_Constant, return_false); + def(AST_Definitions, function(compressor) { + return any(this.definitions, compressor); + }); + def(AST_DestructuredArray, function(compressor) { + return any(this.elements, compressor); + }); + def(AST_DestructuredKeyVal, function(compressor) { + return this.key instanceof AST_Node && this.key.has_side_effects(compressor) + || this.value.has_side_effects(compressor); + }); + def(AST_DestructuredObject, function(compressor) { + return any(this.properties, compressor); + }); + def(AST_Dot, function(compressor) { + return this.expression.may_throw_on_access(compressor) + || this.expression.has_side_effects(compressor); + }); + def(AST_EmptyStatement, return_false); + def(AST_If, function(compressor) { + return this.condition.has_side_effects(compressor) + || this.body && this.body.has_side_effects(compressor) + || this.alternative && this.alternative.has_side_effects(compressor); + }); + def(AST_LabeledStatement, function(compressor) { + return this.body.has_side_effects(compressor); + }); + def(AST_Lambda, return_false); + def(AST_Object, function(compressor) { + return any(this.properties, compressor, function(node, compressor) { + var exp = node.expression; + return !exp.safe_to_spread() || exp.has_side_effects(compressor); + }); + }); + def(AST_ObjectIdentity, return_false); + def(AST_ObjectProperty, function(compressor) { + return this.key instanceof AST_Node && this.key.has_side_effects(compressor) + || this.value.has_side_effects(compressor); + }); + def(AST_Sequence, function(compressor) { + return any(this.expressions, compressor); + }); + def(AST_SimpleStatement, function(compressor) { + return this.body.has_side_effects(compressor); + }); + def(AST_Sub, function(compressor) { + return this.expression.may_throw_on_access(compressor) + || this.expression.has_side_effects(compressor) + || this.property.has_side_effects(compressor); + }); + def(AST_Switch, function(compressor) { + return this.expression.has_side_effects(compressor) + || any(this.body, compressor); + }); + def(AST_SymbolDeclaration, return_false); + def(AST_SymbolRef, function(compressor) { + return !this.is_declared(compressor) || !can_drop_symbol(this, compressor); + }); + def(AST_Template, function(compressor) { + return !this.is_expr_pure(compressor) || any(this.expressions, compressor); + }); + def(AST_Try, function(compressor) { + return any(this.body, compressor) + || this.bcatch && this.bcatch.has_side_effects(compressor) + || this.bfinally && this.bfinally.has_side_effects(compressor); + }); + def(AST_Unary, function(compressor) { + return unary_side_effects[this.operator] + || this.expression.has_side_effects(compressor); + }); + def(AST_VarDef, function() { + return this.value; + }); + })(function(node, func) { + node.DEFMETHOD("has_side_effects", func); + }); + + // determine if expression may throw + (function(def) { + def(AST_Node, return_true); + + def(AST_Constant, return_false); + def(AST_EmptyStatement, return_false); + def(AST_Lambda, return_false); + def(AST_ObjectIdentity, return_false); + def(AST_SymbolDeclaration, return_false); + + function any(list, compressor) { + for (var i = list.length; --i >= 0;) + if (list[i].may_throw(compressor)) + return true; + return false; + } + + function call_may_throw(exp, compressor) { + if (exp.may_throw(compressor)) return true; + if (exp instanceof AST_SymbolRef) exp = exp.fixed_value(); + if (!(exp instanceof AST_Lambda)) return true; + if (any(exp.argnames, compressor)) return true; + if (any(exp.body, compressor)) return true; + return is_arrow(exp) && exp.value && exp.value.may_throw(compressor); + } + + def(AST_Array, function(compressor) { + return any(this.elements, compressor); + }); + def(AST_Assign, function(compressor) { + if (this.right.may_throw(compressor)) return true; + if (!compressor.has_directive("use strict") + && this.operator == "=" + && this.left instanceof AST_SymbolRef) { + return false; + } + return this.left.may_throw(compressor); + }); + def(AST_Await, function(compressor) { + return this.expression.may_throw(compressor); + }); + def(AST_Binary, function(compressor) { + return this.left.may_throw(compressor) + || this.right.may_throw(compressor) + || !can_drop_op(this.operator, this.right, compressor); + }); + def(AST_Block, function(compressor) { + return any(this.body, compressor); + }); + def(AST_Call, function(compressor) { + if (any(this.args, compressor)) return true; + if (this.is_expr_pure(compressor)) return false; + this.may_throw = return_true; + var ret = call_may_throw(this.expression, compressor); + delete this.may_throw; + return ret; + }); + def(AST_Case, function(compressor) { + return this.expression.may_throw(compressor) + || any(this.body, compressor); + }); + def(AST_Conditional, function(compressor) { + return this.condition.may_throw(compressor) + || this.consequent.may_throw(compressor) + || this.alternative.may_throw(compressor); + }); + def(AST_DefaultValue, function(compressor) { + return this.name.may_throw(compressor) + || this.value && this.value.may_throw(compressor); + }); + def(AST_Definitions, function(compressor) { + return any(this.definitions, compressor); + }); + def(AST_Dot, function(compressor) { + return !this.optional && this.expression.may_throw_on_access(compressor) + || this.expression.may_throw(compressor); + }); + def(AST_ForEnumeration, function(compressor) { + if (this.init.may_throw(compressor)) return true; + var obj = this.object; + if (obj.may_throw(compressor)) return true; + obj = obj.tail_node(); + if (!(obj instanceof AST_Array || obj.is_string(compressor))) return true; + return this.body.may_throw(compressor); + }); + def(AST_If, function(compressor) { + return this.condition.may_throw(compressor) + || this.body && this.body.may_throw(compressor) + || this.alternative && this.alternative.may_throw(compressor); + }); + def(AST_LabeledStatement, function(compressor) { + return this.body.may_throw(compressor); + }); + def(AST_Object, function(compressor) { + return any(this.properties, compressor); + }); + def(AST_ObjectProperty, function(compressor) { + return this.value.may_throw(compressor) + || this.key instanceof AST_Node && this.key.may_throw(compressor); + }); + def(AST_Return, function(compressor) { + return this.value && this.value.may_throw(compressor); + }); + def(AST_Sequence, function(compressor) { + return any(this.expressions, compressor); + }); + def(AST_SimpleStatement, function(compressor) { + return this.body.may_throw(compressor); + }); + def(AST_Sub, function(compressor) { + return !this.optional && this.expression.may_throw_on_access(compressor) + || this.expression.may_throw(compressor) + || this.property.may_throw(compressor); + }); + def(AST_Switch, function(compressor) { + return this.expression.may_throw(compressor) + || any(this.body, compressor); + }); + def(AST_SymbolRef, function(compressor) { + return !this.is_declared(compressor) || !can_drop_symbol(this, compressor); + }); + def(AST_Template, function(compressor) { + if (any(this.expressions, compressor)) return true; + if (this.is_expr_pure(compressor)) return false; + if (!this.tag) return false; + this.may_throw = return_true; + var ret = call_may_throw(this.tag, compressor); + delete this.may_throw; + return ret; + }); + def(AST_Try, function(compressor) { + return (this.bcatch ? this.bcatch.may_throw(compressor) : any(this.body, compressor)) + || this.bfinally && this.bfinally.may_throw(compressor); + }); + def(AST_Unary, function(compressor) { + return this.expression.may_throw(compressor) + && !(this.operator == "typeof" && this.expression instanceof AST_SymbolRef); + }); + def(AST_VarDef, function(compressor) { + return this.name.may_throw(compressor) + || this.value && this.value.may_throw(compressor); + }); + })(function(node, func) { + node.DEFMETHOD("may_throw", func); + }); + + // determine if expression is constant + (function(def) { + function all_constant(list, scope) { + for (var i = list.length; --i >= 0;) + if (!list[i].is_constant_expression(scope)) + return false; + return true; + } + def(AST_Node, return_false); + def(AST_Array, function(scope) { + return all_constant(this.elements, scope); + }); + def(AST_Binary, function(scope) { + return this.left.is_constant_expression(scope) + && this.right.is_constant_expression(scope) + && can_drop_op(this.operator, this.right); + }); + def(AST_Class, function(scope) { + var base = this.extends; + if (base && !safe_for_extends(base)) return false; + return all_constant(this.properties, scope); + }); + def(AST_ClassProperty, function(scope) { + return typeof this.key == "string" && (!this.value || this.value.is_constant_expression(scope)); + }); + def(AST_Constant, return_true); + def(AST_Lambda, function(scope) { + var self = this; + var result = true; + var scopes = []; + self.walk(new TreeWalker(function(node, descend) { + if (!result) return true; + if (node instanceof AST_BlockScope) { + if (node === self) return; + scopes.push(node); + descend(); + scopes.pop(); + return true; + } + if (node instanceof AST_SymbolRef) { + if (self.inlined || node.redef || node.in_arg) { + result = false; + return true; + } + if (self.variables.has(node.name)) return true; + var def = node.definition(); + if (member(def.scope, scopes)) return true; + if (scope && !def.redefined()) { + var scope_def = scope.find_variable(node.name); + if (scope_def ? scope_def === def : def.undeclared) { + result = "f"; + return true; + } + } + result = false; + return true; + } + if (node instanceof AST_ObjectIdentity) { + if (is_arrow(self) && all(scopes, function(s) { + return !(s instanceof AST_Scope) || is_arrow(s); + })) result = false; + return true; + } + })); + return result; + }); + def(AST_Object, function(scope) { + return all_constant(this.properties, scope); + }); + def(AST_ObjectProperty, function(scope) { + return typeof this.key == "string" && this.value.is_constant_expression(scope); + }); + def(AST_Unary, function(scope) { + return this.expression.is_constant_expression(scope); + }); + })(function(node, func) { + node.DEFMETHOD("is_constant_expression", func); + }); + + // tell me if a statement aborts + function aborts(thing) { + return thing && thing.aborts(); + } + (function(def) { + def(AST_Statement, return_null); + def(AST_Jump, return_this); + function block_aborts() { + var n = this.body.length; + return n > 0 && aborts(this.body[n - 1]); + } + def(AST_BlockStatement, block_aborts); + def(AST_SwitchBranch, block_aborts); + def(AST_If, function() { + return this.alternative && aborts(this.body) && aborts(this.alternative) && this; + }); + })(function(node, func) { + node.DEFMETHOD("aborts", func); + }); + + /* -----[ optimizers ]----- */ + + var directives = makePredicate(["use asm", "use strict"]); + OPT(AST_Directive, function(self, compressor) { + if (compressor.option("directives") + && (!directives[self.value] || compressor.has_directive(self.value) !== self)) { + return make_node(AST_EmptyStatement, self); + } + return self; + }); + + OPT(AST_Debugger, function(self, compressor) { + if (compressor.option("drop_debugger")) + return make_node(AST_EmptyStatement, self); + return self; + }); + + OPT(AST_LabeledStatement, function(self, compressor) { + if (self.body instanceof AST_If || self.body instanceof AST_Break) { + var body = tighten_body([ self.body ], compressor); + switch (body.length) { + case 0: + self.body = make_node(AST_EmptyStatement, self); + break; + case 1: + self.body = body[0]; + break; + default: + self.body = make_node(AST_BlockStatement, self, { body: body }); + break; + } + } + return compressor.option("unused") && self.label.references.length == 0 ? self.body : self; + }); + + OPT(AST_LoopControl, function(self, compressor) { + if (!compressor.option("dead_code")) return self; + var label = self.label; + if (label) { + var lct = compressor.loopcontrol_target(self); + self.label = null; + if (compressor.loopcontrol_target(self) === lct) { + remove(label.thedef.references, self); + } else { + self.label = label; + } + } + return self; + }); + + OPT(AST_Block, function(self, compressor) { + self.body = tighten_body(self.body, compressor); + return self; + }); + + function trim_block(node, parent, in_list) { + switch (node.body.length) { + case 0: + return in_list ? List.skip : make_node(AST_EmptyStatement, node); + case 1: + var stat = node.body[0]; + if (!safe_to_trim(stat)) return node; + if (parent instanceof AST_IterationStatement && stat instanceof AST_LambdaDefinition) return node; + return stat; + } + return node; + } + + OPT(AST_BlockStatement, function(self, compressor) { + self.body = tighten_body(self.body, compressor); + return trim_block(self, compressor.parent()); + }); + + function drop_rest_farg(fn, compressor) { + if (!compressor.option("rests")) return; + if (fn.uses_arguments) return; + if (!(fn.rest instanceof AST_DestructuredArray)) return; + if (!compressor.drop_fargs(fn, compressor.parent())) return; + fn.argnames = fn.argnames.concat(fn.rest.elements); + fn.rest = fn.rest.rest; + } + + OPT(AST_Lambda, function(self, compressor) { + drop_rest_farg(self, compressor); + self.body = tighten_body(self.body, compressor); + return self; + }); + + function opt_arrow(self, compressor) { + if (!compressor.option("arrows")) return self; + drop_rest_farg(self, compressor); + if (self.value) self.body = [ self.first_statement() ]; + var body = tighten_body(self.body, compressor); + switch (body.length) { + case 1: + var stat = body[0]; + if (stat instanceof AST_Return) { + self.body.length = 0; + self.value = stat.value; + break; + } + default: + self.body = body; + self.value = null; + break; + } + return self; + } + OPT(AST_Arrow, opt_arrow); + OPT(AST_AsyncArrow, opt_arrow); + + OPT(AST_Function, function(self, compressor) { + drop_rest_farg(self, compressor); + self.body = tighten_body(self.body, compressor); + var parent = compressor.parent(); + if (compressor.option("inline")) for (var i = 0; i < self.body.length; i++) { + var stat = self.body[i]; + if (stat instanceof AST_Directive) continue; + if (stat instanceof AST_Return) { + if (i != self.body.length - 1) break; + var call = stat.value; + if (!call || call.TYPE != "Call") break; + if (call.is_expr_pure(compressor)) break; + var exp = call.expression, fn; + if (!(exp instanceof AST_SymbolRef)) { + fn = exp; + } else if (self.name && self.name.definition() === exp.definition()) { + break; + } else { + fn = exp.fixed_value(); + } + if (!(fn instanceof AST_Defun || fn instanceof AST_Function)) break; + if (fn.rest) break; + if (fn.uses_arguments) break; + if (fn === exp) { + if (fn.parent_scope !== self) break; + if (!all(fn.enclosed, function(def) { + return def.scope !== self; + })) break; + } + if ((fn !== exp || fn.name) + && (parent instanceof AST_ClassMethod || parent instanceof AST_ObjectMethod) + && parent.value === compressor.self()) break; + if (fn.contains_this()) break; + var len = fn.argnames.length; + if (len > 0 && compressor.option("inline") < 2) break; + if (len > self.argnames.length) break; + if (!all(self.argnames, function(argname) { + return argname instanceof AST_SymbolFunarg; + })) break; + if (!all(call.args, function(arg) { + return !(arg instanceof AST_Spread); + })) break; + for (var j = 0; j < len; j++) { + var arg = call.args[j]; + if (!(arg instanceof AST_SymbolRef)) break; + if (arg.definition() !== self.argnames[j].definition()) break; + } + if (j < len) break; + for (; j < call.args.length; j++) { + if (call.args[j].has_side_effects(compressor)) break; + } + if (j < call.args.length) break; + if (len < self.argnames.length && !compressor.drop_fargs(self, parent)) { + if (!compressor.drop_fargs(fn, call)) break; + do { + fn.argnames.push(fn.make_var(AST_SymbolFunarg, fn, "argument_" + len)); + } while (++len < self.argnames.length); + } + return exp; + } + break; + } + return self; + }); + + var NO_MERGE = makePredicate("arguments await yield"); + AST_Scope.DEFMETHOD("merge_variables", function(compressor) { + if (!compressor.option("merge_vars")) return; + var in_arg = [], in_try, root, segment = {}, self = this; + var first = [], last = [], index = 0; + var declarations = new Dictionary(); + var references = Object.create(null); + var prev = Object.create(null); + var tw = new TreeWalker(function(node, descend) { + if (node instanceof AST_Assign) { + var lhs = node.left; + var rhs = node.right; + if (lhs instanceof AST_Destructured) { + rhs.walk(tw); + walk_destructured(AST_SymbolRef, mark, lhs); + return true; + } + if (lazy_op[node.operator.slice(0, -1)]) { + lhs.walk(tw); + push(); + rhs.walk(tw); + if (lhs instanceof AST_SymbolRef) mark(lhs); + pop(); + return true; + } + if (lhs instanceof AST_SymbolRef) { + if (node.operator != "=") mark(lhs, true); + rhs.walk(tw); + mark(lhs); + return true; + } + return; + } + if (node instanceof AST_Binary) { + if (!lazy_op[node.operator]) return; + walk_cond(node); + return true; + } + if (node instanceof AST_Break) { + var target = tw.loopcontrol_target(node); + if (!(target instanceof AST_IterationStatement)) insert(target); + return true; + } + if (node instanceof AST_Call) { + var exp = node.expression; + if (exp instanceof AST_LambdaExpression) { + node.args.forEach(function(arg) { + arg.walk(tw); + }); + exp.walk(tw); + } else { + descend(); + mark_expression(exp); + } + return true; + } + if (node instanceof AST_Class) { + if (node.name) node.name.walk(tw); + if (node.extends) node.extends.walk(tw); + node.properties.filter(function(prop) { + if (prop.key instanceof AST_Node) prop.key.walk(tw); + return prop.value; + }).forEach(function(prop) { + if (prop.static) { + prop.value.walk(tw); + } else { + push(); + segment.block = node; + prop.value.walk(tw); + pop(); + } + }); + return true; + } + if (node instanceof AST_Conditional) { + walk_cond(node.condition, node.consequent, node.alternative); + return true; + } + if (node instanceof AST_Continue) { + var target = tw.loopcontrol_target(node); + if (target instanceof AST_Do) insert(target); + return true; + } + if (node instanceof AST_Do) { + push(); + segment.block = node; + segment.loop = true; + var save = segment; + node.body.walk(tw); + if (segment.inserted === node) segment = save; + node.condition.walk(tw); + pop(); + return true; + } + if (node instanceof AST_For) { + if (node.init) node.init.walk(tw); + push(); + segment.block = node; + segment.loop = true; + if (node.condition) node.condition.walk(tw); + node.body.walk(tw); + if (node.step) node.step.walk(tw); + pop(); + return true; + } + if (node instanceof AST_ForEnumeration) { + node.object.walk(tw); + push(); + segment.block = node; + segment.loop = true; + node.init.walk(tw); + node.body.walk(tw); + pop(); + return true; + } + if (node instanceof AST_If) { + walk_cond(node.condition, node.body, node.alternative); + return true; + } + if (node instanceof AST_LabeledStatement) { + push(); + segment.block = node; + var save = segment; + node.body.walk(tw); + if (segment.inserted === node) segment = save; + pop(); + return true; + } + if (node instanceof AST_Scope) { + push(); + segment.block = node; + if (node === self) root = segment; + if (node instanceof AST_Lambda) { + if (node.name) references[node.name.definition().id] = false; + var marker = node.uses_arguments && !tw.has_directive("use strict") ? function(node) { + references[node.definition().id] = false; + } : function(node) { + mark(node); + }; + in_arg.push(node); + node.argnames.forEach(function(argname) { + walk_destructured(AST_SymbolFunarg, marker, argname); + }); + if (node.rest) walk_destructured(AST_SymbolFunarg, marker, node.rest); + in_arg.pop(); + } + walk_lambda(node, tw); + pop(); + return true; + } + if (node instanceof AST_Sub) { + var exp = node.expression; + if (node.optional) { + exp.walk(tw); + push(); + node.property.walk(tw); + pop(); + } else { + descend(); + } + mark_expression(exp); + return true; + } + if (node instanceof AST_Switch) { + node.expression.walk(tw); + var save = segment; + node.body.forEach(function(branch) { + if (branch instanceof AST_Default) return; + branch.expression.walk(tw); + if (save === segment) push(); + }); + segment = save; + node.body.forEach(function(branch) { + push(); + segment.block = node; + var save = segment; + walk_body(branch, tw); + if (segment.inserted === node) segment = save; + pop(); + }); + return true; + } + if (node instanceof AST_SymbolConst || node instanceof AST_SymbolLet) { + references[node.definition().id] = false; + return true; + } + if (node instanceof AST_SymbolRef) { + mark(node, true); + return true; + } + if (node instanceof AST_Try) { + var save_try = in_try; + in_try = node; + walk_body(node, tw); + if (node.bcatch) { + if (node.bcatch.argname) node.bcatch.argname.mark_symbol(function(node) { + if (node instanceof AST_SymbolCatch) { + var def = node.definition(); + references[def.id] = false; + if (def = def.redefined()) references[def.id] = false; + } + }, tw); + if (node.bfinally || (in_try = save_try)) { + walk_body(node.bcatch, tw); + } else { + push(); + walk_body(node.bcatch, tw); + pop(); + } + } + in_try = save_try; + if (node.bfinally) node.bfinally.walk(tw); + return true; + } + if (node instanceof AST_Unary) { + if (!UNARY_POSTFIX[node.operator]) return; + var sym = node.expression; + if (!(sym instanceof AST_SymbolRef)) return; + mark(sym, true); + return true; + } + if (node instanceof AST_VarDef) { + var assigned = node.value; + if (assigned) { + assigned.walk(tw); + } else { + assigned = segment.block instanceof AST_ForEnumeration && segment.block.init === tw.parent(); + } + walk_destructured(AST_SymbolDeclaration, assigned ? function(node) { + if (node instanceof AST_SymbolVar) { + mark(node); + } else { + node.walk(tw); + } + } : function(node) { + if (node instanceof AST_SymbolVar) { + var id = node.definition().id; + var refs = references[id]; + if (refs) { + refs.push(node); + } else if (!(id in references)) { + declarations.add(id, node); + } + } else { + node.walk(tw); + } + }, node.name); + return true; + } + if (node instanceof AST_While) { + push(); + segment.block = node; + segment.loop = true; + descend(); + pop(); + return true; + } + + function mark_expression(exp) { + if (!compressor.option("ie")) return; + var sym = root_expr(exp); + if (sym instanceof AST_SymbolRef) sym.walk(tw); + } + + function walk_cond(condition, consequent, alternative) { + var save = segment; + var segments = [ save, save ]; + if (condition instanceof AST_Binary) switch (condition.operator) { + case "&&": + segments[0] = walk_cond(condition.left, condition.right)[0]; + break; + case "||": + case "??": + segments[1] = walk_cond(condition.left, null, condition.right)[1]; + break; + default: + condition.walk(tw); + break; + } else if (condition instanceof AST_Conditional) { + walk_cond(condition.condition, condition.consequent, condition.alternative); + } else { + condition.walk(tw); + } + segment = segments[0]; + if (consequent) { + push(); + consequent.walk(tw); + } + segments[0] = segment; + segment = segments[1]; + if (alternative) { + push(); + alternative.walk(tw); + } + segments[1] = segment; + segment = save; + return segments; + } + }); + tw.directives = Object.create(compressor.directives); + self.walk(tw); + var changed = false; + var merged = Object.create(null); + while (first.length && last.length) { + var tail = last.shift(); + if (!tail) continue; + var def = tail.definition; + var tail_refs = references[def.id]; + if (!tail_refs) continue; + tail_refs = { end: tail_refs.end }; + while (def.id in merged) def = merged[def.id]; + tail_refs.start = references[def.id].start; + var skipped = []; + do { + var head = first.shift(); + if (tail.index > head.index) continue; + var prev_def = head.definition; + if (!(prev_def.id in prev)) continue; + var head_refs = references[prev_def.id]; + if (!head_refs) continue; + if (head_refs.start.block !== tail_refs.start.block + || !mergeable(head_refs, tail_refs) + || (head_refs.start.loop || !same_scope(def)) && !mergeable(tail_refs, head_refs) + || compressor.option("webkit") && is_funarg(def) !== is_funarg(prev_def) + || prev_def.const_redefs + || !all(head_refs.scopes, function(scope) { + return scope.find_variable(def.name) === def; + })) { + skipped.push(head); + continue; + } + head_refs.forEach(function(sym) { + sym.thedef = def; + sym.name = def.name; + if (sym instanceof AST_SymbolRef) { + def.references.push(sym); + prev_def.replaced++; + } else { + def.orig.push(sym); + prev_def.eliminated++; + } + }); + if (!prev_def.fixed) def.fixed = false; + merged[prev_def.id] = def; + changed = true; + break; + } while (first.length); + if (skipped.length) first = skipped.concat(first); + } + return changed; + + function push() { + segment = Object.create(segment); + } + + function pop() { + segment = Object.getPrototypeOf(segment); + } + + function walk_destructured(symbol_type, mark, lhs) { + var marker = new TreeWalker(function(node) { + if (node instanceof AST_Destructured) return; + if (node instanceof AST_DefaultValue) { + push(); + node.value.walk(tw); + pop(); + node.name.walk(marker); + } else if (node instanceof AST_DestructuredKeyVal) { + if (!(node.key instanceof AST_Node)) { + node.value.walk(marker); + } else if (node.value instanceof AST_PropAccess) { + push(); + segment.block = node; + node.key.walk(tw); + node.value.walk(marker); + pop(); + } else { + node.key.walk(tw); + node.value.walk(marker); + } + } else if (node instanceof symbol_type) { + mark(node); + } else { + node.walk(tw); + } + return true; + }); + lhs.walk(marker); + } + + function mark(sym, read) { + var def = sym.definition(), ldef; + if (read && !all(in_arg, function(fn) { + ldef = fn.variables.get(sym.name); + if (!ldef) return true; + if (!is_funarg(ldef)) return true; + return ldef !== def + && !def.undeclared + && fn.parent_scope.find_variable(sym.name) !== def; + })) return references[def.id] = references[ldef.id] = false; + var seg = segment; + if (in_try) { + push(); + seg = segment; + pop(); + } + if (def.id in references) { + var refs = references[def.id]; + if (!refs) return; + if (refs.start.block !== seg.block) return references[def.id] = false; + push_ref(sym); + refs.end = seg; + if (def.id in prev) { + last[prev[def.id]] = null; + } else if (!read) { + return; + } + } else if ((ldef = self.variables.get(def.name)) !== def) { + if (ldef && root === seg) references[ldef.id] = false; + return references[def.id] = false; + } else if (compressor.exposed(def) || NO_MERGE[sym.name]) { + return references[def.id] = false; + } else { + var refs = declarations.get(def.id) || []; + refs.scopes = []; + push_ref(sym); + references[def.id] = refs; + if (!read) { + refs.start = seg; + return first.push({ + index: index++, + definition: def, + }); + } + if (seg.block !== self) return references[def.id] = false; + refs.start = root; + } + prev[def.id] = last.length; + last.push({ + index: index++, + definition: def, + }); + + function push_ref(sym) { + refs.push(sym); + push_uniq(refs.scopes, sym.scope); + var scope = find_scope(tw); + if (scope !== sym.scope) push_uniq(refs.scopes, scope); + } + } + + function insert(target) { + var stack = []; + while (true) { + if (HOP(segment, "block")) { + var block = segment.block; + if (block instanceof AST_LabeledStatement) block = block.body; + if (block === target) break; + } + stack.push(segment); + pop(); + } + segment.inserted = segment.block; + push(); + while (stack.length) { + var seg = stack.pop(); + push(); + if (HOP(seg, "block")) segment.block = seg.block; + if (HOP(seg, "loop")) segment.loop = seg.loop; + } + } + + function must_visit(base, segment) { + return base === segment || base.isPrototypeOf(segment); + } + + function mergeable(head, tail) { + return must_visit(head.start, head.end) || must_visit(head.start, tail.start); + } + }); + + function fill_holes(orig, elements) { + for (var i = elements.length; --i >= 0;) { + if (!elements[i]) elements[i] = make_node(AST_Hole, orig); + } + } + + function to_class_expr(defcl, drop_name) { + var cl = make_node(AST_ClassExpression, defcl); + if (cl.name) cl.name = drop_name ? null : make_node(AST_SymbolClass, cl.name); + return cl; + } + + function to_func_expr(defun, drop_name) { + var ctor; + switch (defun.CTOR) { + case AST_AsyncDefun: + ctor = AST_AsyncFunction; + break; + case AST_AsyncGeneratorDefun: + ctor = AST_AsyncGeneratorFunction; + break; + case AST_Defun: + ctor = AST_Function; + break; + case AST_GeneratorDefun: + ctor = AST_GeneratorFunction; + break; + } + var fn = make_node(ctor, defun); + fn.name = drop_name ? null : make_node(AST_SymbolLambda, defun.name); + return fn; + } + + AST_Scope.DEFMETHOD("drop_unused", function(compressor) { + if (!compressor.option("unused")) return; + var self = this; + var drop_funcs = !(self instanceof AST_Toplevel) || compressor.toplevel.funcs; + var drop_vars = !(self instanceof AST_Toplevel) || compressor.toplevel.vars; + var assign_as_unused = /keep_assign/.test(compressor.option("unused")) ? return_false : function(node, props) { + var sym, nested = false; + if (node instanceof AST_Assign) { + if (node.write_only || node.operator == "=") sym = extract_reference(node.left, props); + } else if (node instanceof AST_Unary) { + if (node.write_only) sym = extract_reference(node.expression, props); + } + if (!(sym instanceof AST_SymbolRef)) return; + var def = sym.definition(); + if (export_defaults[def.id]) return; + if (compressor.exposed(def)) return; + if (!can_drop_symbol(sym, compressor, nested)) return; + return sym; + + function extract_reference(node, props) { + if (node instanceof AST_PropAccess) { + var expr = node.expression; + if (!expr.may_throw_on_access(compressor, true)) { + nested = true; + if (props && node instanceof AST_Sub) props.unshift(node.property); + return extract_reference(expr, props); + } + } else if (node instanceof AST_Assign && node.operator == "=") { + node.write_only = "p"; + var ref = extract_reference(node.right); + if (!props) return ref; + props.assign = node; + return ref instanceof AST_SymbolRef ? ref : node.left; + } + return node; + } + }; + var assign_in_use = Object.create(null); + var export_defaults = Object.create(null); + var find_variable = function(name) { + find_variable = compose(self, 0, noop); + return find_variable(name); + + function compose(child, level, find) { + var parent = compressor.parent(level); + if (!parent) return find; + var in_arg = parent instanceof AST_Lambda && member(child, parent.argnames); + return compose(parent, level + 1, in_arg ? function(name) { + var def = find(name); + if (def) return def; + def = parent.variables.get(name); + if (def) { + var sym = def.orig[0]; + if (sym instanceof AST_SymbolFunarg || sym instanceof AST_SymbolLambda) return def; + } + } : parent.variables ? function(name) { + return find(name) || parent.variables.get(name); + } : find); + } + }; + var for_ins = Object.create(null); + var in_use = []; + var in_use_ids = Object.create(null); // avoid expensive linear scans of in_use + var lambda_ids = Object.create(null); + var value_read = Object.create(null); + var value_modified = Object.create(null); + var var_defs = Object.create(null); + if (self instanceof AST_Toplevel && compressor.top_retain) { + self.variables.each(function(def) { + if (compressor.top_retain(def) && !(def.id in in_use_ids)) { + AST_Node.info("Retaining variable {name}", def); + in_use_ids[def.id] = true; + in_use.push(def); + } + }); + } + var assignments = new Dictionary(); + var initializations = new Dictionary(); + // pass 1: find out which symbols are directly used in + // this scope (not in nested scopes). + var scope = this; + var tw = new TreeWalker(function(node, descend) { + if (node instanceof AST_Lambda && node.uses_arguments && !tw.has_directive("use strict")) { + node.each_argname(function(argname) { + var def = argname.definition(); + if (!(def.id in in_use_ids)) { + in_use_ids[def.id] = true; + in_use.push(def); + } + }); + } + if (node === self) return; + if (scope === self) { + if (node instanceof AST_DefClass) { + var def = node.name.definition(); + var drop = drop_funcs && !def.exported; + if (!drop && !(def.id in in_use_ids)) { + in_use_ids[def.id] = true; + in_use.push(def); + } + var used = tw.parent() instanceof AST_ExportDefault; + if (used) { + export_defaults[def.id] = true; + } else if (drop && !(def.id in lambda_ids)) { + lambda_ids[def.id] = 1; + } + if (node.extends) node.extends.walk(tw); + var values = []; + node.properties.forEach(function(prop) { + if (prop.key instanceof AST_Node) prop.key.walk(tw); + var value = prop.value; + if (!value) return; + if (is_static_field_or_init(prop)) { + if (!used && value.contains_this()) used = true; + walk_class_prop(value); + } else { + values.push(value); + } + }); + values.forEach(drop && used ? walk_class_prop : function(value) { + initializations.add(def.id, value); + }); + return true; + } + if (node instanceof AST_LambdaDefinition) { + var def = node.name.definition(); + var drop = drop_funcs && !def.exported; + if (!drop && !(def.id in in_use_ids)) { + in_use_ids[def.id] = true; + in_use.push(def); + } + initializations.add(def.id, node); + if (tw.parent() instanceof AST_ExportDefault) { + export_defaults[def.id] = true; + return scan_ref_scoped(node, descend, true); + } + if (drop && !(def.id in lambda_ids)) lambda_ids[def.id] = 1; + return true; + } + if (node instanceof AST_Definitions) { + node.definitions.forEach(function(defn) { + var value = defn.value; + var side_effects = value + && (defn.name instanceof AST_Destructured || value.has_side_effects(compressor)); + var shared = side_effects && value.tail_node().operator == "="; + defn.name.mark_symbol(function(name) { + if (!(name instanceof AST_SymbolDeclaration)) return; + var def = name.definition(); + var_defs[def.id] = (var_defs[def.id] || 0) + 1; + if (node instanceof AST_Var && def.orig[0] instanceof AST_SymbolCatch) { + var redef = def.redefined(); + if (redef) var_defs[redef.id] = (var_defs[redef.id] || 0) + 1; + } + if (!(def.id in in_use_ids) && (!drop_vars || def.exported + || (node instanceof AST_Const ? def.redefined() : def.const_redefs) + || !(node instanceof AST_Var || is_safe_lexical(def)))) { + in_use_ids[def.id] = true; + in_use.push(def); + } + if (value) { + if (!side_effects) { + initializations.add(def.id, value); + } else if (shared) { + verify_safe_usage(def, name, value_modified[def.id]); + } + assignments.add(def.id, defn); + } + unmark_lambda(def); + return true; + }, tw); + if (side_effects) value.walk(tw); + }); + return true; + } + if (node instanceof AST_SymbolFunarg) { + var def = node.definition(); + var_defs[def.id] = (var_defs[def.id] || 0) + 1; + assignments.add(def.id, node); + return true; + } + if (node instanceof AST_SymbolImport) { + var def = node.definition(); + if (!(def.id in in_use_ids) && (!drop_vars || !is_safe_lexical(def))) { + in_use_ids[def.id] = true; + in_use.push(def); + } + return true; + } + } + return scan_ref_scoped(node, descend, true); + + function walk_class_prop(value) { + var save_scope = scope; + scope = node; + value.walk(tw); + scope = save_scope; + } + }); + tw.directives = Object.create(compressor.directives); + self.walk(tw); + var drop_fn_name = compressor.option("keep_fnames") ? return_false : compressor.option("ie") ? function(def) { + return !compressor.exposed(def) && def.references.length == def.replaced; + } : function(def) { + if (!(def.id in in_use_ids)) return true; + if (def.orig.length - def.eliminated < 2) return false; + // function argument will always overshadow its name + if (def.orig[1] instanceof AST_SymbolFunarg) return true; + // retain if referenced within destructured object of argument + return all(def.references, function(ref) { + return !ref.in_arg; + }); + }; + if (compressor.option("ie")) initializations.each(function(init, id) { + if (id in in_use_ids) return; + init.forEach(function(init) { + init.walk(new TreeWalker(function(node) { + if (node instanceof AST_Function && node.name && !drop_fn_name(node.name.definition())) { + node.walk(tw); + return true; + } + if (node instanceof AST_Scope) return true; + })); + }); + }); + // pass 2: for every used symbol we need to walk its + // initialization code to figure out if it uses other + // symbols (that may not be in_use). + tw = new TreeWalker(scan_ref_scoped); + for (var i = 0; i < in_use.length; i++) { + var init = initializations.get(in_use[i].id); + if (init) init.forEach(function(init) { + init.walk(tw); + }); + } + Object.keys(assign_in_use).forEach(function(id) { + var assigns = assign_in_use[id]; + if (!assigns) { + delete assign_in_use[id]; + return; + } + assigns = assigns.reduce(function(in_use, assigns) { + assigns.forEach(function(assign) { + push_uniq(in_use, assign); + }); + return in_use; + }, []); + var in_use = (assignments.get(id) || []).filter(function(node) { + return find_if(node instanceof AST_Unary ? function(assign) { + return assign === node; + } : function(assign) { + if (assign === node) return true; + if (assign instanceof AST_Unary) return false; + return get_rvalue(assign) === get_rvalue(node); + }, assigns); + }); + if (assigns.length == in_use.length) { + assign_in_use[id] = in_use; + } else { + delete assign_in_use[id]; + } + }); + // pass 3: we should drop declarations not in_use + var calls_to_drop_args = []; + var fns_with_marked_args = []; + var trimmer = new TreeTransformer(function(node) { + if (node instanceof AST_DefaultValue) return trim_default(trimmer, node); + if (node instanceof AST_Destructured && node.rest) node.rest = node.rest.transform(trimmer); + if (node instanceof AST_DestructuredArray) { + var trim = !node.rest; + for (var i = node.elements.length; --i >= 0;) { + var element = node.elements[i].transform(trimmer); + if (element) { + node.elements[i] = element; + trim = false; + } else if (trim) { + node.elements.pop(); + } else { + node.elements[i] = make_node(AST_Hole, node.elements[i]); + } + } + return node; + } + if (node instanceof AST_DestructuredObject) { + var properties = []; + node.properties.forEach(function(prop) { + var retain = false; + if (prop.key instanceof AST_Node) { + prop.key = prop.key.transform(tt); + retain = prop.key.has_side_effects(compressor); + } + if ((retain || node.rest) && is_decl(prop.value)) { + prop.value = prop.value.transform(tt); + properties.push(prop); + } else { + var value = prop.value.transform(trimmer); + if (!value && node.rest) { + if (prop.value instanceof AST_DestructuredArray) { + value = make_node(AST_DestructuredArray, prop.value, { elements: [] }); + } else { + value = make_node(AST_DestructuredObject, prop.value, { properties: [] }); + } + } + if (value) { + prop.value = value; + properties.push(prop); + } + } + }); + node.properties = properties; + return node; + } + if (node instanceof AST_SymbolDeclaration) return trim_decl(node); + }); + var tt = new TreeTransformer(function(node, descend, in_list) { + var parent = tt.parent(); + if (drop_vars) { + var props = [], sym = assign_as_unused(node, props); + if (sym) { + var value; + if (can_drop_lhs(sym, node)) { + if (node instanceof AST_Assign) { + value = get_rhs(node); + if (node.write_only === true) value = value.drop_side_effect_free(compressor); + } + if (!value) value = make_node(AST_Number, node, { value: 0 }); + } + if (value) { + if (props.assign) { + var assign = props.assign.drop_side_effect_free(compressor); + if (assign) { + assign.write_only = true; + props.unshift(assign); + } + } + if (!(parent instanceof AST_Sequence) + || parent.tail_node() === node + || value.has_side_effects(compressor)) { + props.push(value); + } + switch (props.length) { + case 0: + return List.skip; + case 1: + return maintain_this_binding(parent, node, props[0].transform(tt)); + default: + return make_sequence(node, props.map(function(prop) { + return prop.transform(tt); + })); + } + } + } else if (node instanceof AST_UnaryPostfix + && node.expression instanceof AST_SymbolRef + && indexOf_assign(node.expression.definition(), node) < 0) { + return make_node(AST_UnaryPrefix, node, { + operator: "+", + expression: node.expression, + }); + } + } + if (node instanceof AST_Binary && node.operator == "instanceof") { + var sym = node.right; + if (!(sym instanceof AST_SymbolRef)) return; + if (sym.definition().id in in_use_ids) return; + var lhs = node.left.drop_side_effect_free(compressor); + var value = make_node(AST_False, node).optimize(compressor); + return lhs ? make_sequence(node, [ lhs, value ]) : value; + } + if (node instanceof AST_Call) { + calls_to_drop_args.push(node); + node.args = node.args.map(function(arg) { + return arg.transform(tt); + }); + node.expression = node.expression.transform(tt); + return node; + } + if (scope !== self) return; + if (drop_funcs && node !== self && node instanceof AST_DefClass) { + var def = node.name.definition(); + if (!(def.id in in_use_ids)) { + log(node.name, "Dropping unused class {name}"); + def.eliminated++; + descend(node, tt); + var trimmed = to_class_expr(node, true); + if (parent instanceof AST_ExportDefault) return trimmed; + trimmed = trimmed.drop_side_effect_free(compressor, true); + if (trimmed) return make_node(AST_SimpleStatement, node, { body: trimmed }); + return in_list ? List.skip : make_node(AST_EmptyStatement, node); + } + } + if (node instanceof AST_ClassExpression && node.name && drop_fn_name(node.name.definition())) { + node.name = null; + } + if (node instanceof AST_Lambda) { + if (drop_funcs && node !== self && node instanceof AST_LambdaDefinition) { + var def = node.name.definition(); + if (!(def.id in in_use_ids)) { + log(node.name, "Dropping unused function {name}"); + def.eliminated++; + if (parent instanceof AST_ExportDefault) { + descend_scope(); + return to_func_expr(node, true); + } + return in_list ? List.skip : make_node(AST_EmptyStatement, node); + } + } + descend_scope(); + if (node instanceof AST_LambdaExpression && node.name && drop_fn_name(node.name.definition())) { + node.name = null; + } + if (!(node instanceof AST_Accessor)) { + var args, spread, trim = compressor.drop_fargs(node, parent); + if (trim && parent instanceof AST_Call && parent.expression === node) { + args = parent.args; + for (spread = 0; spread < args.length; spread++) { + if (args[spread] instanceof AST_Spread) break; + } + } + var argnames = node.argnames; + var rest = node.rest; + var after = false, before = false; + if (rest) { + before = true; + if (!args || spread < argnames.length || rest instanceof AST_SymbolFunarg) { + rest = rest.transform(trimmer); + } else { + var trimmed = trim_destructured(rest, make_node(AST_Array, parent, { + elements: args.slice(argnames.length), + }), trim_decl, !node.uses_arguments, rest); + rest = trimmed.name; + args.length = argnames.length; + if (trimmed.value.elements.length) [].push.apply(args, trimmed.value.elements); + } + if (rest instanceof AST_Destructured && !rest.rest) { + if (rest instanceof AST_DestructuredArray) { + if (rest.elements.length == 0) rest = null; + } else if (rest.properties.length == 0) { + rest = null; + } + } + node.rest = rest; + if (rest) { + trim = false; + after = true; + } + } + var default_length = trim ? -1 : node.length(); + var trim_value = args && !node.uses_arguments && parent !== compressor.parent(); + for (var i = argnames.length; --i >= 0;) { + var sym = argnames[i]; + if (sym instanceof AST_SymbolFunarg) { + var def = sym.definition(); + if (def.id in in_use_ids) { + trim = false; + if (indexOf_assign(def, sym) < 0) sym.unused = null; + } else if (trim) { + log(sym, "Dropping unused function argument {name}"); + argnames.pop(); + def.eliminated++; + sym.unused = true; + } else { + sym.unused = true; + } + } else { + before = true; + var funarg; + if (!args || spread < i) { + funarg = sym.transform(trimmer); + } else { + var trimmed = trim_destructured(sym, args[i], trim_decl, trim_value, sym); + funarg = trimmed.name; + if (trimmed.value) args[i] = trimmed.value; + } + if (funarg) { + trim = false; + argnames[i] = funarg; + if (!after) after = !(funarg instanceof AST_SymbolFunarg); + } else if (trim) { + log_default(sym, "Dropping unused default argument {name}"); + argnames.pop(); + } else if (i > default_length) { + log_default(sym, "Dropping unused default argument assignment {name}"); + if (sym.name instanceof AST_SymbolFunarg) { + sym.name.unused = true; + } else { + after = true; + } + argnames[i] = sym.name; + } else { + log_default(sym, "Dropping unused default argument value {name}"); + argnames[i] = sym = sym.clone(); + sym.value = make_node(AST_Number, sym, { value: 0 }); + after = true; + } + } + } + if (before && !after && node.uses_arguments && !tt.has_directive("use strict")) { + node.rest = make_node(AST_DestructuredArray, node, { elements: [] }); + } + fns_with_marked_args.push(node); + } + return node; + } + if (node instanceof AST_Catch && node.argname instanceof AST_Destructured) { + node.argname.transform(trimmer); + } + if (node instanceof AST_Definitions && !(parent instanceof AST_ForEnumeration && parent.init === node)) { + // place uninitialized names at the start + var body = [], head = [], tail = []; + // for unused names whose initialization has + // side effects, we can cascade the init. code + // into the next one, or next statement. + var side_effects = []; + var duplicated = 0; + var is_var = node instanceof AST_Var; + node.definitions.forEach(function(def) { + if (def.value) def.value = def.value.transform(tt); + var value = def.value; + if (def.name instanceof AST_Destructured) { + var trimmed = trim_destructured(def.name, value, function(node) { + if (!drop_vars) return node; + if (node.definition().id in in_use_ids) return node; + if (is_catch(node)) return node; + if (is_var && !can_drop_symbol(node)) return node; + return null; + }, true); + if (trimmed.name) { + def = make_node(AST_VarDef, def, { + name: trimmed.name, + value: value = trimmed.value, + }); + flush(); + } else if (trimmed.value) { + side_effects.push(trimmed.value); + } + return; + } + var sym = def.name.definition(); + var drop_sym = is_var ? can_drop_symbol(def.name) : is_safe_lexical(sym); + if (!drop_sym || !drop_vars || sym.id in in_use_ids) { + var index; + if (value && ((index = indexOf_assign(sym, def)) < 0 || self_assign(value.tail_node()))) { + def = def.clone(); + value = value.drop_side_effect_free(compressor); + if (value) AST_Node.warn("Side effects in definition of variable {name} [{start}]", def.name); + if (node instanceof AST_Const) { + def.value = value || make_node(AST_Number, def, { value: 0 }); + } else { + def.value = null; + if (value) side_effects.push(value); + } + value = null; + if (index >= 0) assign_in_use[sym.id][index] = def; + } + var old_def, fn; + if (!value && !(node instanceof AST_Let)) { + if (parent instanceof AST_ExportDeclaration) { + flush(); + } else if (drop_sym && var_defs[sym.id] > 1) { + AST_Node.info("Dropping declaration of variable {name} [{start}]", def.name); + var_defs[sym.id]--; + sym.eliminated++; + } else { + head.push(def); + } + } else if (compressor.option("functions") + && !compressor.option("ie") + && drop_sym + && value + && var_defs[sym.id] == 1 + && sym.assignments == 0 + && (fn = value.tail_node()) instanceof AST_LambdaExpression + && !is_arguments(sym) + && !is_arrow(fn) + && assigned_once(fn, sym.references) + && can_declare_defun(fn) + && (old_def = rename_def(fn, def.name.name)) !== false) { + AST_Node.warn("Declaring {name} as function [{start}]", def.name); + var ctor; + switch (fn.CTOR) { + case AST_AsyncFunction: + ctor = AST_AsyncDefun; + break; + case AST_AsyncGeneratorFunction: + ctor = AST_AsyncGeneratorDefun; + break; + case AST_Function: + ctor = AST_Defun; + break; + case AST_GeneratorFunction: + ctor = AST_GeneratorDefun; + break; + } + var defun = make_node(ctor, fn); + defun.name = make_node(AST_SymbolDefun, def.name); + var name_def = def.name.scope.resolve().def_function(defun.name); + if (old_def) old_def.forEach(function(node) { + node.name = name_def.name; + node.thedef = name_def; + node.reference(); + }); + body.push(defun); + if (value !== fn) [].push.apply(side_effects, value.expressions.slice(0, -1)); + } else { + if (drop_sym + && var_defs[sym.id] > 1 + && !(parent instanceof AST_ExportDeclaration) + && sym.orig.indexOf(def.name) > sym.eliminated) { + var_defs[sym.id]--; + duplicated++; + } + flush(); + } + } else if (is_catch(def.name)) { + value = value && value.drop_side_effect_free(compressor); + if (value) side_effects.push(value); + if (var_defs[sym.id] > 1) { + AST_Node.warn("Dropping duplicated declaration of variable {name} [{start}]", def.name); + var_defs[sym.id]--; + sym.eliminated++; + } else { + def.value = null; + head.push(def); + } + } else { + value = value && value.drop_side_effect_free(compressor); + if (value) { + AST_Node.warn("Side effects in initialization of unused variable {name} [{start}]", def.name); + side_effects.push(value); + } else { + log(def.name, "Dropping unused variable {name}"); + } + sym.eliminated++; + } + + function self_assign(ref) { + return ref instanceof AST_SymbolRef && ref.definition() === sym; + } + + function assigned_once(fn, refs) { + if (refs.length == 0) return fn === def.name.fixed_value(); + return all(refs, function(ref) { + return fn === ref.fixed_value(); + }); + } + + function can_declare_defun(fn) { + if (!is_var || compressor.has_directive("use strict") || !(fn instanceof AST_Function)) { + return parent instanceof AST_Scope; + } + return parent instanceof AST_Block + || parent instanceof AST_For && parent.init === node + || parent instanceof AST_If; + } + + function rename_def(fn, name) { + if (!fn.name) return null; + var def = fn.name.definition(); + if (def.orig.length > 1) return null; + if (def.assignments > 0) return false; + if (def.name == name) return def; + if (compressor.option("keep_fnames")) return false; + var forbidden; + switch (name) { + case "await": + forbidden = is_async; + break; + case "yield": + forbidden = is_generator; + break; + } + return all(def.references, function(ref) { + var scope = ref.scope; + if (scope.find_variable(name) !== sym) return false; + if (forbidden) do { + scope = scope.resolve(); + if (forbidden(scope)) return false; + } while (scope !== fn && (scope = scope.parent_scope)); + return true; + }) && def; + } + + function is_catch(node) { + var sym = node.definition(); + return sym.orig[0] instanceof AST_SymbolCatch && sym.scope.resolve() === node.scope.resolve(); + } + + function flush() { + if (side_effects.length > 0) { + if (tail.length == 0) { + body.push(make_node(AST_SimpleStatement, node, { + body: make_sequence(node, side_effects), + })); + } else if (value) { + side_effects.push(value); + def.value = make_sequence(value, side_effects); + } else { + def.value = make_node(AST_UnaryPrefix, def, { + operator: "void", + expression: make_sequence(def, side_effects), + }); + } + side_effects = []; + } + tail.push(def); + } + }); + switch (head.length) { + case 0: + if (tail.length == 0) break; + if (tail.length == duplicated) { + [].unshift.apply(side_effects, tail.map(function(def) { + AST_Node.info("Dropping duplicated definition of variable {name} [{start}]", def.name); + var sym = def.name.definition(); + var ref = make_node(AST_SymbolRef, def.name); + sym.references.push(ref); + var assign = make_node(AST_Assign, def, { + operator: "=", + left: ref, + right: def.value, + }); + var index = indexOf_assign(sym, def); + if (index >= 0) assign_in_use[sym.id][index] = assign; + sym.assignments++; + sym.eliminated++; + return assign; + })); + break; + } + case 1: + if (tail.length == 0) { + var id = head[0].name.definition().id; + if (id in for_ins) { + node.definitions = head; + for_ins[id].init = node; + break; + } + } + default: + var seq; + if (tail.length > 0 && (seq = tail[0].value) instanceof AST_Sequence) { + tail[0].value = seq.tail_node(); + body.push(make_node(AST_SimpleStatement, node, { + body: make_sequence(seq, seq.expressions.slice(0, -1)), + })); + } + node.definitions = head.concat(tail); + body.push(node); + } + if (side_effects.length > 0) { + body.push(make_node(AST_SimpleStatement, node, { body: make_sequence(node, side_effects) })); + } + return insert_statements(body, node, in_list); + } + if (node instanceof AST_Assign) { + descend(node, tt); + if (!(node.left instanceof AST_Destructured)) return node; + var trimmed = trim_destructured(node.left, node.right, function(node) { + return node; + }, node.write_only === true); + if (trimmed.name) return make_node(AST_Assign, node, { + operator: node.operator, + left: trimmed.name, + right: trimmed.value, + }); + if (trimmed.value) return trimmed.value; + if (parent instanceof AST_Sequence && parent.tail_node() !== node) return List.skip; + return make_node(AST_Number, node, { value: 0 }); + } + if (node instanceof AST_LabeledStatement && node.body instanceof AST_For) { + // Certain combination of unused name + side effect leads to invalid AST: + // https://github.com/mishoo/UglifyJS/issues/1830 + // We fix it at this stage by moving the label inwards, back to the `for`. + descend(node, tt); + if (node.body instanceof AST_BlockStatement) { + var block = node.body; + node.body = block.body.pop(); + block.body.push(node); + return in_list ? List.splice(block.body) : block; + } + return node; + } + if (node instanceof AST_Scope) { + descend_scope(); + return node; + } + if (node instanceof AST_SymbolImport) { + if (!compressor.option("imports") || node.definition().id in in_use_ids) return node; + return in_list ? List.skip : null; + } + + function descend_scope() { + var save_scope = scope; + scope = node; + descend(node, tt); + scope = save_scope; + } + }, function(node, in_list) { + if (node instanceof AST_BlockStatement) return trim_block(node, tt.parent(), in_list); + if (node instanceof AST_ExportDeclaration) { + var block = node.body; + if (!(block instanceof AST_BlockStatement)) return; + node.body = block.body.pop(); + block.body.push(node); + return in_list ? List.splice(block.body) : block; + } + if (node instanceof AST_For) return patch_for_init(node, in_list); + if (node instanceof AST_ForIn) { + if (!drop_vars || !compressor.option("loops")) return; + if (!is_empty(node.body)) return; + var sym = get_init_symbol(node); + if (!sym) return; + var def = sym.definition(); + if (def.id in in_use_ids) return; + log(sym, "Dropping unused loop variable {name}"); + if (for_ins[def.id] === node) delete for_ins[def.id]; + var body = []; + var value = node.object.drop_side_effect_free(compressor); + if (value) { + AST_Node.warn("Side effects in object of for-in loop [{start}]", value); + body.push(make_node(AST_SimpleStatement, node, { body: value })); + } + if (node.init instanceof AST_Definitions && def.orig[0] instanceof AST_SymbolCatch) { + body.push(node.init); + } + return insert_statements(body, node, in_list); + } + if (node instanceof AST_Import) { + if (node.properties && node.properties.length == 0) node.properties = null; + return node; + } + if (node instanceof AST_Sequence) { + if (node.expressions.length > 1) return; + return maintain_this_binding(tt.parent(), node, node.expressions[0]); + } + }); + tt.push(compressor.parent()); + tt.directives = Object.create(compressor.directives); + self.transform(tt); + if (self instanceof AST_Lambda + && self.body.length == 1 + && self.body[0] instanceof AST_Directive + && self.body[0].value == "use strict") { + self.body.length = 0; + } + calls_to_drop_args.forEach(function(call) { + drop_unused_call_args(call, compressor, fns_with_marked_args); + }); + + function log(sym, text) { + AST_Node[sym.definition().references.length > 0 ? "info" : "warn"](text + " [{start}]", sym); + } + + function log_default(node, text) { + if (node.name instanceof AST_SymbolFunarg) { + log(node.name, text); + } else { + AST_Node.info(text + " [{start}]", node); + } + } + + function get_rvalue(expr) { + return expr[expr instanceof AST_Assign ? "right" : "value"]; + } + + function insert_statements(body, orig, in_list) { + switch (body.length) { + case 0: + return in_list ? List.skip : make_node(AST_EmptyStatement, orig); + case 1: + return body[0]; + default: + return in_list ? List.splice(body) : make_node(AST_BlockStatement, orig, { body: body }); + } + } + + function track_assigns(def, node) { + if (def.scope.resolve() !== self) return false; + if (!def.fixed || !node.fixed) assign_in_use[def.id] = false; + return assign_in_use[def.id] !== false; + } + + function add_assigns(def, node) { + if (!assign_in_use[def.id]) assign_in_use[def.id] = []; + if (node.fixed.assigns) push_uniq(assign_in_use[def.id], node.fixed.assigns); + } + + function indexOf_assign(def, node) { + var nodes = assign_in_use[def.id]; + return nodes && nodes.indexOf(node); + } + + function unmark_lambda(def) { + if (lambda_ids[def.id] > 1 && !(def.id in in_use_ids)) { + in_use_ids[def.id] = true; + in_use.push(def); + } + lambda_ids[def.id] = 0; + } + + function verify_safe_usage(def, read, modified) { + if (def.id in in_use_ids) return; + if (read && modified) { + in_use_ids[def.id] = read; + in_use.push(def); + } else { + value_read[def.id] = read; + value_modified[def.id] = modified; + } + } + + function can_drop_lhs(sym, node) { + var def = sym.definition(); + var in_use = in_use_ids[def.id]; + if (!in_use) return true; + if (node[node instanceof AST_Assign ? "left" : "expression"] !== sym) return false; + return in_use === sym && def.references.length - def.replaced == 1 || indexOf_assign(def, node) < 0; + } + + function get_rhs(assign) { + var rhs = assign.right; + if (!assign.write_only) return rhs; + if (!(rhs instanceof AST_Binary && lazy_op[rhs.operator])) return rhs; + if (!(rhs.left instanceof AST_SymbolRef)) return rhs; + if (!(assign.left instanceof AST_SymbolRef)) return rhs; + var def = assign.left.definition(); + if (rhs.left.definition() !== def) return rhs; + if (rhs.right.has_side_effects(compressor)) return rhs; + if (track_assigns(def, rhs.left)) add_assigns(def, rhs.left); + return rhs.right; + } + + function get_init_symbol(for_in) { + var init = for_in.init; + if (init instanceof AST_Definitions) { + init = init.definitions[0].name; + return init instanceof AST_SymbolDeclaration && init; + } + while (init instanceof AST_PropAccess) init = init.expression.tail_node(); + if (init instanceof AST_SymbolRef) return init; + } + + function scan_ref_scoped(node, descend, init) { + if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef) { + var def = node.left.definition(); + if (def.scope.resolve() === self) assignments.add(def.id, node); + } + if (node instanceof AST_SymbolRef && node.in_arg) var_defs[node.definition().id] = 0; + if (node instanceof AST_Unary && node.expression instanceof AST_SymbolRef) { + var def = node.expression.definition(); + if (def.scope.resolve() === self) assignments.add(def.id, node); + } + var props = [], sym = assign_as_unused(node, props); + if (sym) { + var node_def = sym.definition(); + if (node_def.scope.resolve() !== self && self.variables.get(sym.name) !== node_def) return; + if (is_arguments(node_def) && !all(self.argnames, function(argname) { + return !argname.match_symbol(function(node) { + if (node instanceof AST_SymbolFunarg) { + var def = node.definition(); + return def.references.length > def.replaced; + } + }, true); + })) return; + if (node.write_only === "p" && node.right.may_throw_on_access(compressor, true)) return; + var assign = props.assign; + if (assign) { + assign.write_only = true; + assign.walk(tw); + } + props.forEach(function(prop) { + prop.walk(tw); + }); + if (node instanceof AST_Assign) { + var right = get_rhs(node), shared = false; + if (init && node.write_only === true && !right.has_side_effects(compressor)) { + initializations.add(node_def.id, right); + } else { + right.walk(tw); + shared = right.tail_node().operator == "="; + } + if (node.left === sym) { + if (!node.write_only || shared) { + verify_safe_usage(node_def, sym, value_modified[node_def.id]); + } + } else { + var fixed = sym.fixed_value(); + if (!fixed || !fixed.is_constant()) { + verify_safe_usage(node_def, value_read[node_def.id], true); + } + } + } + if (track_assigns(node_def, sym) && is_lhs(sym, node) !== sym) add_assigns(node_def, sym); + unmark_lambda(node_def); + return true; + } + if (node instanceof AST_Binary) { + if (node.operator != "instanceof") return; + var sym = node.right; + if (!(sym instanceof AST_SymbolRef)) return; + var id = sym.definition().id; + if (!lambda_ids[id]) return; + node.left.walk(tw); + lambda_ids[id]++; + return true; + } + if (node instanceof AST_ForIn) { + if (node.init instanceof AST_SymbolRef && scope === self) { + var id = node.init.definition().id; + if (!(id in for_ins)) for_ins[id] = node; + } + if (!drop_vars || !compressor.option("loops")) return; + if (!is_empty(node.body)) return; + if (node.init.has_side_effects(compressor)) return; + var sym = get_init_symbol(node); + if (!sym) return; + var def = sym.definition(); + if (def.scope.resolve() !== self) { + var d = find_variable(sym.name); + if (d === def || d && d.redefined() === def) return; + } + node.object.walk(tw); + return true; + } + if (node instanceof AST_SymbolRef) { + var node_def = node.definition(); + if (!(node_def.id in in_use_ids)) { + in_use_ids[node_def.id] = true; + in_use.push(node_def); + } + if (cross_scope(node_def.scope, node.scope)) { + var redef = node_def.redefined(); + if (redef && !(redef.id in in_use_ids)) { + in_use_ids[redef.id] = true; + in_use.push(redef); + } + } + if (track_assigns(node_def, node)) add_assigns(node_def, node); + return true; + } + if (node instanceof AST_Scope) { + var save_scope = scope; + scope = node; + descend(); + scope = save_scope; + return true; + } + } + + function is_decl(node) { + return (node instanceof AST_DefaultValue ? node.name : node) instanceof AST_SymbolDeclaration; + } + + function trim_decl(node) { + if (node.definition().id in in_use_ids) return node; + if (node instanceof AST_SymbolFunarg) node.unused = true; + return null; + } + + function trim_default(trimmer, node) { + node.value = node.value.transform(tt); + var name = node.name.transform(trimmer); + if (!name) { + if (node.name instanceof AST_Destructured) return null; + var value = node.value.drop_side_effect_free(compressor); + if (!value) return null; + log(node.name, "Side effects in default value of unused variable {name}"); + node = node.clone(); + node.name.unused = null; + node.value = value; + } + return node; + } + + function trim_destructured(node, value, process, drop, root) { + var trimmer = new TreeTransformer(function(node) { + if (node instanceof AST_DefaultValue) { + if (!(compressor.option("default_values") && value && value.is_defined(compressor))) { + var save_drop = drop; + drop = false; + var trimmed = trim_default(trimmer, node); + drop = save_drop; + if (!trimmed && drop && value) value = value.drop_side_effect_free(compressor); + return trimmed; + } else if (node === root) { + root = node = node.name; + } else { + node = node.name; + } + } + if (node instanceof AST_DestructuredArray) { + var save_drop = drop; + var save_value = value; + if (value instanceof AST_SymbolRef) { + drop = false; + value = value.fixed_value(); + } + var native, values; + if (value instanceof AST_Array) { + native = true; + values = value.elements; + } else { + native = value && value.is_string(compressor); + values = false; + } + var elements = [], newValues = drop && [], pos = 0; + node.elements.forEach(function(element, index) { + value = values && values[index]; + if (value instanceof AST_Hole) { + value = null; + } else if (value instanceof AST_Spread) { + if (drop) { + newValues.length = pos; + fill_holes(save_value, newValues); + [].push.apply(newValues, values.slice(index)); + save_value.elements = newValues; + } + value = values = false; + } + element = element.transform(trimmer); + if (element) elements[pos] = element; + if (drop && value) newValues[pos] = value; + if (element || value || !drop || !values) pos++; + }); + value = values && make_node(AST_Array, save_value, { + elements: values.slice(node.elements.length), + }); + if (node.rest) { + var was_drop = drop; + drop = false; + node.rest = node.rest.transform(compressor.option("rests") ? trimmer : tt); + drop = was_drop; + if (node.rest) elements.length = pos; + } + if (drop) { + if (value && !node.rest) value = value.drop_side_effect_free(compressor); + if (value instanceof AST_Array) { + value = value.elements; + } else if (value instanceof AST_Sequence) { + value = value.expressions; + } else if (value) { + value = [ value ]; + } + if (value && value.length) { + newValues.length = pos; + [].push.apply(newValues, value); + } + } + value = save_value; + drop = save_drop; + if (values && newValues) { + fill_holes(value, newValues); + value = value.clone(); + value.elements = newValues; + } + if (!native) { + elements.length = node.elements.length; + } else if (!node.rest) switch (elements.length) { + case 0: + if (node === root) break; + if (drop) value = value.drop_side_effect_free(compressor); + return null; + case 1: + if (!drop) break; + if (node === root) break; + var sym = elements[0]; + if (sym.has_side_effects(compressor)) break; + if (value.has_side_effects(compressor) && sym.match_symbol(function(node) { + return node instanceof AST_PropAccess; + })) break; + value = make_node(AST_Sub, node, { + expression: value, + property: make_node(AST_Number, node, { value: 0 }), + }); + return sym; + } + fill_holes(node, elements); + node.elements = elements; + return node; + } + if (node instanceof AST_DestructuredObject) { + var save_drop = drop; + var save_value = value; + if (value instanceof AST_SymbolRef) { + drop = false; + value = value.fixed_value(); + } + var prop_keys, prop_map, values; + if (value instanceof AST_Object) { + prop_keys = []; + prop_map = new Dictionary(); + values = value.properties.map(function(prop, index) { + prop = prop.clone(); + if (prop instanceof AST_Spread) { + prop_map = false; + } else { + var key = prop.key; + if (key instanceof AST_Node) key = key.evaluate(compressor, true); + if (key instanceof AST_Node) { + prop_map = false; + } else if (prop_map && !(prop instanceof AST_ObjectSetter)) { + prop_map.set(key, prop); + } + prop_keys[index] = key; + } + return prop; + }); + } + if (node.rest) { + value = false; + node.rest = node.rest.transform(compressor.option("rests") ? trimmer : tt); + } + var can_drop = new Dictionary(); + var drop_keys = drop && new Dictionary(); + var properties = []; + node.properties.map(function(prop) { + var key = prop.key; + if (key instanceof AST_Node) { + prop.key = key = key.transform(tt); + key = key.evaluate(compressor, true); + } + if (key instanceof AST_Node) { + drop_keys = false; + } else { + can_drop.set(key, !can_drop.has(key)); + } + return key; + }).forEach(function(key, index) { + var prop = node.properties[index], trimmed; + if (key instanceof AST_Node) { + drop = false; + value = false; + trimmed = prop.value.transform(trimmer) || retain_lhs(prop.value); + } else { + drop = drop_keys && can_drop.get(key); + var mapped = prop_map && prop_map.get(key); + if (mapped) { + value = mapped.value; + if (value instanceof AST_Accessor) value = false; + } else { + value = false; + } + trimmed = prop.value.transform(trimmer); + if (!trimmed) { + if (node.rest || retain_key(prop)) trimmed = retain_lhs(prop.value); + if (drop_keys && !drop_keys.has(key)) { + if (mapped) { + drop_keys.set(key, mapped); + if (value === null) { + prop_map.set(key, retain_key(mapped) && make_node(AST_ObjectKeyVal, mapped, { + key: mapped.key, + value: make_node(AST_Number, mapped, { value: 0 }), + })); + } + } else { + drop_keys.set(key, true); + } + } + } else if (drop_keys) { + drop_keys.set(key, false); + } + if (value) mapped.value = value; + } + if (trimmed) { + prop.value = trimmed; + properties.push(prop); + } + }); + value = save_value; + drop = save_drop; + if (drop_keys && prop_keys) { + value = value.clone(); + value.properties = List(values, function(prop, index) { + if (prop instanceof AST_Spread) return prop; + var key = prop_keys[index]; + if (key instanceof AST_Node) return prop; + if (drop_keys.has(key)) { + var mapped = drop_keys.get(key); + if (!mapped) return prop; + if (mapped === prop) return prop_map.get(key) || List.skip; + } else if (node.rest) { + return prop; + } + var trimmed = prop.value.drop_side_effect_free(compressor); + if (trimmed) { + prop.value = trimmed; + return prop; + } + return retain_key(prop) ? make_node(AST_ObjectKeyVal, prop, { + key: prop.key, + value: make_node(AST_Number, prop, { value: 0 }), + }) : List.skip; + }); + } + if (value && !node.rest) switch (properties.length) { + case 0: + if (node === root) break; + if (value.may_throw_on_access(compressor, true)) break; + if (drop) value = value.drop_side_effect_free(compressor); + return null; + case 1: + if (!drop) break; + if (node === root) break; + var prop = properties[0]; + if (prop.key instanceof AST_Node) break; + if (prop.value.has_side_effects(compressor)) break; + if (value.has_side_effects(compressor) && prop.value.match_symbol(function(node) { + return node instanceof AST_PropAccess; + })) break; + value = make_node(AST_Sub, node, { + expression: value, + property: make_node_from_constant(prop.key, prop), + }); + return prop.value; + } + node.properties = properties; + return node; + } + if (node instanceof AST_Hole) { + node = null; + } else { + node = process(node); + } + if (!node && drop && value) value = value.drop_side_effect_free(compressor); + return node; + }); + return { + name: node.transform(trimmer), + value: value, + }; + + function retain_key(prop) { + return prop.key instanceof AST_Node && prop.key.has_side_effects(compressor); + } + + function clear_write_only(node) { + if (node instanceof AST_Assign) { + node.write_only = false; + clear_write_only(node.right); + } else if (node instanceof AST_Binary) { + if (!lazy_op[node.operator]) return; + clear_write_only(node.left); + clear_write_only(node.right); + } else if (node instanceof AST_Conditional) { + clear_write_only(node.consequent); + clear_write_only(node.alternative); + } else if (node instanceof AST_Sequence) { + clear_write_only(node.tail_node()); + } else if (node instanceof AST_Unary) { + node.write_only = false; + } + } + + function retain_lhs(node) { + if (node instanceof AST_DefaultValue) return retain_lhs(node.name); + if (node instanceof AST_Destructured) { + if (value === null) { + value = make_node(AST_Number, node, { value: 0 }); + } else if (value) { + if (value.may_throw_on_access(compressor, true)) { + value = make_node(AST_Array, node, { + elements: value instanceof AST_Sequence ? value.expressions : [ value ], + }); + } else { + clear_write_only(value); + } + } + return make_node(AST_DestructuredObject, node, { properties: [] }); + } + node.unused = null; + return node; + } + } + }); + + AST_Scope.DEFMETHOD("hoist_declarations", function(compressor) { + if (compressor.has_directive("use asm")) return; + var hoist_funs = compressor.option("hoist_funs"); + var hoist_vars = compressor.option("hoist_vars"); + var self = this; + if (hoist_vars) { + // let's count var_decl first, we seem to waste a lot of + // space if we hoist `var` when there's only one. + var var_decl = 0; + self.walk(new TreeWalker(function(node) { + if (var_decl > 1) return true; + if (node instanceof AST_ExportDeclaration) return true; + if (node instanceof AST_Scope && node !== self) return true; + if (node instanceof AST_Var) { + var_decl++; + return true; + } + })); + if (var_decl <= 1) hoist_vars = false; + } + if (!hoist_funs && !hoist_vars) return; + var consts = new Dictionary(); + var dirs = []; + var hoisted = []; + var vars = new Dictionary(); + var tt = new TreeTransformer(function(node, descend, in_list) { + if (node === self) return; + if (node instanceof AST_Directive) { + dirs.push(node); + return in_list ? List.skip : make_node(AST_EmptyStatement, node); + } + if (node instanceof AST_LambdaDefinition) { + if (!hoist_funs) return node; + var p = tt.parent(); + if (p instanceof AST_ExportDeclaration) return node; + if (p instanceof AST_ExportDefault) return node; + if (p !== self && compressor.has_directive("use strict")) return node; + hoisted.push(node); + return in_list ? List.skip : make_node(AST_EmptyStatement, node); + } + if (node instanceof AST_Var) { + if (!hoist_vars) return node; + var p = tt.parent(); + if (p instanceof AST_ExportDeclaration) return node; + if (!all(node.definitions, function(defn) { + var sym = defn.name; + return sym instanceof AST_SymbolVar + && !consts.has(sym.name) + && self.find_variable(sym.name) === sym.definition(); + })) return node; + node.definitions.forEach(function(defn) { + vars.set(defn.name.name, defn); + }); + var seq = node.to_assignments(); + if (p instanceof AST_ForEnumeration && p.init === node) { + if (seq) return seq; + var sym = node.definitions[0].name; + return make_node(AST_SymbolRef, sym); + } + if (p instanceof AST_For && p.init === node) return seq; + if (!seq) return in_list ? List.skip : make_node(AST_EmptyStatement, node); + return make_node(AST_SimpleStatement, node, { body: seq }); + } + if (node instanceof AST_Scope) return node; + if (node instanceof AST_SymbolConst) { + consts.set(node.name, true); + return node; + } + }); + self.transform(tt); + if (vars.size() > 0) { + // collect only vars which don't show up in self's arguments list + var defns = []; + if (self instanceof AST_Lambda) self.each_argname(function(argname) { + if (all(argname.definition().references, function(ref) { + return !ref.in_arg; + })) vars.del(argname.name); + }); + vars.each(function(defn, name) { + defn = defn.clone(); + defn.name = defn.name.clone(); + defn.value = null; + defns.push(defn); + vars.set(name, defn); + defn.name.definition().orig.unshift(defn.name); + }); + if (defns.length > 0) hoisted.push(make_node(AST_Var, self, { definitions: defns })); + } + self.body = dirs.concat(hoisted, self.body); + }); + + function scan_local_returns(fn, transform) { + fn.walk(new TreeWalker(function(node) { + if (node instanceof AST_Return) { + transform(node); + return true; + } + if (node instanceof AST_Scope && node !== fn) return true; + })); + } + + function map_self_returns(fn) { + var map = Object.create(null); + scan_local_returns(fn, function(node) { + var value = node.value; + if (value) value = value.tail_node(); + if (value instanceof AST_SymbolRef) { + var id = value.definition().id; + map[id] = (map[id] || 0) + 1; + } + }); + return map; + } + + function can_trim_returns(def, self_returns, compressor) { + if (compressor.exposed(def)) return false; + switch (def.references.length - def.replaced - (self_returns[def.id] || 0)) { + case def.drop_return: + return "d"; + case def.bool_return: + return true; + } + } + + function process_boolean_returns(fn, compressor) { + scan_local_returns(fn, function(node) { + node.in_bool = true; + var value = node.value; + if (value) { + var ev = fuzzy_eval(compressor, value); + if (!ev) { + value = value.drop_side_effect_free(compressor); + node.value = value ? make_sequence(node.value, [ + value, + make_node(AST_Number, node.value, { value: 0 }), + ]) : null; + } else if (!(ev instanceof AST_Node)) { + value = value.drop_side_effect_free(compressor); + node.value = value ? make_sequence(node.value, [ + value, + make_node(AST_Number, node.value, { value: 1 }), + ]) : make_node(AST_Number, node.value, { value: 1 }); + } + } + }); + } + + AST_Scope.DEFMETHOD("process_returns", noop); + AST_Defun.DEFMETHOD("process_returns", function(compressor) { + if (!compressor.option("booleans")) return; + if (compressor.parent() instanceof AST_ExportDefault) return; + switch (can_trim_returns(this.name.definition(), map_self_returns(this), compressor)) { + case "d": + drop_returns(compressor, this, true); + break; + case true: + process_boolean_returns(this, compressor); + break; + } + }); + AST_Function.DEFMETHOD("process_returns", function(compressor) { + if (!compressor.option("booleans")) return; + var drop = true; + var self_returns = map_self_returns(this); + if (this.name && !can_trim(this.name.definition())) return; + var parent = compressor.parent(); + if (parent instanceof AST_Assign) { + if (parent.operator != "=") return; + var sym = parent.left; + if (!(sym instanceof AST_SymbolRef)) return; + if (!can_trim(sym.definition())) return; + } else if (parent instanceof AST_Call && parent.expression !== this) { + var exp = parent.expression; + if (exp instanceof AST_SymbolRef) exp = exp.fixed_value(); + if (!(exp instanceof AST_Lambda)) return; + if (exp.uses_arguments || exp.pinned()) return; + var args = parent.args, sym; + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + if (arg === this) { + sym = exp.argnames[i]; + if (!sym && exp.rest) return; + break; + } + if (arg instanceof AST_Spread) return; + } + if (sym instanceof AST_DefaultValue) sym = sym.name; + if (sym instanceof AST_SymbolFunarg && !can_trim(sym.definition())) return; + } else if (parent.TYPE == "Call") { + compressor.pop(); + var in_bool = compressor.in_boolean_context(); + compressor.push(this); + switch (in_bool) { + case true: + drop = false; + case "d": + break; + default: + return; + } + } else return; + if (drop) { + drop_returns(compressor, this, true); + } else { + process_boolean_returns(this, compressor); + } + + function can_trim(def) { + switch (can_trim_returns(def, self_returns, compressor)) { + case true: + drop = false; + case "d": + return true; + } + } + }); + + AST_BlockScope.DEFMETHOD("var_names", function() { + var var_names = this._var_names; + if (!var_names) { + this._var_names = var_names = new Dictionary(); + this.enclosed.forEach(function(def) { + var_names.set(def.name, true); + }); + this.variables.each(function(def, name) { + var_names.set(name, true); + }); + } + return var_names; + }); + + AST_Scope.DEFMETHOD("make_var", function(type, orig, prefix) { + var scopes = [ this ]; + if (orig instanceof AST_SymbolDeclaration) orig.definition().references.forEach(function(ref) { + var s = ref.scope; + do { + if (!push_uniq(scopes, s)) return; + s = s.parent_scope; + } while (s && s !== this); + }); + prefix = prefix.replace(/^[^a-z_$]|[^a-z0-9_$]/gi, "_"); + var name = prefix; + for (var i = 0; !all(scopes, function(scope) { + return !scope.var_names().has(name); + }); i++) name = prefix + "$" + i; + var sym = make_node(type, orig, { + name: name, + scope: this, + }); + var def = this.def_variable(sym); + scopes.forEach(function(scope) { + scope.enclosed.push(def); + scope.var_names().set(name, true); + }); + return sym; + }); + + AST_Scope.DEFMETHOD("hoist_properties", function(compressor) { + if (!compressor.option("hoist_props") || compressor.has_directive("use asm")) return; + var self = this; + if (is_arrow(self) && self.value) return; + var top_retain = self instanceof AST_Toplevel && compressor.top_retain || return_false; + var defs_by_id = Object.create(null); + var tt = new TreeTransformer(function(node, descend) { + if (node instanceof AST_Assign) { + if (node.operator != "=") return; + if (!node.write_only) return; + if (!can_hoist(node.left, node.right, 1)) return; + descend(node, tt); + var defs = new Dictionary(); + var assignments = []; + var decls = []; + node.right.properties.forEach(function(prop) { + var decl = make_sym(AST_SymbolVar, node.left, prop.key); + decls.push(make_node(AST_VarDef, node, { + name: decl, + value: null, + })); + var sym = make_node(AST_SymbolRef, node, { + name: decl.name, + scope: self, + thedef: decl.definition(), + }); + sym.reference(); + assignments.push(make_node(AST_Assign, node, { + operator: "=", + left: sym, + right: prop.value, + })); + }); + defs.value = node.right; + defs_by_id[node.left.definition().id] = defs; + self.body.splice(self.body.indexOf(tt.stack[1]) + 1, 0, make_node(AST_Var, node, { + definitions: decls, + })); + return make_sequence(node, assignments); + } + if (node instanceof AST_Scope) { + if (node === self) return; + var parent = tt.parent(); + if (parent.TYPE == "Call" && parent.expression === node) return; + return node; + } + if (node instanceof AST_VarDef) { + if (!can_hoist(node.name, node.value, 0)) return; + descend(node, tt); + var defs = new Dictionary(); + var var_defs = []; + var decl = node.clone(); + decl.value = node.name instanceof AST_SymbolConst ? make_node(AST_Number, node, { value: 0 }) : null; + var_defs.push(decl); + node.value.properties.forEach(function(prop) { + var_defs.push(make_node(AST_VarDef, node, { + name: make_sym(node.name.CTOR, node.name, prop.key), + value: prop.value, + })); + }); + defs.value = node.value; + defs_by_id[node.name.definition().id] = defs; + return List.splice(var_defs); + } + + function make_sym(type, sym, key) { + var new_var = self.make_var(type, sym, sym.name + "_" + key); + defs.set(key, new_var.definition()); + return new_var; + } + }); + self.transform(tt); + self.transform(new TreeTransformer(function(node, descend) { + if (node instanceof AST_PropAccess) { + if (!(node.expression instanceof AST_SymbolRef)) return; + var defs = defs_by_id[node.expression.definition().id]; + if (!defs) return; + if (node.expression.fixed_value() !== defs.value) return; + var def = defs.get(node.get_property()); + var sym = make_node(AST_SymbolRef, node, { + name: def.name, + scope: node.expression.scope, + thedef: def, + }); + sym.reference(); + return sym; + } + if (node instanceof AST_SymbolRef) { + var defs = defs_by_id[node.definition().id]; + if (!defs) return; + if (node.fixed_value() !== defs.value) return; + return make_node(AST_Object, node, { properties: [] }); + } + })); + + function can_hoist(sym, right, count) { + if (!(sym instanceof AST_Symbol)) return; + var def = sym.definition(); + if (def.assignments != count) return; + if (def.references.length - def.replaced == count) return; + if (def.single_use) return; + if (self.find_variable(sym.name) !== def) return; + if (top_retain(def)) return; + if (sym.fixed_value() !== right) return; + var fixed = sym.fixed || def.fixed; + if (fixed.direct_access) return; + if (fixed.escaped && fixed.escaped.depth == 1) return; + return right instanceof AST_Object + && right.properties.length > 0 + && can_drop_symbol(sym, compressor) + && all(right.properties, function(prop) { + return can_hoist_property(prop) && prop.key !== "__proto__"; + }); + } + }); + + function fn_name_unused(fn, compressor) { + if (!fn.name || !compressor.option("ie")) return true; + var def = fn.name.definition(); + if (compressor.exposed(def)) return false; + return all(def.references, function(sym) { + return !(sym instanceof AST_SymbolRef); + }); + } + + function drop_returns(compressor, exp, ignore_name) { + if (!(exp instanceof AST_Lambda)) return; + var arrow = is_arrow(exp); + var async = is_async(exp); + var changed = false; + var drop_body = false; + if (arrow && compressor.option("arrows")) { + if (!exp.value) { + drop_body = true; + } else if (!async || needs_enqueuing(compressor, exp.value)) { + var dropped = exp.value.drop_side_effect_free(compressor); + if (dropped !== exp.value) { + changed = true; + exp.value = dropped; + } + } + } else if (!is_generator(exp)) { + if (!ignore_name && exp.name) { + var def = exp.name.definition(); + drop_body = def.references.length == def.replaced; + } else { + drop_body = true; + } + } + if (drop_body) { + exp.process_expression(false, function(node) { + var value = node.value; + if (value) { + if (async && !needs_enqueuing(compressor, value)) return node; + value = value.drop_side_effect_free(compressor, true); + } + changed = true; + if (!value) return make_node(AST_EmptyStatement, node); + return make_node(AST_SimpleStatement, node, { body: value }); + }); + scan_local_returns(exp, function(node) { + var value = node.value; + if (value) { + if (async && !needs_enqueuing(compressor, value)) return; + var dropped = value.drop_side_effect_free(compressor); + if (dropped !== value) { + changed = true; + if (dropped && async && !needs_enqueuing(compressor, dropped)) { + dropped = dropped.negate(compressor); + } + node.value = dropped; + } + } + }); + } + if (async && compressor.option("awaits")) { + if (drop_body) exp.process_expression("awaits", function(node) { + var body = node.body; + if (body instanceof AST_Await) { + if (needs_enqueuing(compressor, body.expression)) { + changed = true; + body = body.expression.drop_side_effect_free(compressor, true); + if (!body) return make_node(AST_EmptyStatement, node); + node.body = body; + } + } else if (body instanceof AST_Sequence) { + var exprs = body.expressions; + for (var i = exprs.length; --i >= 0;) { + var tail = exprs[i]; + if (!(tail instanceof AST_Await)) break; + var value = tail.expression; + if (!needs_enqueuing(compressor, value)) break; + changed = true; + if (exprs[i] = value.drop_side_effect_free(compressor)) break; + } + switch (i) { + case -1: + return make_node(AST_EmptyStatement, node); + case 0: + node.body = exprs[0]; + break; + default: + exprs.length = i + 1; + break; + } + } + return node; + }); + var abort = !drop_body && exp.name || arrow && exp.value && !needs_enqueuing(compressor, exp.value); + var tw = new TreeWalker(function(node) { + if (abort) return true; + if (tw.parent() === exp && node.may_throw(compressor)) return abort = true; + if (node instanceof AST_Await) return abort = true; + if (node instanceof AST_ForAwaitOf) return abort = true; + if (node instanceof AST_Return) { + if (node.value && !needs_enqueuing(compressor, node.value)) return abort = true; + return; + } + if (node instanceof AST_Scope && node !== exp) return true; + }); + exp.walk(tw); + if (!abort) { + var ctor; + switch (exp.CTOR) { + case AST_AsyncArrow: + ctor = AST_Arrow; + break; + case AST_AsyncFunction: + ctor = AST_Function; + break; + case AST_AsyncGeneratorFunction: + ctor = AST_GeneratorFunction; + break; + } + return make_node(ctor, exp); + } + } + return changed && exp.clone(); + } + + // drop_side_effect_free() + // remove side-effect-free parts which only affects return value + (function(def) { + // Drop side-effect-free elements from an array of expressions. + // Returns an array of expressions with side-effects or null + // if all elements were dropped. Note: original array may be + // returned if nothing changed. + function trim(nodes, compressor, first_in_statement, spread) { + var len = nodes.length; + var ret = [], changed = false; + for (var i = 0; i < len; i++) { + var node = nodes[i]; + var trimmed; + if (spread && node instanceof AST_Spread) { + trimmed = spread(node, compressor, first_in_statement); + } else { + trimmed = node.drop_side_effect_free(compressor, first_in_statement); + } + if (trimmed !== node) changed = true; + if (trimmed) { + ret.push(trimmed); + first_in_statement = false; + } + } + return ret.length ? changed ? ret : nodes : null; + } + function array_spread(node, compressor, first_in_statement) { + var exp = node.expression; + if (!exp.is_string(compressor)) return node; + return exp.drop_side_effect_free(compressor, first_in_statement); + } + function convert_spread(node) { + return node instanceof AST_Spread ? make_node(AST_Array, node, { elements: [ node ] }) : node; + } + def(AST_Node, return_this); + def(AST_Accessor, return_null); + def(AST_Array, function(compressor, first_in_statement) { + var values = trim(this.elements, compressor, first_in_statement, array_spread); + if (!values) return null; + if (values === this.elements && all(values, function(node) { + return node instanceof AST_Spread; + })) return this; + return make_sequence(this, values.map(convert_spread)); + }); + def(AST_Assign, function(compressor) { + var left = this.left; + if (left instanceof AST_PropAccess) { + var expr = left.expression; + if (expr.may_throw_on_access(compressor, true)) return this; + if (compressor.has_directive("use strict") && expr.is_constant()) return this; + } + if (left.has_side_effects(compressor)) return this; + if (lazy_op[this.operator.slice(0, -1)]) return this; + this.write_only = true; + if (!root_expr(left).is_constant_expression(compressor.find_parent(AST_Scope))) return this; + return this.right.drop_side_effect_free(compressor); + }); + def(AST_Await, function(compressor) { + if (!compressor.option("awaits")) return this; + var exp = this.expression; + if (!needs_enqueuing(compressor, exp)) return this; + if (exp instanceof AST_UnaryPrefix && exp.operator == "!") exp = exp.expression; + var dropped = exp.drop_side_effect_free(compressor); + if (dropped === exp) return this; + if (!dropped) { + dropped = make_node(AST_Number, exp, { value: 0 }); + } else if (!needs_enqueuing(compressor, dropped)) { + dropped = dropped.negate(compressor); + } + var node = this.clone(); + node.expression = dropped; + return node; + }); + def(AST_Binary, function(compressor, first_in_statement) { + var left = this.left; + var right = this.right; + var op = this.operator; + if (!can_drop_op(op, right, compressor)) { + var lhs = left.drop_side_effect_free(compressor, first_in_statement); + if (lhs === left) return this; + var node = this.clone(); + node.left = lhs || make_node(AST_Number, left, { value: 0 }); + return node; + } + var rhs = right.drop_side_effect_free(compressor, first_in_statement); + if (!rhs) return left.drop_side_effect_free(compressor, first_in_statement); + if (lazy_op[op] && rhs.has_side_effects(compressor)) { + var node = this; + if (rhs !== right) { + node = node.clone(); + node.right = rhs.drop_side_effect_free(compressor); + } + if (op == "??") return node; + var negated = node.clone(); + negated.operator = op == "&&" ? "||" : "&&"; + negated.left = left.negate(compressor, first_in_statement); + var negated_rhs = negated.right.tail_node(); + if (negated_rhs instanceof AST_Binary && negated.operator == negated_rhs.operator) swap_chain(negated); + var best = first_in_statement ? best_of_statement : best_of_expression; + return op == "&&" ? best(node, negated) : best(negated, node); + } + var lhs = left.drop_side_effect_free(compressor, first_in_statement); + if (!lhs) return rhs; + rhs = rhs.drop_side_effect_free(compressor); + if (!rhs) return lhs; + return make_sequence(this, [ lhs, rhs ]); + }); + function assign_this_only(fn, compressor) { + fn.new = true; + var result = all(fn.body, function(stat) { + return !stat.has_side_effects(compressor); + }) && all(fn.argnames, function(argname) { + return !argname.match_symbol(return_false); + }) && !(fn.rest && fn.rest.match_symbol(return_false)); + fn.new = false; + return result; + } + def(AST_Call, function(compressor, first_in_statement) { + var self = this; + if (self.is_expr_pure(compressor)) { + if (self.pure) AST_Node.warn("Dropping __PURE__ call [{start}]", self); + var args = trim(self.args, compressor, first_in_statement, array_spread); + return args && make_sequence(self, args.map(convert_spread)); + } + var exp = self.expression; + if (self.is_call_pure(compressor)) { + var exprs = self.args.slice(); + exprs.unshift(exp.expression); + exprs = trim(exprs, compressor, first_in_statement, array_spread); + return exprs && make_sequence(self, exprs.map(convert_spread)); + } + if (compressor.option("yields") && is_generator(exp)) { + var call = self.clone(); + call.expression = make_node(AST_Function, exp); + call.expression.body = []; + var opt = call.transform(compressor); + if (opt !== call) return opt.drop_side_effect_free(compressor, first_in_statement); + } + var dropped = drop_returns(compressor, exp); + if (dropped) { + // always shallow clone to ensure stripping of negated IIFEs + self = self.clone(); + self.expression = dropped; + // avoid extraneous traversal + if (exp._squeezed) self.expression._squeezed = true; + } + if (self instanceof AST_New) { + var fn = exp; + if (fn instanceof AST_SymbolRef) fn = fn.fixed_value(); + if (fn instanceof AST_Lambda) { + if (assign_this_only(fn, compressor)) { + var exprs = self.args.slice(); + exprs.unshift(exp); + exprs = trim(exprs, compressor, first_in_statement, array_spread); + return exprs && make_sequence(self, exprs.map(convert_spread)); + } + if (!fn.contains_this()) { + self = make_node(AST_Call, self); + self.expression = self.expression.clone(); + self.args = self.args.slice(); + } + } + } + self.call_only = true; + return self; + }); + def(AST_ClassExpression, function(compressor, first_in_statement) { + var self = this; + var exprs = [], values = [], init = 0; + var props = self.properties; + for (var i = 0; i < props.length; i++) { + var prop = props[i]; + if (prop.key instanceof AST_Node) exprs.push(prop.key); + if (!is_static_field_or_init(prop)) continue; + var value = prop.value; + if (!value.has_side_effects(compressor)) continue; + if (value.contains_this()) return self; + if (prop instanceof AST_ClassInit) { + init++; + values.push(prop); + } else { + values.push(value); + } + } + var base = self.extends; + if (base) { + if (base instanceof AST_SymbolRef) base = base.fixed_value(); + base = !safe_for_extends(base); + if (!base) exprs.unshift(self.extends); + } + exprs = trim(exprs, compressor, first_in_statement); + if (exprs) first_in_statement = false; + values = trim(values, compressor, first_in_statement); + if (!exprs) { + if (!base && !values && !self.name) return null; + exprs = []; + } + if (base || self.name || !compressor.has_directive("use strict")) { + var node = to_class_expr(self); + if (!base) node.extends = null; + node.properties = []; + if (values) { + if (values.length == init) { + if (exprs.length) values.unshift(make_node(AST_ClassField, self, { + key: make_sequence(self, exprs), + value: null, + })); + node.properties = values; + } else node.properties.push(make_node(AST_ClassField, self, { + static: true, + key: exprs.length ? make_sequence(self, exprs) : "c", + value: make_value(), + })); + } else if (exprs.length) node.properties.push(make_node(AST_ClassMethod, self, { + key: make_sequence(self, exprs), + value: make_node(AST_Function, self, { + argnames: [], + body: [], + }).init_vars(node), + })); + return node; + } + if (values) exprs.push(make_node(AST_Call, self, { + expression: make_node(AST_Arrow, self, { + argnames: [], + body: [], + value: make_value(), + }).init_vars(self.parent_scope), + args: [], + })); + return make_sequence(self, exprs); + + function make_value() { + return make_sequence(self, values.map(function(node) { + if (!(node instanceof AST_ClassInit)) return node; + var fn = make_node(AST_Arrow, node.value); + fn.argnames = []; + return make_node(AST_Call, node, { + expression: fn, + args: [], + }); + })); + } + }); + def(AST_Conditional, function(compressor) { + var consequent = this.consequent.drop_side_effect_free(compressor); + var alternative = this.alternative.drop_side_effect_free(compressor); + if (consequent === this.consequent && alternative === this.alternative) return this; + var exprs; + if (compressor.option("ie")) { + exprs = []; + if (consequent instanceof AST_Function) { + exprs.push(consequent); + consequent = null; + } + if (alternative instanceof AST_Function) { + exprs.push(alternative); + alternative = null; + } + } + var node; + if (!consequent) { + node = alternative ? make_node(AST_Binary, this, { + operator: "||", + left: this.condition, + right: alternative, + }) : this.condition.drop_side_effect_free(compressor); + } else if (!alternative) { + node = make_node(AST_Binary, this, { + operator: "&&", + left: this.condition, + right: consequent, + }); + } else { + node = this.clone(); + node.consequent = consequent; + node.alternative = alternative; + } + if (!exprs) return node; + if (node) exprs.push(node); + return exprs.length == 0 ? null : make_sequence(this, exprs); + }); + def(AST_Constant, return_null); + def(AST_Dot, function(compressor, first_in_statement) { + var expr = this.expression; + if (expr.may_throw_on_access(compressor)) return this; + return expr.drop_side_effect_free(compressor, first_in_statement); + }); + def(AST_Function, function(compressor) { + return fn_name_unused(this, compressor) ? null : this; + }); + def(AST_LambdaExpression, return_null); + def(AST_Object, function(compressor, first_in_statement) { + var exprs = []; + this.properties.forEach(function(prop) { + if (prop instanceof AST_Spread) { + exprs.push(prop); + } else { + if (prop.key instanceof AST_Node) exprs.push(prop.key); + exprs.push(prop.value); + } + }); + var values = trim(exprs, compressor, first_in_statement, function(node, compressor, first_in_statement) { + var exp = node.expression; + return exp.safe_to_spread() ? exp.drop_side_effect_free(compressor, first_in_statement) : node; + }); + if (!values) return null; + if (values === exprs && !all(values, function(node) { + return !(node instanceof AST_Spread); + })) return this; + return make_sequence(this, values.map(function(node) { + return node instanceof AST_Spread ? make_node(AST_Object, node, { properties: [ node ] }) : node; + })); + }); + def(AST_ObjectIdentity, return_null); + def(AST_Sequence, function(compressor, first_in_statement) { + var expressions = trim(this.expressions, compressor, first_in_statement); + if (!expressions) return null; + var end = expressions.length - 1; + var last = expressions[end]; + if (compressor.option("awaits") && end > 0 && last instanceof AST_Await && last.expression.is_constant()) { + expressions = expressions.slice(0, -1); + end--; + var expr = expressions[end]; + last.expression = needs_enqueuing(compressor, expr) ? expr : expr.negate(compressor); + expressions[end] = last; + } + var assign, cond, lhs; + if (compressor.option("conditionals") + && end > 0 + && (assign = expressions[end - 1]) instanceof AST_Assign + && assign.operator == "=" + && (lhs = assign.left) instanceof AST_SymbolRef + && (cond = to_conditional_assignment(compressor, lhs.definition(), assign.right, last))) { + assign = assign.clone(); + assign.right = cond; + expressions = expressions.slice(0, -2); + expressions.push(assign.drop_side_effect_free(compressor, first_in_statement)); + } + return expressions === this.expressions ? this : make_sequence(this, expressions); + }); + def(AST_Sub, function(compressor, first_in_statement) { + var expr = this.expression; + if (expr.may_throw_on_access(compressor)) return this; + var prop = this.property; + expr = expr.drop_side_effect_free(compressor, first_in_statement); + if (!expr) return prop.drop_side_effect_free(compressor, first_in_statement); + prop = prop.drop_side_effect_free(compressor); + if (!prop) return expr; + return make_sequence(this, [ expr, prop ]); + }); + def(AST_SymbolRef, function(compressor) { + return this.is_declared(compressor) && can_drop_symbol(this, compressor) ? null : this; + }); + def(AST_Template, function(compressor, first_in_statement) { + var self = this; + if (self.is_expr_pure(compressor)) { + var expressions = self.expressions; + if (expressions.length == 0) return null; + return make_sequence(self, expressions).drop_side_effect_free(compressor, first_in_statement); + } + var tag = self.tag; + var dropped = drop_returns(compressor, tag); + if (dropped) { + // always shallow clone to signal internal changes + self = self.clone(); + self.tag = dropped; + // avoid extraneous traversal + if (tag._squeezed) self.tag._squeezed = true; + } + return self; + }); + def(AST_Unary, function(compressor, first_in_statement) { + var exp = this.expression; + if (unary_side_effects[this.operator]) { + this.write_only = !exp.has_side_effects(compressor); + return this; + } + if (this.operator == "typeof" && exp instanceof AST_SymbolRef && can_drop_symbol(exp, compressor)) { + return null; + } + var node = exp.drop_side_effect_free(compressor, first_in_statement); + if (first_in_statement && node && is_iife_call(node)) { + if (node === exp && this.operator == "!") return this; + return node.negate(compressor, first_in_statement); + } + return node; + }); + })(function(node, func) { + node.DEFMETHOD("drop_side_effect_free", func); + }); + + OPT(AST_SimpleStatement, function(self, compressor) { + if (compressor.option("side_effects")) { + var body = self.body; + var node = body.drop_side_effect_free(compressor, true); + if (!node) { + AST_Node.warn("Dropping side-effect-free statement [{start}]", self); + return make_node(AST_EmptyStatement, self); + } + if (node !== body) { + return make_node(AST_SimpleStatement, self, { body: node }); + } + } + return self; + }); + + OPT(AST_While, function(self, compressor) { + return compressor.option("loops") ? make_node(AST_For, self).optimize(compressor) : self; + }); + + function has_loop_control(loop, parent, type) { + if (!type) type = AST_LoopControl; + var found = false; + var tw = new TreeWalker(function(node) { + if (found || node instanceof AST_Scope) return true; + if (node instanceof type && tw.loopcontrol_target(node) === loop) { + return found = true; + } + }); + if (parent instanceof AST_LabeledStatement) tw.push(parent); + tw.push(loop); + loop.body.walk(tw); + return found; + } + + OPT(AST_Do, function(self, compressor) { + if (!compressor.option("loops")) return self; + var cond = fuzzy_eval(compressor, self.condition); + if (!(cond instanceof AST_Node)) { + if (cond && !has_loop_control(self, compressor.parent(), AST_Continue)) return make_node(AST_For, self, { + body: make_node(AST_BlockStatement, self.body, { + body: [ + self.body, + make_node(AST_SimpleStatement, self.condition, { body: self.condition }), + ], + }), + }).optimize(compressor); + if (!has_loop_control(self, compressor.parent())) return make_node(AST_BlockStatement, self.body, { + body: [ + self.body, + make_node(AST_SimpleStatement, self.condition, { body: self.condition }), + ], + }).optimize(compressor); + } + if (self.body instanceof AST_BlockStatement && !has_loop_control(self, compressor.parent(), AST_Continue)) { + var body = self.body.body; + for (var i = body.length; --i >= 0;) { + var stat = body[i]; + if (stat instanceof AST_If + && !stat.alternative + && stat.body instanceof AST_Break + && compressor.loopcontrol_target(stat.body) === self) { + if (has_block_scope_refs(stat.condition)) break; + self.condition = make_node(AST_Binary, self, { + operator: "&&", + left: stat.condition.negate(compressor), + right: self.condition, + }); + body.splice(i, 1); + } else if (stat instanceof AST_SimpleStatement) { + if (has_block_scope_refs(stat.body)) break; + self.condition = make_sequence(self, [ + stat.body, + self.condition, + ]); + body.splice(i, 1); + } else if (!is_declaration(stat, true)) { + break; + } + } + self.body = trim_block(self.body, compressor.parent()); + } + if (self.body instanceof AST_EmptyStatement) return make_node(AST_For, self).optimize(compressor); + if (self.body instanceof AST_SimpleStatement) return make_node(AST_For, self, { + condition: make_sequence(self.condition, [ + self.body.body, + self.condition, + ]), + body: make_node(AST_EmptyStatement, self), + }).optimize(compressor); + return self; + + function has_block_scope_refs(node) { + var found = false; + node.walk(new TreeWalker(function(node) { + if (found) return true; + if (node instanceof AST_SymbolRef) { + if (!member(node.definition(), self.enclosed)) found = true; + return true; + } + })); + return found; + } + }); + + function if_break_in_loop(self, compressor) { + var first = first_statement(self.body); + if (compressor.option("dead_code") + && (first instanceof AST_Break + || first instanceof AST_Continue && external_target(first) + || first instanceof AST_Exit)) { + var body = []; + if (is_statement(self.init)) { + body.push(self.init); + } else if (self.init) { + body.push(make_node(AST_SimpleStatement, self.init, { body: self.init })); + } + var retain = external_target(first) || first instanceof AST_Exit; + if (self.condition && retain) { + body.push(make_node(AST_If, self, { + condition: self.condition, + body: first, + alternative: null, + })); + } else if (self.condition) { + body.push(make_node(AST_SimpleStatement, self.condition, { body: self.condition })); + } else if (retain) { + body.push(first); + } + extract_declarations_from_unreachable_code(compressor, self.body, body); + return make_node(AST_BlockStatement, self, { body: body }); + } + if (first instanceof AST_If) { + var ab = first_statement(first.body); + if (ab instanceof AST_Break && !external_target(ab)) { + if (self.condition) { + self.condition = make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "&&", + right: first.condition.negate(compressor), + }); + } else { + self.condition = first.condition.negate(compressor); + } + var body = as_statement_array(first.alternative); + extract_declarations_from_unreachable_code(compressor, first.body, body); + return drop_it(body); + } + ab = first_statement(first.alternative); + if (ab instanceof AST_Break && !external_target(ab)) { + if (self.condition) { + self.condition = make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "&&", + right: first.condition, + }); + } else { + self.condition = first.condition; + } + var body = as_statement_array(first.body); + extract_declarations_from_unreachable_code(compressor, first.alternative, body); + return drop_it(body); + } + } + return self; + + function first_statement(body) { + return body instanceof AST_BlockStatement ? body.body[0] : body; + } + + function external_target(node) { + return compressor.loopcontrol_target(node) !== compressor.self(); + } + + function drop_it(rest) { + if (self.body instanceof AST_BlockStatement) { + self.body = self.body.clone(); + self.body.body = rest.concat(self.body.body.slice(1)); + self.body = self.body.transform(compressor); + } else { + self.body = make_node(AST_BlockStatement, self.body, { body: rest }).transform(compressor); + } + return if_break_in_loop(self, compressor); + } + } + + OPT(AST_For, function(self, compressor) { + if (!compressor.option("loops")) return self; + if (compressor.option("side_effects")) { + if (self.init) self.init = self.init.drop_side_effect_free(compressor); + if (self.step) self.step = self.step.drop_side_effect_free(compressor); + } + if (self.condition) { + var cond = fuzzy_eval(compressor, self.condition); + if (!cond) { + if (compressor.option("dead_code")) { + var body = []; + if (is_statement(self.init)) { + body.push(self.init); + } else if (self.init) { + body.push(make_node(AST_SimpleStatement, self.init, { body: self.init })); + } + body.push(make_node(AST_SimpleStatement, self.condition, { body: self.condition })); + extract_declarations_from_unreachable_code(compressor, self.body, body); + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } + } else if (!(cond instanceof AST_Node)) { + self.body = make_node(AST_BlockStatement, self.body, { + body: [ + make_node(AST_SimpleStatement, self.condition, { body: self.condition }), + self.body, + ], + }); + self.condition = null; + } + } + return if_break_in_loop(self, compressor); + }); + + OPT(AST_ForEnumeration, function(self, compressor) { + if (compressor.option("varify") && is_lexical_definition(self.init)) { + var name = self.init.definitions[0].name; + if ((name instanceof AST_Destructured || name instanceof AST_SymbolLet) + && !name.match_symbol(function(node) { + if (node instanceof AST_SymbolDeclaration) { + var def = node.definition(); + return !same_scope(def) || may_overlap(compressor, def); + } + }, true)) { + self.init = to_var(self.init, self.resolve()); + } + } + return self; + }); + + function mark_locally_defined(condition, consequent, alternative) { + if (condition instanceof AST_Sequence) condition = condition.tail_node(); + if (!(condition instanceof AST_Binary)) return; + if (!(condition.left instanceof AST_String)) { + switch (condition.operator) { + case "&&": + mark_locally_defined(condition.left, consequent); + mark_locally_defined(condition.right, consequent); + break; + case "||": + mark_locally_defined(negate(condition.left), alternative); + mark_locally_defined(negate(condition.right), alternative); + break; + } + return; + } + if (!(condition.right instanceof AST_UnaryPrefix)) return; + if (condition.right.operator != "typeof") return; + var sym = condition.right.expression; + if (!is_undeclared_ref(sym)) return; + var body; + var undef = condition.left.value == "undefined"; + switch (condition.operator) { + case "==": + body = undef ? alternative : consequent; + break; + case "!=": + body = undef ? consequent : alternative; + break; + default: + return; + } + if (!body) return; + var abort = false; + var def = sym.definition(); + var fn; + var refs = []; + var scanned = []; + var tw = new TreeWalker(function(node, descend) { + if (abort) return true; + if (node instanceof AST_Assign) { + var ref = node.left; + if (!(ref instanceof AST_SymbolRef && ref.definition() === def)) return; + node.right.walk(tw); + switch (node.operator) { + case "=": + case "&&=": + abort = true; + } + return true; + } + if (node instanceof AST_Call) { + descend(); + fn = node.expression.tail_node(); + var save; + if (fn instanceof AST_SymbolRef) { + fn = fn.fixed_value(); + save = refs.length; + } + if (!(fn instanceof AST_Lambda)) { + abort = true; + } else if (push_uniq(scanned, fn)) { + fn.walk(tw); + } + if (save >= 0) refs.length = save; + return true; + } + if (node instanceof AST_DWLoop) { + var save = refs.length; + descend(); + if (abort) refs.length = save; + return true; + } + if (node instanceof AST_For) { + if (node.init) node.init.walk(tw); + var save = refs.length; + if (node.condition) node.condition.walk(tw); + node.body.walk(tw); + if (node.step) node.step.walk(tw); + if (abort) refs.length = save; + return true; + } + if (node instanceof AST_ForEnumeration) { + node.object.walk(tw); + var save = refs.length; + node.init.walk(tw); + node.body.walk(tw); + if (abort) refs.length = save; + return true; + } + if (node instanceof AST_Scope) { + if (node === fn) return; + return true; + } + if (node instanceof AST_SymbolRef) { + if (node.definition() === def) refs.push(node); + return true; + } + }); + body.walk(tw); + refs.forEach(function(ref) { + ref.defined = true; + }); + + function negate(node) { + if (!(node instanceof AST_Binary)) return; + switch (node.operator) { + case "==": + node = node.clone(); + node.operator = "!="; + return node; + case "!=": + node = node.clone(); + node.operator = "=="; + return node; + } + } + } + + function fuzzy_eval(compressor, node, nullish) { + if (node.truthy) return true; + if (is_undefined(node)) return undefined; + if (node.falsy && !nullish) return false; + if (node.is_truthy()) return true; + return node.evaluate(compressor, true); + } + + function mark_duplicate_condition(compressor, node) { + var child; + var level = 0; + var negated = false; + var parent = compressor.self(); + if (!is_statement(parent)) while (true) { + child = parent; + parent = compressor.parent(level++); + if (parent instanceof AST_Binary) { + switch (child) { + case parent.left: + if (lazy_op[parent.operator]) continue; + break; + case parent.right: + if (match(parent.left)) switch (parent.operator) { + case "&&": + node[negated ? "falsy" : "truthy"] = true; + break; + case "||": + case "??": + node[negated ? "truthy" : "falsy"] = true; + break; + } + break; + } + } else if (parent instanceof AST_Conditional) { + var cond = parent.condition; + if (cond === child) continue; + if (match(cond)) switch (child) { + case parent.consequent: + node[negated ? "falsy" : "truthy"] = true; + break; + case parent.alternative: + node[negated ? "truthy" : "falsy"] = true; + break; + } + } else if (parent instanceof AST_Exit) { + break; + } else if (parent instanceof AST_If) { + break; + } else if (parent instanceof AST_Sequence) { + if (parent.expressions[0] === child) continue; + } else if (parent instanceof AST_SimpleStatement) { + break; + } + return; + } + while (true) { + child = parent; + parent = compressor.parent(level++); + if (parent instanceof AST_BlockStatement) { + if (parent.body[0] === child) continue; + } else if (parent instanceof AST_If) { + if (match(parent.condition)) switch (child) { + case parent.body: + node[negated ? "falsy" : "truthy"] = true; + break; + case parent.alternative: + node[negated ? "truthy" : "falsy"] = true; + break; + } + } + return; + } + + function match(cond) { + if (node.equals(cond)) return true; + if (!(cond instanceof AST_UnaryPrefix)) return false; + if (cond.operator != "!") return false; + if (!node.equals(cond.expression)) return false; + negated = true; + return true; + } + } + + OPT(AST_If, function(self, compressor) { + if (is_empty(self.alternative)) self.alternative = null; + + if (!compressor.option("conditionals")) return self; + if (compressor.option("booleans") && !self.condition.has_side_effects(compressor)) { + mark_duplicate_condition(compressor, self.condition); + } + // if condition can be statically determined, warn and drop + // one of the blocks. note, statically determined implies + // “has no side effects”; also it doesn't work for cases like + // `x && true`, though it probably should. + if (compressor.option("dead_code")) { + var cond = fuzzy_eval(compressor, self.condition); + if (!cond) { + AST_Node.warn("Condition always false [{start}]", self.condition); + var body = [ + make_node(AST_SimpleStatement, self.condition, { body: self.condition }).transform(compressor), + ]; + extract_declarations_from_unreachable_code(compressor, self.body, body); + if (self.alternative) body.push(self.alternative); + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } else if (!(cond instanceof AST_Node)) { + AST_Node.warn("Condition always true [{start}]", self.condition); + var body = [ + make_node(AST_SimpleStatement, self.condition, { body: self.condition }).transform(compressor), + self.body, + ]; + if (self.alternative) extract_declarations_from_unreachable_code(compressor, self.alternative, body); + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } + } + var negated = self.condition.negate(compressor); + var self_condition_length = self.condition.print_to_string().length; + var negated_length = negated.print_to_string().length; + var negated_is_best = negated_length < self_condition_length; + if (self.alternative && negated_is_best) { + negated_is_best = false; // because we already do the switch here. + // no need to swap values of self_condition_length and negated_length + // here because they are only used in an equality comparison later on. + self.condition = negated; + var tmp = self.body; + self.body = self.alternative; + self.alternative = is_empty(tmp) ? null : tmp; + } + var body_defuns = []; + var body_var_defs = []; + var body_refs = []; + var body_exprs = sequencesize(self.body, body_defuns, body_var_defs, body_refs); + var alt_defuns = []; + var alt_var_defs = []; + var alt_refs = []; + var alt_exprs = sequencesize(self.alternative, alt_defuns, alt_var_defs, alt_refs); + if (body_exprs instanceof AST_BlockStatement || alt_exprs instanceof AST_BlockStatement) { + var body = [], var_defs = []; + if (body_exprs) { + [].push.apply(body, body_defuns); + [].push.apply(var_defs, body_var_defs); + if (body_exprs instanceof AST_BlockStatement) { + self.body = body_exprs; + } else if (body_exprs.length == 0) { + self.body = make_node(AST_EmptyStatement, self.body); + } else { + self.body = make_node(AST_SimpleStatement, self.body, { + body: make_sequence(self.body, body_exprs), + }); + } + body_refs.forEach(process_to_assign); + } + if (alt_exprs) { + [].push.apply(body, alt_defuns); + [].push.apply(var_defs, alt_var_defs); + if (alt_exprs instanceof AST_BlockStatement) { + self.alternative = alt_exprs; + } else if (alt_exprs.length == 0) { + self.alternative = null; + } else { + self.alternative = make_node(AST_SimpleStatement, self.alternative, { + body: make_sequence(self.alternative, alt_exprs), + }); + } + alt_refs.forEach(process_to_assign); + } + if (var_defs.length > 0) body.push(make_node(AST_Var, self, { definitions: var_defs })); + if (body.length > 0) { + body.push(self.transform(compressor)); + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } + } else if (body_exprs && alt_exprs) { + var body = body_defuns.concat(alt_defuns); + if (body_var_defs.length > 0 || alt_var_defs.length > 0) body.push(make_node(AST_Var, self, { + definitions: body_var_defs.concat(alt_var_defs), + })); + if (body_exprs.length == 0) { + body.push(make_node(AST_SimpleStatement, self.condition, { + body: alt_exprs.length > 0 ? make_node(AST_Binary, self, { + operator: "||", + left: self.condition, + right: make_sequence(self.alternative, alt_exprs), + }).transform(compressor) : self.condition.clone(), + }).optimize(compressor)); + } else if (alt_exprs.length == 0) { + if (self_condition_length === negated_length && !negated_is_best + && self.condition instanceof AST_Binary && self.condition.operator == "||") { + // although the code length of self.condition and negated are the same, + // negated does not require additional surrounding parentheses. + // see https://github.com/mishoo/UglifyJS/issues/979 + negated_is_best = true; + } + body.push(make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator: negated_is_best ? "||" : "&&", + left: negated_is_best ? negated : self.condition, + right: make_sequence(self.body, body_exprs), + }).transform(compressor), + }).optimize(compressor)); + } else { + body.push(make_node(AST_SimpleStatement, self, { + body: make_node(AST_Conditional, self, { + condition: self.condition, + consequent: make_sequence(self.body, body_exprs), + alternative: make_sequence(self.alternative, alt_exprs), + }), + }).optimize(compressor)); + } + body_refs.forEach(process_to_assign); + alt_refs.forEach(process_to_assign); + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } + if (is_empty(self.body)) self = make_node(AST_If, self, { + condition: negated, + body: self.alternative, + alternative: null, + }); + if (self.alternative instanceof AST_Exit && self.body.TYPE == self.alternative.TYPE) { + var cons_value = self.body.value; + var alt_value = self.alternative.value; + if (!cons_value && !alt_value) return make_node(AST_BlockStatement, self, { + body: [ + make_node(AST_SimpleStatement, self, { body: self.condition }), + self.body, + ], + }).optimize(compressor); + if (cons_value && alt_value || !keep_return_void()) { + var exit = make_node(self.body.CTOR, self, { + value: make_node(AST_Conditional, self, { + condition: self.condition, + consequent: cons_value || make_node(AST_Undefined, self.body).transform(compressor), + alternative: alt_value || make_node(AST_Undefined, self.alternative).transform(compressor), + }), + }); + if (exit instanceof AST_Return) exit.in_bool = self.body.in_bool || self.alternative.in_bool; + return exit; + } + } + if (self.body instanceof AST_If && !self.body.alternative && !self.alternative) { + self = make_node(AST_If, self, { + condition: make_node(AST_Binary, self.condition, { + operator: "&&", + left: self.condition, + right: self.body.condition, + }), + body: self.body.body, + alternative: null, + }); + } + if (aborts(self.body) && self.alternative) { + var alt = self.alternative; + self.alternative = null; + return make_node(AST_BlockStatement, self, { body: [ self, alt ] }).optimize(compressor); + } + if (aborts(self.alternative)) { + var body = self.body; + self.body = self.alternative; + self.condition = negated_is_best ? negated : self.condition.negate(compressor); + self.alternative = null; + return make_node(AST_BlockStatement, self, { body: [ self, body ] }).optimize(compressor); + } + if (self.alternative) { + var body_stats = as_array(self.body); + var body_index = last_index(body_stats); + var alt_stats = as_array(self.alternative); + var alt_index = last_index(alt_stats); + for (var stats = []; body_index >= 0 && alt_index >= 0;) { + var stat = body_stats[body_index]; + var alt_stat = alt_stats[alt_index]; + if (stat.equals(alt_stat)) { + body_stats.splice(body_index--, 1); + alt_stats.splice(alt_index--, 1); + stats.unshift(merge_expression(stat, alt_stat)); + } else { + if (!(stat instanceof AST_SimpleStatement)) break; + if (!(alt_stat instanceof AST_SimpleStatement)) break; + var expr1 = stat.body.tail_node(); + var expr2 = alt_stat.body.tail_node(); + if (!expr1.equals(expr2)) break; + body_index = pop_expr(body_stats, stat.body, body_index); + alt_index = pop_expr(alt_stats, alt_stat.body, alt_index); + stats.unshift(make_node(AST_SimpleStatement, expr1, { body: merge_expression(expr1, expr2) })); + } + } + if (stats.length > 0) { + self.body = body_stats.length > 0 ? make_node(AST_BlockStatement, self, { + body: body_stats, + }) : make_node(AST_EmptyStatement, self); + self.alternative = alt_stats.length > 0 ? make_node(AST_BlockStatement, self, { + body: alt_stats, + }) : null; + stats.unshift(self); + return make_node(AST_BlockStatement, self, { body: stats }).optimize(compressor); + } + } + if (compressor.option("typeofs")) mark_locally_defined(self.condition, self.body, self.alternative); + return self; + + function as_array(node) { + return node instanceof AST_BlockStatement ? node.body : [ node ]; + } + + function keep_return_void() { + var has_finally = false, level = 0, node = compressor.self(); + do { + if (node instanceof AST_Catch) { + if (compressor.parent(level).bfinally) has_finally = true; + level++; + } else if (node instanceof AST_Finally) { + level++; + } else if (node instanceof AST_Scope) { + return has_finally && in_async_generator(node); + } else if (node instanceof AST_Try) { + if (node.bfinally) has_finally = true; + } + } while (node = compressor.parent(level++)); + } + + function last_index(stats) { + for (var index = stats.length; --index >= 0;) { + if (!is_declaration(stats[index], true)) break; + } + return index; + } + + function pop_expr(stats, body, index) { + if (body instanceof AST_Sequence) { + stats[index] = make_node(AST_SimpleStatement, body, { + body: make_sequence(body, body.expressions.slice(0, -1)), + }); + } else { + stats.splice(index--, 1); + } + return index; + } + + function sequencesize(stat, defuns, var_defs, refs) { + if (stat == null) return []; + if (stat instanceof AST_BlockStatement) { + var exprs = []; + for (var i = 0; i < stat.body.length; i++) { + var line = stat.body[i]; + if (line instanceof AST_EmptyStatement) continue; + if (line instanceof AST_Exit) { + if (i == 0) return; + if (exprs.length > 0) { + line = line.clone(); + exprs.push(line.value || make_node(AST_Undefined, line).transform(compressor)); + line.value = make_sequence(stat, exprs); + } + var block = stat.clone(); + block.body = block.body.slice(i + 1); + block.body.unshift(line); + return block; + } + if (line instanceof AST_LambdaDefinition) { + defuns.push(line); + } else if (line instanceof AST_SimpleStatement) { + if (!compressor.option("sequences") && exprs.length > 0) return; + exprs.push(line.body); + } else if (line instanceof AST_Var) { + if (!compressor.option("sequences") && exprs.length > 0) return; + line.remove_initializers(compressor, var_defs); + line.definitions.forEach(process_var_def); + } else { + return; + } + } + return exprs; + } + if (stat instanceof AST_LambdaDefinition) { + defuns.push(stat); + return []; + } + if (stat instanceof AST_EmptyStatement) return []; + if (stat instanceof AST_SimpleStatement) return [ stat.body ]; + if (stat instanceof AST_Var) { + var exprs = []; + stat.remove_initializers(compressor, var_defs); + stat.definitions.forEach(process_var_def); + return exprs; + } + + function process_var_def(var_def) { + if (!var_def.value) return; + exprs.push(make_node(AST_Assign, var_def, { + operator: "=", + left: var_def.name.convert_symbol(AST_SymbolRef, function(ref) { + refs.push(ref); + }), + right: var_def.value, + })); + } + } + }); + + OPT(AST_Switch, function(self, compressor) { + if (!compressor.option("switches")) return self; + if (!compressor.option("dead_code")) return self; + var body = []; + var branch; + var decl = []; + var default_branch; + var exact_match; + var side_effects = []; + for (var i = 0, len = self.body.length; i < len; i++) { + branch = self.body[i]; + if (branch instanceof AST_Default) { + var prev = body[body.length - 1]; + if (default_branch || is_break(branch.body[0], compressor) && (!prev || aborts(prev))) { + eliminate_branch(branch, prev); + continue; + } else { + default_branch = branch; + } + } else { + var exp = branch.expression; + var equals = make_node(AST_Binary, self, { + operator: "===", + left: self.expression, + right: exp, + }).evaluate(compressor, true); + if (!equals) { + if (exp.has_side_effects(compressor)) side_effects.push(exp); + eliminate_branch(branch, body[body.length - 1]); + continue; + } + if (!(equals instanceof AST_Node)) { + if (default_branch) { + var default_index = body.indexOf(default_branch); + body.splice(default_index, 1); + eliminate_branch(default_branch, body[default_index - 1]); + default_branch = null; + } + if (exp.has_side_effects(compressor)) { + exact_match = branch; + } else { + default_branch = branch = make_node(AST_Default, branch); + } + while (++i < len) eliminate_branch(self.body[i], branch); + } + } + if (i + 1 >= len || aborts(branch)) { + var prev = body[body.length - 1]; + var statements = branch.body; + if (aborts(prev)) switch (prev.body.length - statements.length) { + case 1: + var stat = prev.body[prev.body.length - 1]; + if (!is_break(stat, compressor)) break; + statements = statements.concat(stat); + case 0: + var prev_block = make_node(AST_BlockStatement, prev); + var next_block = make_node(AST_BlockStatement, branch, { body: statements }); + if (prev_block.equals(next_block)) prev.body = []; + } + } + if (side_effects.length) { + if (branch instanceof AST_Default) { + body.push(make_node(AST_Case, self, { expression: make_sequence(self, side_effects), body: [] })); + } else { + side_effects.push(branch.expression); + branch.expression = make_sequence(self, side_effects); + } + side_effects = []; + } + body.push(branch); + } + if (side_effects.length && !exact_match) { + body.push(make_node(AST_Case, self, { expression: make_sequence(self, side_effects), body: [] })); + } + while (branch = body[body.length - 1]) { + var stat = branch.body[branch.body.length - 1]; + if (is_break(stat, compressor)) branch.body.pop(); + if (branch === default_branch) { + if (!has_declarations_only(branch)) break; + } else if (branch.expression.has_side_effects(compressor)) { + break; + } else if (default_branch) { + if (!has_declarations_only(default_branch)) break; + if (body[body.length - 2] !== default_branch) break; + default_branch.body = default_branch.body.concat(branch.body); + branch.body = []; + } else if (!has_declarations_only(branch)) break; + eliminate_branch(branch); + if (body.pop() === default_branch) default_branch = null; + } + if (!branch) { + decl.push(make_node(AST_SimpleStatement, self.expression, { body: self.expression })); + if (side_effects.length) decl.push(make_node(AST_SimpleStatement, self, { + body: make_sequence(self, side_effects), + })); + return make_node(AST_BlockStatement, self, { body: decl }).optimize(compressor); + } + if (branch === default_branch) while (branch = body[body.length - 2]) { + if (branch instanceof AST_Default) break; + if (!has_declarations_only(branch)) break; + var exp = branch.expression; + if (exp.has_side_effects(compressor)) { + var prev = body[body.length - 3]; + if (prev && !aborts(prev)) break; + default_branch.body.unshift(make_node(AST_SimpleStatement, self, { body: exp })); + } + eliminate_branch(branch); + body.splice(-2, 1); + } + body[0].body = decl.concat(body[0].body); + self.body = body; + if (compressor.option("conditionals")) switch (body.length) { + case 1: + if (!no_break(body[0])) break; + var exp = body[0].expression; + var statements = body[0].body.slice(); + if (body[0] !== default_branch && body[0] !== exact_match) return make_node(AST_If, self, { + condition: make_node(AST_Binary, self, { + operator: "===", + left: self.expression, + right: exp, + }), + body: make_node(AST_BlockStatement, self, { body: statements }), + alternative: null, + }).optimize(compressor); + if (exp) statements.unshift(make_node(AST_SimpleStatement, exp, { body: exp })); + statements.unshift(make_node(AST_SimpleStatement, self.expression, { body: self.expression })); + return make_node(AST_BlockStatement, self, { body: statements }).optimize(compressor); + case 2: + if (!member(default_branch, body) || !no_break(body[1])) break; + var statements = body[0].body.slice(); + var exclusive = statements.length && is_break(statements[statements.length - 1], compressor); + if (exclusive) statements.pop(); + if (!all(statements, no_break)) break; + var alternative = body[1].body.length && make_node(AST_BlockStatement, body[1]); + var node = make_node(AST_If, self, { + condition: make_node(AST_Binary, self, body[0] === default_branch ? { + operator: "!==", + left: self.expression, + right: body[1].expression, + } : { + operator: "===", + left: self.expression, + right: body[0].expression, + }), + body: make_node(AST_BlockStatement, body[0], { body: statements }), + alternative: exclusive && alternative || null, + }); + if (!exclusive && alternative) node = make_node(AST_BlockStatement, self, { body: [ node, alternative ] }); + return node.optimize(compressor); + } + return self; + + function is_break(node, tw) { + return node instanceof AST_Break && tw.loopcontrol_target(node) === self; + } + + function no_break(node) { + var found = false; + var tw = new TreeWalker(function(node) { + if (found + || node instanceof AST_Lambda + || node instanceof AST_SimpleStatement) return true; + if (is_break(node, tw)) found = true; + }); + tw.push(self); + node.walk(tw); + return !found; + } + + function eliminate_branch(branch, prev) { + if (prev && !aborts(prev)) { + prev.body = prev.body.concat(branch.body); + } else { + extract_declarations_from_unreachable_code(compressor, branch, decl); + } + } + }); + + OPT(AST_Try, function(self, compressor) { + self.body = tighten_body(self.body, compressor); + if (compressor.option("dead_code")) { + if (has_declarations_only(self) + && !(self.bcatch && self.bcatch.argname && self.bcatch.argname.match_symbol(function(node) { + return node instanceof AST_SymbolCatch && !can_drop_symbol(node); + }, true))) { + var body = []; + if (self.bcatch) { + extract_declarations_from_unreachable_code(compressor, self.bcatch, body); + body.forEach(function(stat) { + if (!(stat instanceof AST_Var)) return; + stat.definitions.forEach(function(var_def) { + var def = var_def.name.definition().redefined(); + if (!def) return; + var_def.name = var_def.name.clone(); + var_def.name.thedef = def; + }); + }); + } + body.unshift(make_node(AST_BlockStatement, self).optimize(compressor)); + if (self.bfinally) { + body.push(make_node(AST_BlockStatement, self.bfinally).optimize(compressor)); + } + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } + if (self.bfinally && has_declarations_only(self.bfinally)) { + var body = make_node(AST_BlockStatement, self.bfinally).optimize(compressor); + body = self.body.concat(body); + if (!self.bcatch) return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + self.body = body; + self.bfinally = null; + } + } + return self; + }); + + function remove_initializers(make_value) { + return function(compressor, defns) { + var dropped = false; + this.definitions.forEach(function(defn) { + if (defn.value) dropped = true; + defn.name.match_symbol(function(node) { + if (node instanceof AST_SymbolDeclaration) defns.push(make_node(AST_VarDef, node, { + name: node, + value: make_value(compressor, node), + })); + }, true); + }); + return dropped; + }; + } + + AST_Const.DEFMETHOD("remove_initializers", remove_initializers(function(compressor, node) { + return make_node(AST_Undefined, node).optimize(compressor); + })); + AST_Let.DEFMETHOD("remove_initializers", remove_initializers(return_null)); + AST_Var.DEFMETHOD("remove_initializers", remove_initializers(return_null)); + + AST_Definitions.DEFMETHOD("to_assignments", function() { + var assignments = this.definitions.reduce(function(a, defn) { + var def = defn.name.definition(); + var value = defn.value; + if (value) { + if (value instanceof AST_Sequence) value = value.clone(); + var name = make_node(AST_SymbolRef, defn.name); + var assign = make_node(AST_Assign, defn, { + operator: "=", + left: name, + right: value, + }); + a.push(assign); + var fixed = function() { + return assign.right; + }; + fixed.assigns = [ assign ]; + fixed.direct_access = def.direct_access; + fixed.escaped = def.escaped; + name.fixed = fixed; + def.references.forEach(function(ref) { + if (!ref.fixed) return; + var assigns = ref.fixed.assigns; + if (!assigns) return; + if (assigns[0] !== defn) return; + if (assigns.length > 1 || ref.fixed.to_binary || ref.fixed.to_prefix) { + assigns[0] = assign; + } else { + ref.fixed = fixed; + if (def.fixed === ref.fixed) def.fixed = fixed; + } + }); + def.references.push(name); + } + def.assignments++; + def.eliminated++; + def.single_use = false; + return a; + }, []); + if (assignments.length == 0) return null; + return make_sequence(this, assignments); + }); + + function is_safe_lexical(def) { + return def.name != "arguments" && def.orig.length < (def.orig[0] instanceof AST_SymbolLambda ? 3 : 2); + } + + function may_overlap(compressor, def) { + if (compressor.exposed(def)) return true; + var scope = def.scope.resolve(); + for (var s = def.scope; s !== scope;) { + s = s.parent_scope; + if (s.var_names().has(def.name)) return true; + } + } + + function to_var(stat, scope) { + return make_node(AST_Var, stat, { + definitions: stat.definitions.map(function(defn) { + return make_node(AST_VarDef, defn, { + name: defn.name.convert_symbol(AST_SymbolVar, function(name, node) { + var def = name.definition(); + def.orig[def.orig.indexOf(node)] = name; + if (def.scope === scope) return; + def.scope = scope; + scope.variables.set(def.name, def); + scope.enclosed.push(def); + scope.var_names().set(def.name, true); + }), + value: defn.value, + }); + }), + }); + } + + function can_varify(compressor, sym) { + var def = sym.definition(); + return (def.fixed || def.fixed === 0) + && is_safe_lexical(def) + && same_scope(def) + && !may_overlap(compressor, def); + } + + function varify(self, compressor) { + return compressor.option("varify") && all(self.definitions, function(defn) { + return !defn.name.match_symbol(function(node) { + if (node instanceof AST_SymbolDeclaration) return !can_varify(compressor, node); + }, true); + }) ? to_var(self, compressor.find_parent(AST_Scope)) : self; + } + + OPT(AST_Const, varify); + OPT(AST_Let, varify); + + function trim_optional_chain(node, compressor) { + if (!compressor.option("optional_chains")) return; + if (node.terminal) do { + var expr = node.expression; + if (node.optional) { + var ev = fuzzy_eval(compressor, expr, true); + if (ev == null) return make_node(AST_UnaryPrefix, node, { + operator: "void", + expression: expr, + }).optimize(compressor); + if (!(ev instanceof AST_Node)) node.optional = false; + } + node = expr; + } while ((node.TYPE == "Call" || node instanceof AST_PropAccess) && !node.terminal); + } + + function lift_sequence_in_expression(node, compressor) { + var exp = node.expression; + if (!(exp instanceof AST_Sequence)) return node; + var x = exp.expressions.slice(); + var e = node.clone(); + e.expression = x.pop(); + x.push(e); + return make_sequence(node, x); + } + + function drop_unused_call_args(call, compressor, fns_with_marked_args) { + var exp = call.expression; + var fn = exp instanceof AST_SymbolRef ? exp.fixed_value() : exp; + if (!(fn instanceof AST_Lambda)) return; + if (fn.uses_arguments) return; + if (fn.pinned()) return; + if (fns_with_marked_args && fns_with_marked_args.indexOf(fn) < 0) return; + var args = call.args; + if (!all(args, function(arg) { + return !(arg instanceof AST_Spread); + })) return; + var argnames = fn.argnames; + var is_iife = fn === exp && !fn.name; + if (fn.rest) { + if (!(is_iife && compressor.option("rests"))) return; + var insert = argnames.length; + args = args.slice(0, insert); + while (args.length < insert) args.push(make_node(AST_Undefined, call).optimize(compressor)); + args.push(make_node(AST_Array, call, { elements: call.args.slice(insert) })); + argnames = argnames.concat(fn.rest); + fn.rest = null; + } else { + args = args.slice(); + argnames = argnames.slice(); + } + var pos = 0, last = 0; + var drop_defaults = is_iife && compressor.option("default_values"); + var drop_fargs = is_iife && compressor.drop_fargs(fn, call) ? function(argname, arg) { + if (!argname) return true; + if (argname instanceof AST_DestructuredArray) { + return argname.elements.length == 0 && !argname.rest && arg instanceof AST_Array; + } + if (argname instanceof AST_DestructuredObject) { + return argname.properties.length == 0 && !argname.rest && arg && !arg.may_throw_on_access(compressor); + } + return argname.unused; + } : return_false; + var side_effects = []; + for (var i = 0; i < args.length; i++) { + var argname = argnames[i]; + if (drop_defaults && argname instanceof AST_DefaultValue && args[i].is_defined(compressor)) { + argnames[i] = argname = argname.name; + } + if (!argname || argname.unused !== undefined) { + var node = args[i].drop_side_effect_free(compressor); + if (drop_fargs(argname)) { + if (argname) argnames.splice(i, 1); + args.splice(i, 1); + if (node) side_effects.push(node); + i--; + continue; + } else if (node) { + side_effects.push(node); + args[pos++] = make_sequence(call, side_effects); + side_effects = []; + } else if (argname) { + if (side_effects.length) { + args[pos++] = make_sequence(call, side_effects); + side_effects = []; + } else { + args[pos++] = make_node(AST_Number, args[i], { value: 0 }); + continue; + } + } + } else if (drop_fargs(argname, args[i])) { + var node = args[i].drop_side_effect_free(compressor); + argnames.splice(i, 1); + args.splice(i, 1); + if (node) side_effects.push(node); + i--; + continue; + } else { + side_effects.push(args[i]); + args[pos++] = make_sequence(call, side_effects); + side_effects = []; + } + last = pos; + } + for (; i < argnames.length; i++) { + if (drop_fargs(argnames[i])) argnames.splice(i--, 1); + } + fn.argnames = argnames; + args.length = last; + call.args = args; + if (!side_effects.length) return; + var arg = make_sequence(call, side_effects); + args.push(args.length < argnames.length ? make_node(AST_UnaryPrefix, call, { + operator: "void", + expression: arg, + }) : arg); + } + + function avoid_await_yield(compressor, parent_scope) { + if (!parent_scope) parent_scope = compressor.find_parent(AST_Scope); + var avoid = []; + if (is_async(parent_scope) || parent_scope instanceof AST_Toplevel && compressor.option("module")) { + avoid.push("await"); + } + if (is_generator(parent_scope)) avoid.push("yield"); + return avoid.length && makePredicate(avoid); + } + + function safe_from_await_yield(fn, avoid) { + if (!avoid) return true; + var safe = true; + var tw = new TreeWalker(function(node) { + if (!safe) return true; + if (node instanceof AST_Scope) { + if (node === fn) return; + if (is_arrow(node)) { + for (var i = 0; safe && i < node.argnames.length; i++) node.argnames[i].walk(tw); + } else if (node instanceof AST_LambdaDefinition && avoid[node.name.name]) { + safe = false; + } + return true; + } + if (node instanceof AST_Symbol && avoid[node.name] && node !== fn.name) safe = false; + }); + fn.walk(tw); + return safe; + } + + function safe_from_strict_mode(fn, compressor) { + return fn.in_strict_mode(compressor) || !compressor.has_directive("use strict"); + } + + OPT(AST_Call, function(self, compressor) { + var exp = self.expression; + var terminated = trim_optional_chain(self, compressor); + if (terminated) return terminated; + if (compressor.option("sequences")) { + if (exp instanceof AST_PropAccess) { + var seq = lift_sequence_in_expression(exp, compressor); + if (seq !== exp) { + var call = self.clone(); + call.expression = seq.expressions.pop(); + seq.expressions.push(call); + return seq.optimize(compressor); + } + } else if (!needs_unbinding(exp.tail_node())) { + var seq = lift_sequence_in_expression(self, compressor); + if (seq !== self) return seq.optimize(compressor); + } + } + if (compressor.option("unused")) drop_unused_call_args(self, compressor); + if (compressor.option("unsafe")) { + if (is_undeclared_ref(exp)) switch (exp.name) { + case "Array": + // Array(n) ---> [ , , ... , ] + if (self.args.length == 1) { + var first = self.args[0]; + if (first instanceof AST_Number) try { + var length = first.value; + if (length > 6) break; + var elements = Array(length); + for (var i = 0; i < length; i++) elements[i] = make_node(AST_Hole, self); + return make_node(AST_Array, self, { elements: elements }); + } catch (ex) { + AST_Node.warn("Invalid array length: {length} [{start}]", { + length: length, + start: self.start, + }); + break; + } + if (!first.is_boolean(compressor) && !first.is_string(compressor)) break; + } + // Array(...) ---> [ ... ] + return make_node(AST_Array, self, { elements: self.args }); + case "Object": + // Object() ---> {} + if (self.args.length == 0) return make_node(AST_Object, self, { properties: [] }); + break; + case "String": + // String() ---> "" + if (self.args.length == 0) return make_node(AST_String, self, { value: "" }); + // String(x) ---> "" + x + if (self.args.length == 1) return make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_String, self, { value: "" }), + right: self.args[0], + }).optimize(compressor); + break; + case "Number": + // Number() ---> 0 + if (self.args.length == 0) return make_node(AST_Number, self, { value: 0 }); + // Number(x) ---> +("" + x) + if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, { + operator: "+", + expression: make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_String, self, { value: "" }), + right: self.args[0], + }), + }).optimize(compressor); + break; + case "Boolean": + // Boolean() ---> false + if (self.args.length == 0) return make_node(AST_False, self).optimize(compressor); + // Boolean(x) ---> !!x + if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: self.args[0], + }), + }).optimize(compressor); + break; + case "RegExp": + // attempt to convert RegExp(...) to literal + var params = []; + if (all(self.args, function(arg) { + var value = arg.evaluate(compressor); + params.unshift(value); + return arg !== value; + })) try { + return best_of(compressor, self, make_node(AST_RegExp, self, { + value: RegExp.apply(RegExp, params), + })); + } catch (ex) { + AST_Node.warn("Error converting {this} [{start}]", self); + } + break; + } else if (exp instanceof AST_Dot) switch (exp.property) { + case "toString": + // x.toString() ---> "" + x + var expr = exp.expression; + if (self.args.length == 0 && !(expr.may_throw_on_access(compressor) || expr instanceof AST_Super)) { + return make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_String, self, { value: "" }), + right: expr, + }).optimize(compressor); + } + break; + case "join": + if (exp.expression instanceof AST_Array && self.args.length < 2) EXIT: { + var separator = self.args[0]; + // [].join() ---> "" + // [].join(x) ---> (x, "") + if (exp.expression.elements.length == 0 && !(separator instanceof AST_Spread)) { + return separator ? make_sequence(self, [ + separator, + make_node(AST_String, self, { value: "" }), + ]).optimize(compressor) : make_node(AST_String, self, { value: "" }); + } + if (separator) { + separator = separator.evaluate(compressor); + if (separator instanceof AST_Node) break EXIT; // not a constant + } + var elements = []; + var consts = []; + for (var i = 0; i < exp.expression.elements.length; i++) { + var el = exp.expression.elements[i]; + var value = el.evaluate(compressor); + if (value !== el) { + consts.push(value); + } else if (el instanceof AST_Spread) { + break EXIT; + } else { + if (consts.length > 0) { + elements.push(make_node(AST_String, self, { value: consts.join(separator) })); + consts.length = 0; + } + elements.push(el); + } + } + if (consts.length > 0) elements.push(make_node(AST_String, self, { + value: consts.join(separator), + })); + // [ x ].join() ---> "" + x + // [ x ].join(".") ---> "" + x + // [ 1, 2, 3 ].join() ---> "1,2,3" + // [ 1, 2, 3 ].join(".") ---> "1.2.3" + if (elements.length == 1) { + if (elements[0].is_string(compressor)) return elements[0]; + return make_node(AST_Binary, elements[0], { + operator: "+", + left: make_node(AST_String, self, { value: "" }), + right: elements[0], + }); + } + // [ 1, 2, a, 3 ].join("") ---> "12" + a + "3" + if (separator == "") { + var first; + if (elements[0].is_string(compressor) || elements[1].is_string(compressor)) { + first = elements.shift(); + } else { + first = make_node(AST_String, self, { value: "" }); + } + return elements.reduce(function(prev, el) { + return make_node(AST_Binary, el, { + operator: "+", + left: prev, + right: el, + }); + }, first).optimize(compressor); + } + // [ x, "foo", "bar", y ].join() ---> [ x, "foo,bar", y ].join() + // [ x, "foo", "bar", y ].join("-") ---> [ x, "foo-bar", y ].join("-") + // need this awkward cloning to not affect original element + // best_of will decide which one to get through. + var node = self.clone(); + node.expression = node.expression.clone(); + node.expression.expression = node.expression.expression.clone(); + node.expression.expression.elements = elements; + return best_of(compressor, self, node); + } + break; + case "charAt": + if (self.args.length < 2) { + var node = make_node(AST_Binary, self, { + operator: "||", + left: make_node(AST_Sub, self, { + expression: exp.expression, + property: self.args.length ? make_node(AST_Binary, self.args[0], { + operator: "|", + left: make_node(AST_Number, self, { value: 0 }), + right: self.args[0], + }) : make_node(AST_Number, self, { value: 0 }), + }).optimize(compressor), + right: make_node(AST_String, self, { value: "" }), + }); + node.is_string = return_true; + return node.optimize(compressor); + } + break; + case "apply": + if (self.args.length == 2 && self.args[1] instanceof AST_Array) { + var args = self.args[1].elements.slice(); + args.unshift(self.args[0]); + return make_node(AST_Call, self, { + expression: make_node(AST_Dot, exp, { + expression: exp.expression, + property: "call", + }), + args: args, + }).optimize(compressor); + } + break; + case "call": + var func = exp.expression; + if (func instanceof AST_SymbolRef) { + func = func.fixed_value(); + } + if (func instanceof AST_Lambda && !func.contains_this()) { + return (self.args.length ? make_sequence(self, [ + self.args[0], + make_node(AST_Call, self, { + expression: exp.expression, + args: self.args.slice(1), + }), + ]) : make_node(AST_Call, self, { + expression: exp.expression, + args: [], + })).optimize(compressor); + } + break; + } else if (compressor.option("side_effects") + && exp instanceof AST_Call + && exp.args.length == 1 + && is_undeclared_ref(exp.expression) + && exp.expression.name == "Object") { + var call = self.clone(); + call.expression = maintain_this_binding(self, exp, exp.args[0]); + return call.optimize(compressor); + } + } + if (compressor.option("unsafe_Function") + && is_undeclared_ref(exp) + && exp.name == "Function") { + // new Function() ---> function(){} + if (self.args.length == 0) return make_node(AST_Function, self, { + argnames: [], + body: [], + }).init_vars(exp.scope); + if (all(self.args, function(x) { + return x instanceof AST_String; + })) { + // quite a corner-case, but we can handle it: + // https://github.com/mishoo/UglifyJS/issues/203 + // if the code argument is a constant, then we can minify it. + try { + var code = "n(function(" + self.args.slice(0, -1).map(function(arg) { + return arg.value; + }).join() + "){" + self.args[self.args.length - 1].value + "})"; + var ast = parse(code); + var mangle = { ie: compressor.option("ie") }; + ast.figure_out_scope(mangle); + var comp = new Compressor(compressor.options); + ast = ast.transform(comp); + ast.figure_out_scope(mangle); + ast.compute_char_frequency(mangle); + ast.mangle_names(mangle); + var fun; + ast.walk(new TreeWalker(function(node) { + if (fun) return true; + if (node instanceof AST_Lambda) { + fun = node; + return true; + } + })); + var code = OutputStream(); + AST_BlockStatement.prototype._codegen.call(fun, code); + self.args = [ + make_node(AST_String, self, { + value: fun.argnames.map(function(arg) { + return arg.print_to_string(); + }).join(), + }), + make_node(AST_String, self.args[self.args.length - 1], { + value: code.get().replace(/^\{|\}$/g, "") + }), + ]; + return self; + } catch (ex) { + if (ex instanceof JS_Parse_Error) { + AST_Node.warn("Error parsing code passed to new Function [{start}]", self.args[self.args.length - 1]); + AST_Node.warn(ex.toString()); + } else { + throw ex; + } + } + } + } + var fn = exp instanceof AST_SymbolRef ? exp.fixed_value() : exp; + var parent = compressor.parent(), current = compressor.self(); + var is_func = fn instanceof AST_Lambda + && (!is_async(fn) || compressor.option("awaits") && parent instanceof AST_Await) + && (!is_generator(fn) || compressor.option("yields") && current instanceof AST_Yield && current.nested); + var stat = is_func && fn.first_statement(); + var has_default = 0, has_destructured = false; + var has_spread = !all(self.args, function(arg) { + return !(arg instanceof AST_Spread); + }); + var can_drop = is_func && all(fn.argnames, function(argname, index) { + if (has_default == 1 && self.args[index] instanceof AST_Spread) has_default = 2; + if (argname instanceof AST_DefaultValue) { + if (!has_default) has_default = 1; + var arg = has_default == 1 && self.args[index]; + if (!is_undefined(arg)) has_default = 2; + if (has_arg_refs(fn, argname.value)) return false; + argname = argname.name; + } + if (argname instanceof AST_Destructured) { + has_destructured = true; + if (has_arg_refs(fn, argname)) return false; + } + return true; + }) && !(fn.rest instanceof AST_Destructured && has_arg_refs(fn, fn.rest)); + var can_inline = can_drop + && compressor.option("inline") + && !self.is_expr_pure(compressor) + && (exp === fn || safe_from_strict_mode(fn, compressor)); + if (can_inline && stat instanceof AST_Return) { + var value = stat.value; + if (exp === fn + && !fn.name + && (!value || value.is_constant_expression()) + && safe_from_await_yield(fn, avoid_await_yield(compressor))) { + return make_sequence(self, convert_args(value)).optimize(compressor); + } + } + if (is_func && !fn.contains_this()) { + var def, value, var_assigned = false; + if (can_inline + && !fn.uses_arguments + && !fn.pinned() + && !(fn.name && fn instanceof AST_LambdaExpression) + && (exp === fn || !recursive_ref(compressor, def = exp.definition(), fn) + && fn.is_constant_expression(find_scope(compressor))) + && (value = can_flatten_body(stat))) { + var replacing = exp === fn || def.single_use && def.references.length - def.replaced == 1; + if (can_substitute_directly()) { + var args = self.args.slice(); + var refs = []; + var retValue = value.clone(true).transform(new TreeTransformer(function(node) { + if (node instanceof AST_SymbolRef) { + var def = node.definition(); + if (fn.variables.get(node.name) !== def) { + refs.push(node); + return node; + } + var index = resolve_index(def); + var arg = args[index]; + if (!arg) return make_node(AST_Undefined, self); + args[index] = null; + var parent = this.parent(); + return parent ? maintain_this_binding(parent, node, arg) : arg; + } + })); + var save_inlined = fn.inlined; + if (exp !== fn) fn.inlined = true; + var exprs = []; + args.forEach(function(arg) { + if (!arg) return; + arg = arg.clone(true); + arg.walk(new TreeWalker(function(node) { + if (node instanceof AST_SymbolRef) refs.push(node); + })); + exprs.push(arg); + }, []); + exprs.push(retValue); + var node = make_sequence(self, exprs).optimize(compressor); + fn.inlined = save_inlined; + node = maintain_this_binding(parent, current, node); + if (replacing || best_of_expression(node, self) === node) { + refs.forEach(function(ref) { + ref.scope = exp === fn ? fn.parent_scope : exp.scope; + ref.reference(); + var def = ref.definition(); + if (replacing) def.replaced++; + def.single_use = false; + }); + return node; + } else if (!node.has_side_effects(compressor)) { + self.drop_side_effect_free = function(compressor, first_in_statement) { + var self = this; + var exprs = self.args.slice(); + exprs.unshift(self.expression); + return make_sequence(self, exprs).drop_side_effect_free(compressor, first_in_statement); + }; + } + } + var arg_used, insert, in_loop, scope; + if (replacing && can_inject_symbols()) { + fn._squeezed = true; + if (exp !== fn) fn.parent_scope = exp.scope; + var node = make_sequence(self, flatten_fn()).optimize(compressor); + return maintain_this_binding(parent, current, node); + } + } + if (compressor.option("side_effects") + && can_drop + && all(fn.body, is_empty) + && (fn === exp ? fn_name_unused(fn, compressor) : !has_default && !has_destructured && !fn.rest) + && !(is_arrow(fn) && fn.value) + && safe_from_await_yield(fn, avoid_await_yield(compressor))) { + return make_sequence(self, convert_args()).optimize(compressor); + } + } + if (compressor.option("drop_console")) { + if (exp instanceof AST_PropAccess) { + var name = exp.expression; + while (name.expression) { + name = name.expression; + } + if (is_undeclared_ref(name) && name.name == "console") { + return make_node(AST_Undefined, self).optimize(compressor); + } + } + } + if (compressor.option("negate_iife") && parent instanceof AST_SimpleStatement && is_iife_call(current)) { + return self.negate(compressor, true); + } + return try_evaluate(compressor, self); + + function make_void_lhs(orig) { + return make_node(AST_Sub, orig, { + expression: make_node(AST_Array, orig, { elements: [] }), + property: make_node(AST_Number, orig, { value: 0 }), + }); + } + + function convert_args(value) { + var args = self.args.slice(); + var destructured = has_default > 1 || has_destructured || fn.rest; + if (destructured || has_spread) args = [ make_node(AST_Array, self, { elements: args }) ]; + if (destructured) { + var tt = new TreeTransformer(function(node, descend) { + if (node instanceof AST_DefaultValue) return make_node(AST_DefaultValue, node, { + name: node.name.transform(tt) || make_void_lhs(node), + value: node.value, + }); + if (node instanceof AST_DestructuredArray) { + var elements = []; + node.elements.forEach(function(node, index) { + node = node.transform(tt); + if (node) elements[index] = node; + }); + fill_holes(node, elements); + return make_node(AST_DestructuredArray, node, { elements: elements }); + } + if (node instanceof AST_DestructuredObject) { + var properties = [], side_effects = []; + node.properties.forEach(function(prop) { + var key = prop.key; + var value = prop.value.transform(tt); + if (value) { + if (side_effects.length) { + if (!(key instanceof AST_Node)) key = make_node_from_constant(key, prop); + side_effects.push(key); + key = make_sequence(node, side_effects); + side_effects = []; + } + properties.push(make_node(AST_DestructuredKeyVal, prop, { + key: key, + value: value, + })); + } else if (key instanceof AST_Node) { + side_effects.push(key); + } + }); + if (side_effects.length) properties.push(make_node(AST_DestructuredKeyVal, node, { + key: make_sequence(node, side_effects), + value: make_void_lhs(node), + })); + return make_node(AST_DestructuredObject, node, { properties: properties }); + } + if (node instanceof AST_SymbolFunarg) return null; + }); + var lhs = []; + fn.argnames.forEach(function(argname, index) { + argname = argname.transform(tt); + if (argname) lhs[index] = argname; + }); + var rest = fn.rest && fn.rest.transform(tt); + if (rest) lhs.length = fn.argnames.length; + fill_holes(fn, lhs); + args[0] = make_node(AST_Assign, self, { + operator: "=", + left: make_node(AST_DestructuredArray, fn, { + elements: lhs, + rest: rest, + }), + right: args[0], + }); + } else fn.argnames.forEach(function(argname) { + if (argname instanceof AST_DefaultValue) args.push(argname.value); + }); + args.push(value || make_node(AST_Undefined, self)); + return args; + } + + function noop_value() { + return self.call_only ? make_node(AST_Number, self, { value: 0 }) : make_node(AST_Undefined, self); + } + + function return_value(stat) { + if (!stat) return noop_value(); + if (stat instanceof AST_Return) return stat.value || noop_value(); + if (stat instanceof AST_SimpleStatement) { + return self.call_only ? stat.body : make_node(AST_UnaryPrefix, stat, { + operator: "void", + expression: stat.body, + }); + } + } + + function can_flatten_body(stat) { + var len = fn.body.length; + if (len < 2) { + stat = return_value(stat); + if (stat) return stat; + } + if (compressor.option("inline") < 3) return false; + stat = null; + for (var i = 0; i < len; i++) { + var line = fn.body[i]; + if (line instanceof AST_Var) { + if (var_assigned) { + if (!stat) continue; + if (!(stat instanceof AST_SimpleStatement)) return false; + if (!declarations_only(line)) stat = null; + } else if (!declarations_only(line)) { + if (stat && !(stat instanceof AST_SimpleStatement)) return false; + stat = null; + var_assigned = true; + } + } else if (line instanceof AST_AsyncDefun + || line instanceof AST_Defun + || line instanceof AST_EmptyStatement) { + continue; + } else if (stat) { + return false; + } else { + stat = line; + } + } + return return_value(stat); + } + + function resolve_index(def) { + for (var i = fn.argnames.length; --i >= 0;) { + if (fn.argnames[i].definition() === def) return i; + } + } + + function can_substitute_directly() { + if (has_default || has_destructured || has_spread || var_assigned || fn.rest) return; + if (compressor.option("inline") < 2 && fn.argnames.length) return; + if (!fn.variables.all(function(def) { + return def.references.length - def.replaced < 2 && def.orig[0] instanceof AST_SymbolFunarg; + })) return; + var scope = compressor.find_parent(AST_Scope); + var abort = false; + var avoid = avoid_await_yield(compressor, scope); + var begin; + var in_order = []; + var side_effects = false; + var tw = new TreeWalker(function(node, descend) { + if (abort) return true; + if (node instanceof AST_Binary && lazy_op[node.operator] + || node instanceof AST_Conditional) { + in_order = null; + return; + } + if (node instanceof AST_Scope) return abort = true; + if (avoid && node instanceof AST_Symbol && avoid[node.name]) return abort = true; + if (node instanceof AST_SymbolRef) { + var def = node.definition(); + if (fn.variables.get(node.name) !== def) { + in_order = null; + return; + } + if (def.init instanceof AST_LambdaDefinition) return abort = true; + if (is_lhs(node, tw.parent())) return abort = true; + var index = resolve_index(def); + if (!(begin < index)) begin = index; + if (!in_order) return; + if (side_effects) { + in_order = null; + } else { + in_order.push(fn.argnames[index]); + } + return; + } + if (side_effects) return; + if (node instanceof AST_Assign && node.left instanceof AST_PropAccess) { + node.left.expression.walk(tw); + if (node.left instanceof AST_Sub) node.left.property.walk(tw); + node.right.walk(tw); + side_effects = true; + return true; + } + if (node.has_side_effects(compressor)) { + descend(); + side_effects = true; + return true; + } + }); + value.walk(tw); + if (abort) return; + var end = self.args.length; + if (in_order && fn.argnames.length >= end) { + end = fn.argnames.length; + while (end-- > begin && fn.argnames[end] === in_order.pop()); + end++; + } + return end <= begin || all(self.args.slice(begin, end), side_effects && !in_order ? function(funarg) { + return funarg.is_constant_expression(scope); + } : function(funarg) { + return !funarg.has_side_effects(compressor); + }); + } + + function var_exists(defined, name) { + return defined.has(name) || identifier_atom[name] || scope.var_names().has(name); + } + + function can_inject_args(defined, safe_to_inject) { + var abort = false; + fn.each_argname(function(arg) { + if (abort) return; + if (arg.unused) return; + if (!safe_to_inject || var_exists(defined, arg.name)) return abort = true; + arg_used.set(arg.name, true); + if (in_loop) in_loop.push(arg.definition()); + }); + return !abort; + } + + function can_inject_vars(defined, safe_to_inject) { + for (var i = 0; i < fn.body.length; i++) { + var stat = fn.body[i]; + if (stat instanceof AST_LambdaDefinition) { + var name = stat.name; + if (!safe_to_inject) return false; + if (arg_used.has(name.name)) return false; + if (var_exists(defined, name.name)) return false; + if (!all(stat.enclosed, function(def) { + return def.scope === scope || def.scope === stat || !defined.has(def.name); + })) return false; + if (in_loop) in_loop.push(name.definition()); + continue; + } + if (!(stat instanceof AST_Var)) continue; + if (!safe_to_inject) return false; + for (var j = stat.definitions.length; --j >= 0;) { + var name = stat.definitions[j].name; + if (var_exists(defined, name.name)) return false; + if (in_loop) in_loop.push(name.definition()); + } + } + return true; + } + + function can_inject_symbols() { + var defined = new Dictionary(); + var level = 0, child; + scope = current; + do { + if (scope.variables) scope.variables.each(function(def) { + defined.set(def.name, true); + }); + child = scope; + scope = compressor.parent(level++); + if (scope instanceof AST_ClassField) { + if (!scope.static) return false; + } else if (scope instanceof AST_DWLoop) { + in_loop = []; + } else if (scope instanceof AST_For) { + if (scope.init === child) continue; + in_loop = []; + } else if (scope instanceof AST_ForEnumeration) { + if (scope.init === child) continue; + if (scope.object === child) continue; + in_loop = []; + } + } while (!(scope instanceof AST_Scope)); + insert = scope.body.indexOf(child) + 1; + if (!insert) return false; + if (!safe_from_await_yield(fn, avoid_await_yield(compressor, scope))) return false; + var safe_to_inject = (exp !== fn || fn.parent_scope.resolve() === scope) && !scope.pinned(); + if (scope instanceof AST_Toplevel) { + if (compressor.toplevel.vars) { + defined.set("arguments", true); + } else { + safe_to_inject = false; + } + } + arg_used = new Dictionary(); + var inline = compressor.option("inline"); + if (!can_inject_args(defined, inline >= 2 && safe_to_inject)) return false; + if (!can_inject_vars(defined, inline >= 3 && safe_to_inject)) return false; + return !in_loop || in_loop.length == 0 || !is_reachable(fn, in_loop); + } + + function append_var(decls, expressions, name, value) { + var def = name.definition(); + if (!scope.var_names().has(name.name)) { + scope.var_names().set(name.name, true); + decls.push(make_node(AST_VarDef, name, { + name: name, + value: null, + })); + } + scope.variables.set(name.name, def); + scope.enclosed.push(def); + if (!value) return; + var sym = make_node(AST_SymbolRef, name); + def.assignments++; + def.references.push(sym); + expressions.push(make_node(AST_Assign, self, { + operator: "=", + left: sym, + right: value, + })); + } + + function flatten_args(decls, expressions) { + var len = fn.argnames.length; + for (var i = self.args.length; --i >= len;) { + expressions.push(self.args[i]); + } + var default_args = []; + for (i = len; --i >= 0;) { + var argname = fn.argnames[i]; + var name; + if (argname instanceof AST_DefaultValue) { + default_args.push(argname); + name = argname.name; + } else { + name = argname; + } + var value = self.args[i]; + if (name.unused || scope.var_names().has(name.name)) { + if (value) expressions.push(value); + } else { + var symbol = make_node(AST_SymbolVar, name); + var def = name.definition(); + def.orig.push(symbol); + def.eliminated++; + if (name.unused !== undefined) { + append_var(decls, expressions, symbol); + if (value) expressions.push(value); + } else { + if (!value && argname === name && (in_loop + || name.name == "arguments" && !is_arrow(fn) && is_arrow(scope))) { + value = make_node(AST_Undefined, self); + } + append_var(decls, expressions, symbol, value); + } + } + } + decls.reverse(); + expressions.reverse(); + for (i = default_args.length; --i >= 0;) { + var node = default_args[i]; + if (node.name.unused !== undefined) { + expressions.push(node.value); + } else { + var sym = make_node(AST_SymbolRef, node.name); + node.name.definition().references.push(sym); + expressions.push(make_node(AST_Assign, node, { + operator: "=", + left: sym, + right: node.value, + })); + } + } + } + + function flatten_destructured(decls, expressions) { + expressions.push(make_node(AST_Assign, self, { + operator: "=", + left: make_node(AST_DestructuredArray, self, { + elements: fn.argnames.map(function(argname) { + if (argname.unused) return make_node(AST_Hole, argname); + return argname.convert_symbol(AST_SymbolRef, process); + }), + rest: fn.rest && fn.rest.convert_symbol(AST_SymbolRef, process), + }), + right: make_node(AST_Array, self, { elements: self.args.slice() }), + })); + + function process(ref, name) { + if (name.unused) return make_void_lhs(name); + var def = name.definition(); + def.assignments++; + def.references.push(ref); + var symbol = make_node(AST_SymbolVar, name); + def.orig.push(symbol); + def.eliminated++; + append_var(decls, expressions, symbol); + } + } + + function flatten_vars(decls, expressions) { + var args = [ insert, 0 ]; + var decl_var = [], expr_fn = [], expr_var = [], expr_loop = [], exprs = []; + fn.body.filter(in_loop ? function(stat) { + if (!(stat instanceof AST_LambdaDefinition)) return true; + var name = make_node(AST_SymbolVar, flatten_var(stat.name)); + var def = name.definition(); + def.fixed = false; + def.orig.push(name); + def.eliminated++; + append_var(decls, expr_fn, name, to_func_expr(stat, true)); + return false; + } : function(stat) { + if (!(stat instanceof AST_LambdaDefinition)) return true; + var def = stat.name.definition(); + scope.functions.set(def.name, def); + scope.variables.set(def.name, def); + scope.enclosed.push(def); + scope.var_names().set(def.name, true); + args.push(stat); + return false; + }).forEach(function(stat) { + if (!(stat instanceof AST_Var)) { + if (stat instanceof AST_SimpleStatement) exprs.push(stat.body); + return; + } + for (var j = 0; j < stat.definitions.length; j++) { + var var_def = stat.definitions[j]; + var name = flatten_var(var_def.name); + var value = var_def.value; + if (value && exprs.length > 0) { + exprs.push(value); + value = make_sequence(var_def, exprs); + exprs = []; + } + append_var(decl_var, expr_var, name, value); + if (!in_loop) continue; + if (arg_used.has(name.name)) continue; + if (name.definition().orig.length == 1 && fn.functions.has(name.name)) continue; + expr_loop.push(init_ref(compressor, name)); + } + }); + [].push.apply(decls, decl_var); + [].push.apply(expressions, expr_loop); + [].push.apply(expressions, expr_fn); + [].push.apply(expressions, expr_var); + return args; + } + + function flatten_fn() { + var decls = []; + var expressions = []; + if (has_default > 1 || has_destructured || has_spread || fn.rest) { + flatten_destructured(decls, expressions); + } else { + flatten_args(decls, expressions); + } + var args = flatten_vars(decls, expressions); + expressions.push(value); + if (decls.length) args.push(make_node(AST_Var, fn, { definitions: decls })); + [].splice.apply(scope.body, args); + fn.enclosed.forEach(function(def) { + if (scope.var_names().has(def.name)) return; + scope.enclosed.push(def); + scope.var_names().set(def.name, true); + }); + return expressions; + } + }); + + OPT(AST_New, function(self, compressor) { + if (compressor.option("unsafe")) { + var exp = self.expression; + if (is_undeclared_ref(exp)) switch (exp.name) { + case "Array": + case "Error": + case "Function": + case "Object": + case "RegExp": + return make_node(AST_Call, self).transform(compressor); + } + } + if (compressor.option("sequences")) { + var seq = lift_sequence_in_expression(self, compressor); + if (seq !== self) return seq.optimize(compressor); + } + if (compressor.option("unused")) drop_unused_call_args(self, compressor); + return self; + }); + + // (a = b, x && a = c) ---> a = x ? c : b + // (a = b, x || a = c) ---> a = x ? b : c + function to_conditional_assignment(compressor, def, value, node) { + if (!(node instanceof AST_Binary)) return; + if (!(node.operator == "&&" || node.operator == "||")) return; + if (!(node.right instanceof AST_Assign)) return; + if (node.right.operator != "=") return; + if (!(node.right.left instanceof AST_SymbolRef)) return; + if (node.right.left.definition() !== def) return; + if (value.has_side_effects(compressor)) return; + if (!safe_from_assignment(node.left)) return; + if (!safe_from_assignment(node.right.right)) return; + def.replaced++; + return node.operator == "&&" ? make_node(AST_Conditional, node, { + condition: node.left, + consequent: node.right.right, + alternative: value, + }) : make_node(AST_Conditional, node, { + condition: node.left, + consequent: value, + alternative: node.right.right, + }); + + function safe_from_assignment(node) { + if (node.has_side_effects(compressor)) return; + var hit = false; + node.walk(new TreeWalker(function(node) { + if (hit) return true; + if (node instanceof AST_SymbolRef && node.definition() === def) return hit = true; + })); + return !hit; + } + } + + OPT(AST_Sequence, function(self, compressor) { + var expressions = filter_for_side_effects(); + var end = expressions.length - 1; + merge_assignments(); + trim_right_for_undefined(); + if (end == 0) { + self = maintain_this_binding(compressor.parent(), compressor.self(), expressions[0]); + if (!(self instanceof AST_Sequence)) self = self.optimize(compressor); + return self; + } + self.expressions = expressions; + return self; + + function filter_for_side_effects() { + if (!compressor.option("side_effects")) return self.expressions; + var expressions = []; + var first = first_in_statement(compressor); + var last = self.expressions.length - 1; + self.expressions.forEach(function(expr, index) { + if (index < last) expr = expr.drop_side_effect_free(compressor, first); + if (expr) { + merge_sequence(expressions, expr); + first = false; + } + }); + return expressions; + } + + function trim_right_for_undefined() { + if (!compressor.option("side_effects")) return; + while (end > 0 && is_undefined(expressions[end], compressor)) end--; + if (end < expressions.length - 1) { + expressions[end] = make_node(AST_UnaryPrefix, self, { + operator: "void", + expression: expressions[end], + }); + expressions.length = end + 1; + } + } + + function is_simple_assign(node) { + return node instanceof AST_Assign + && node.operator == "=" + && node.left instanceof AST_SymbolRef + && node.left.definition(); + } + + function merge_assignments() { + for (var i = 1; i < end; i++) { + var prev = expressions[i - 1]; + var def = is_simple_assign(prev); + if (!def) continue; + var expr = expressions[i]; + if (compressor.option("conditionals")) { + var cond = to_conditional_assignment(compressor, def, prev.right, expr); + if (cond) { + prev.right = cond; + expressions.splice(i--, 1); + end--; + continue; + } + } + if (compressor.option("dead_code") + && is_simple_assign(expr) === def + && expr.right.is_constant_expression(def.scope.resolve())) { + expressions[--i] = prev.right; + } + } + } + }); + + OPT(AST_UnaryPostfix, function(self, compressor) { + if (compressor.option("sequences")) { + var seq = lift_sequence_in_expression(self, compressor); + if (seq !== self) return seq.optimize(compressor); + } + return try_evaluate(compressor, self); + }); + + var SIGN_OPS = makePredicate("+ -"); + var MULTIPLICATIVE_OPS = makePredicate("* / %"); + OPT(AST_UnaryPrefix, function(self, compressor) { + var op = self.operator; + var exp = self.expression; + if (compressor.option("sequences") && can_lift()) { + var seq = lift_sequence_in_expression(self, compressor); + if (seq !== self) return seq.optimize(compressor); + } + switch (op) { + case "+": + if (!compressor.option("evaluate")) break; + if (!exp.is_number(compressor, true)) break; + var parent = compressor.parent(); + if (parent instanceof AST_UnaryPrefix && parent.operator == "delete") break; + return exp; + case "-": + if (exp instanceof AST_Infinity) exp = exp.transform(compressor); + // avoids infinite recursion of numerals + if (exp instanceof AST_Number || exp instanceof AST_Infinity) return self; + break; + case "!": + if (!compressor.option("booleans")) break; + if (exp.is_truthy()) return make_sequence(self, [ exp, make_node(AST_False, self) ]).optimize(compressor); + if (compressor.in_boolean_context()) { + // !!foo ---> foo, if we're in boolean context + if (exp instanceof AST_UnaryPrefix && exp.operator == "!") return exp.expression; + if (exp instanceof AST_Binary) { + var first = first_in_statement(compressor); + self = (first ? best_of_statement : best_of_expression)(self, exp.negate(compressor, first)); + } + } + break; + case "delete": + if (!compressor.option("evaluate")) break; + if (may_not_delete(exp)) break; + return make_sequence(self, [ exp, make_node(AST_True, self) ]).optimize(compressor); + case "typeof": + if (!compressor.option("booleans")) break; + if (!compressor.in_boolean_context()) break; + // typeof always returns a non-empty string, thus always truthy + AST_Node.warn("Boolean expression always true [{start}]", self); + var exprs = [ make_node(AST_True, self) ]; + if (!(exp instanceof AST_SymbolRef && can_drop_symbol(exp, compressor))) exprs.unshift(exp); + return make_sequence(self, exprs).optimize(compressor); + case "void": + if (!compressor.option("side_effects")) break; + exp = exp.drop_side_effect_free(compressor); + if (!exp) return make_node(AST_Undefined, self).optimize(compressor); + self.expression = exp; + return self; + } + if (compressor.option("evaluate") + && exp instanceof AST_Binary + && SIGN_OPS[op] + && MULTIPLICATIVE_OPS[exp.operator] + && (exp.left.is_constant() || !exp.right.has_side_effects(compressor))) { + return make_node(AST_Binary, self, { + operator: exp.operator, + left: make_node(AST_UnaryPrefix, exp.left, { + operator: op, + expression: exp.left, + }), + right: exp.right, + }); + } + return try_evaluate(compressor, self); + + function may_not_delete(node) { + return node instanceof AST_Infinity + || node instanceof AST_NaN + || node instanceof AST_NewTarget + || node instanceof AST_PropAccess + || node instanceof AST_SymbolRef + || node instanceof AST_Undefined; + } + + function can_lift() { + switch (op) { + case "delete": + return !may_not_delete(exp.tail_node()); + case "typeof": + return !is_undeclared_ref(exp.tail_node()); + default: + return true; + } + } + }); + + OPT(AST_Await, function(self, compressor) { + if (!compressor.option("awaits")) return self; + if (compressor.option("sequences")) { + var seq = lift_sequence_in_expression(self, compressor); + if (seq !== self) return seq.optimize(compressor); + } + if (compressor.option("side_effects")) { + var exp = self.expression; + if (exp instanceof AST_Await) return exp.optimize(compressor); + if (exp instanceof AST_UnaryPrefix && exp.expression instanceof AST_Await) return exp.optimize(compressor); + for (var level = 0, node = self, parent; parent = compressor.parent(level++); node = parent) { + if (is_arrow(parent)) { + if (parent.value === node) return exp.optimize(compressor); + } else if (parent instanceof AST_Return) { + var drop = true; + do { + node = parent; + parent = compressor.parent(level++); + if (parent instanceof AST_Try && (parent.bfinally || parent.bcatch) !== node) { + drop = false; + break; + } + } while (parent && !(parent instanceof AST_Scope)); + if (drop) return exp.optimize(compressor); + } else if (parent instanceof AST_Sequence) { + if (parent.tail_node() === node) continue; + } + break; + } + } + return self; + }); + + OPT(AST_Yield, function(self, compressor) { + if (!compressor.option("yields")) return self; + if (compressor.option("sequences")) { + var seq = lift_sequence_in_expression(self, compressor); + if (seq !== self) return seq.optimize(compressor); + } + var exp = self.expression; + if (self.nested && exp.TYPE == "Call") { + var inlined = exp.clone().optimize(compressor); + if (inlined.TYPE != "Call") return inlined; + } + return self; + }); + + AST_Binary.DEFMETHOD("lift_sequences", function(compressor) { + if (this.left instanceof AST_PropAccess) { + if (!(this.left.expression instanceof AST_Sequence)) return this; + var x = this.left.expression.expressions.slice(); + var e = this.clone(); + e.left = e.left.clone(); + e.left.expression = x.pop(); + x.push(e); + return make_sequence(this, x); + } + if (this.left instanceof AST_Sequence) { + var x = this.left.expressions.slice(); + var e = this.clone(); + e.left = x.pop(); + x.push(e); + return make_sequence(this, x); + } + if (this.right instanceof AST_Sequence) { + if (this.left.has_side_effects(compressor)) return this; + var assign = this.operator == "=" && this.left instanceof AST_SymbolRef; + var x = this.right.expressions; + var last = x.length - 1; + for (var i = 0; i < last; i++) { + if (!assign && x[i].has_side_effects(compressor)) break; + } + if (i == last) { + x = x.slice(); + var e = this.clone(); + e.right = x.pop(); + x.push(e); + return make_sequence(this, x); + } + if (i > 0) { + var e = this.clone(); + e.right = make_sequence(this.right, x.slice(i)); + x = x.slice(0, i); + x.push(e); + return make_sequence(this, x); + } + } + return this; + }); + + var indexFns = makePredicate("indexOf lastIndexOf"); + var commutativeOperators = makePredicate("== === != !== * & | ^"); + function is_object(node, plain) { + if (node instanceof AST_Assign) return !plain && node.operator == "=" && is_object(node.right); + if (node instanceof AST_New) return !plain; + if (node instanceof AST_Sequence) return is_object(node.tail_node(), plain); + if (node instanceof AST_SymbolRef) return !plain && is_object(node.fixed_value()); + return node instanceof AST_Array + || node instanceof AST_Class + || node instanceof AST_Lambda + || node instanceof AST_Object; + } + + function can_drop_op(op, rhs, compressor) { + switch (op) { + case "in": + return is_object(rhs) || compressor && compressor.option("unsafe_comps"); + case "instanceof": + if (rhs instanceof AST_SymbolRef) rhs = rhs.fixed_value(); + return is_lambda(rhs) || compressor && compressor.option("unsafe_comps"); + default: + return true; + } + } + + function needs_enqueuing(compressor, node) { + if (node.is_constant()) return true; + if (node instanceof AST_Assign) return node.operator != "=" || needs_enqueuing(compressor, node.right); + if (node instanceof AST_Binary) { + return !lazy_op[node.operator] + || needs_enqueuing(compressor, node.left) && needs_enqueuing(compressor, node.right); + } + if (node instanceof AST_Call) return is_async(node.expression); + if (node instanceof AST_Conditional) { + return needs_enqueuing(compressor, node.consequent) && needs_enqueuing(compressor, node.alternative); + } + if (node instanceof AST_Sequence) return needs_enqueuing(compressor, node.tail_node()); + if (node instanceof AST_SymbolRef) { + var fixed = node.fixed_value(); + return fixed && needs_enqueuing(compressor, fixed); + } + if (node instanceof AST_Template) return !node.tag || is_raw_tag(compressor, node.tag); + if (node instanceof AST_Unary) return true; + } + + function extract_lhs(node, compressor) { + if (node instanceof AST_Assign) return is_lhs_read_only(node.left, compressor) ? node : node.left; + if (node instanceof AST_Sequence) return extract_lhs(node.tail_node(), compressor); + if (node instanceof AST_UnaryPrefix && UNARY_POSTFIX[node.operator]) { + return is_lhs_read_only(node.expression, compressor) ? node : node.expression; + } + return node; + } + + function repeatable(compressor, node) { + if (node instanceof AST_Dot) return repeatable(compressor, node.expression); + if (node instanceof AST_Sub) { + return repeatable(compressor, node.expression) && repeatable(compressor, node.property); + } + if (node instanceof AST_Symbol) return true; + return !node.has_side_effects(compressor); + } + + function swap_chain(self, compressor) { + var rhs = self.right.tail_node(); + if (rhs !== self.right) { + var exprs = self.right.expressions.slice(0, -1); + exprs.push(rhs.left); + rhs = rhs.clone(); + rhs.left = make_sequence(self.right, exprs); + self.right = rhs; + } + self.left = make_node(AST_Binary, self, { + operator: self.operator, + left: self.left, + right: rhs.left, + start: self.left.start, + end: rhs.left.end, + }); + self.right = rhs.right; + if (compressor) { + self.left = self.left.transform(compressor); + } else if (self.operator == rhs.left.operator) { + swap_chain(self.left); + } + } + + OPT(AST_Binary, function(self, compressor) { + if (commutativeOperators[self.operator] + && self.right.is_constant() + && !self.left.is_constant() + && !(self.left instanceof AST_Binary + && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { + // if right is a constant, whatever side effects the + // left side might have could not influence the + // result. hence, force switch. + reverse(); + } + if (compressor.option("sequences")) { + var seq = self.lift_sequences(compressor); + if (seq !== self) return seq.optimize(compressor); + } + if (compressor.option("assignments") && lazy_op[self.operator]) { + var lhs = extract_lhs(self.left, compressor); + var right = self.right; + // a || (a = x) ---> a = a || x + // (a = x) && (a = y) ---> a = (a = x) && y + if (lhs instanceof AST_SymbolRef + && right instanceof AST_Assign + && right.operator == "=" + && lhs.equals(right.left)) { + lhs = lhs.clone(); + var assign = make_node(AST_Assign, self, { + operator: "=", + left: lhs, + right: make_node(AST_Binary, self, { + operator: self.operator, + left: self.left, + right: right.right, + }), + }); + if (lhs.fixed) { + lhs.fixed = function() { + return assign.right; + }; + lhs.fixed.assigns = [ assign ]; + } + var def = lhs.definition(); + def.references.push(lhs); + def.replaced++; + return assign.optimize(compressor); + } + } + if (compressor.option("comparisons")) switch (self.operator) { + case "===": + case "!==": + if (is_undefined(self.left, compressor) && self.right.is_defined(compressor)) { + AST_Node.warn("Expression always defined [{start}]", self); + return make_sequence(self, [ + self.right, + make_node(self.operator == "===" ? AST_False : AST_True, self), + ]).optimize(compressor); + } + var is_strict_comparison = true; + if ((self.left.is_string(compressor) && self.right.is_string(compressor)) || + (self.left.is_number(compressor) && self.right.is_number(compressor)) || + (self.left.is_boolean(compressor) && self.right.is_boolean(compressor)) || + repeatable(compressor, self.left) && self.left.equals(self.right)) { + self.operator = self.operator.slice(0, 2); + } + // XXX: intentionally falling down to the next case + case "==": + case "!=": + // void 0 == x ---> null == x + if (!is_strict_comparison && is_undefined(self.left, compressor)) { + self.left = make_node(AST_Null, self.left); + } + // "undefined" == typeof x ---> undefined === x + else if (compressor.option("typeofs") + && self.left instanceof AST_String + && self.left.value == "undefined" + && self.right instanceof AST_UnaryPrefix + && self.right.operator == "typeof") { + var expr = self.right.expression; + if (expr instanceof AST_SymbolRef ? expr.is_declared(compressor) + : !(expr instanceof AST_PropAccess && compressor.option("ie"))) { + self.right = expr; + self.left = make_node(AST_Undefined, self.left).optimize(compressor); + if (self.operator.length == 2) self.operator += "="; + } + } + // obj !== obj ---> false + else if (self.left instanceof AST_SymbolRef + && self.right instanceof AST_SymbolRef + && self.left.definition() === self.right.definition() + && is_object(self.left)) { + return make_node(self.operator[0] == "=" ? AST_True : AST_False, self).optimize(compressor); + } + break; + case "&&": + case "||": + // void 0 !== x && null !== x ---> null != x + // void 0 === x || null === x ---> null == x + var left = self.left; + if (!(left instanceof AST_Binary)) break; + if (left.operator != (self.operator == "&&" ? "!==" : "===")) break; + if (!(self.right instanceof AST_Binary)) break; + if (left.operator != self.right.operator) break; + if (is_undefined(left.left, compressor) && self.right.left instanceof AST_Null + || left.left instanceof AST_Null && is_undefined(self.right.left, compressor)) { + var expr = left.right; + if (expr instanceof AST_Assign && expr.operator == "=") expr = expr.left; + if (expr.has_side_effects(compressor)) break; + if (!expr.equals(self.right.right)) break; + left.operator = left.operator.slice(0, -1); + left.left = make_node(AST_Null, self); + return left; + } + break; + } + var in_bool = false; + var parent = compressor.parent(); + if (compressor.option("booleans")) { + var lhs = extract_lhs(self.left, compressor); + if (lazy_op[self.operator] && !lhs.has_side_effects(compressor)) { + // a || a ---> a + // (a = x) && a --> a = x + if (lhs.equals(self.right)) { + return maintain_this_binding(parent, compressor.self(), self.left).optimize(compressor); + } + mark_duplicate_condition(compressor, lhs); + } + in_bool = compressor.in_boolean_context(); + } + if (in_bool) switch (self.operator) { + case "+": + var ev = self.left.evaluate(compressor, true); + if (ev && typeof ev == "string" || (ev = self.right.evaluate(compressor, true)) && typeof ev == "string") { + AST_Node.warn("+ in boolean context always true [{start}]", self); + var exprs = []; + if (self.left.evaluate(compressor) instanceof AST_Node) exprs.push(self.left); + if (self.right.evaluate(compressor) instanceof AST_Node) exprs.push(self.right); + if (exprs.length < 2) { + exprs.push(make_node(AST_True, self)); + return make_sequence(self, exprs).optimize(compressor); + } + self.truthy = true; + } + break; + case "==": + if (self.left instanceof AST_String && self.left.value == "" && self.right.is_string(compressor)) { + return make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: self.right, + }).optimize(compressor); + } + break; + case "!=": + if (self.left instanceof AST_String && self.left.value == "" && self.right.is_string(compressor)) { + return self.right.optimize(compressor); + } + break; + } + if (compressor.option("comparisons") && self.is_boolean(compressor)) { + if (parent.TYPE != "Binary") { + var negated = make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: self.negate(compressor), + }); + if (best_of(compressor, self, negated) === negated) return negated; + } + switch (self.operator) { + case ">": reverse("<"); break; + case ">=": reverse("<="); break; + } + } + if (compressor.option("conditionals") && lazy_op[self.operator]) { + if (self.left instanceof AST_Binary && self.operator == self.left.operator) { + var before = make_node(AST_Binary, self, { + operator: self.operator, + left: self.left.right, + right: self.right, + }); + var after = before.transform(compressor); + if (before !== after) { + self.left = self.left.left; + self.right = after; + } + } + // x && (y && z) ---> x && y && z + // w || (x, y || z) ---> w || (x, y) || z + var rhs = self.right.tail_node(); + if (rhs instanceof AST_Binary && self.operator == rhs.operator) swap_chain(self, compressor); + } + if (compressor.option("strings") && self.operator == "+") { + // "foo" + 42 + "" ---> "foo" + 42 + if (self.right instanceof AST_String + && self.right.value == "" + && self.left.is_string(compressor)) { + return self.left.optimize(compressor); + } + // "" + ("foo" + 42) ---> "foo" + 42 + if (self.left instanceof AST_String + && self.left.value == "" + && self.right.is_string(compressor)) { + return self.right.optimize(compressor); + } + // "" + 42 + "foo" ---> 42 + "foo" + if (self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.left instanceof AST_String + && self.left.left.value == "" + && self.right.is_string(compressor) + && (self.left.right.is_constant() || !self.right.has_side_effects(compressor))) { + self.left = self.left.right; + return self.optimize(compressor); + } + // "x" + (y + "z") ---> "x" + y + "z" + // w + (x, "y" + z) ---> w + (x, "y") + z + var rhs = self.right.tail_node(); + if (rhs instanceof AST_Binary + && self.operator == rhs.operator + && (self.left.is_string(compressor) && rhs.is_string(compressor) + || rhs.left.is_string(compressor) + && (self.left.is_constant() || !rhs.right.has_side_effects(compressor)))) { + swap_chain(self, compressor); + } + } + if (compressor.option("evaluate")) { + var associative = true; + switch (self.operator) { + case "&&": + var ll = fuzzy_eval(compressor, self.left); + if (!ll) { + AST_Node.warn("Condition left of && always false [{start}]", self); + return maintain_this_binding(parent, compressor.self(), self.left).optimize(compressor); + } else if (!(ll instanceof AST_Node)) { + AST_Node.warn("Condition left of && always true [{start}]", self); + return make_sequence(self, [ self.left, self.right ]).optimize(compressor); + } + if (!self.right.evaluate(compressor, true)) { + if (in_bool && !(self.right.evaluate(compressor) instanceof AST_Node)) { + AST_Node.warn("Boolean && always false [{start}]", self); + return make_sequence(self, [ self.left, make_node(AST_False, self) ]).optimize(compressor); + } else self.falsy = true; + } else if ((in_bool || parent.operator == "&&" && parent.left === compressor.self()) + && !(self.right.evaluate(compressor) instanceof AST_Node)) { + AST_Node.warn("Dropping side-effect-free && [{start}]", self); + return self.left.optimize(compressor); + } + // (x || false) && y ---> x ? y : false + if (self.left.operator == "||") { + var lr = fuzzy_eval(compressor, self.left.right); + if (!lr) return make_node(AST_Conditional, self, { + condition: self.left.left, + consequent: self.right, + alternative: self.left.right, + }).optimize(compressor); + } + break; + case "??": + var nullish = true; + case "||": + var ll = fuzzy_eval(compressor, self.left, nullish); + if (nullish ? ll == null : !ll) { + AST_Node.warn("Condition left of {operator} always {value} [{start}]", { + operator: self.operator, + value: nullish ? "nullish" : "false", + start: self.start, + }); + return make_sequence(self, [ self.left, self.right ]).optimize(compressor); + } else if (!(ll instanceof AST_Node)) { + AST_Node.warn("Condition left of {operator} always {value} [{start}]", { + operator: self.operator, + value: nullish ? "defined" : "true", + start: self.start, + }); + return maintain_this_binding(parent, compressor.self(), self.left).optimize(compressor); + } + var rr; + if (!nullish && (rr = self.right.evaluate(compressor, true)) && !(rr instanceof AST_Node)) { + if (in_bool && !(self.right.evaluate(compressor) instanceof AST_Node)) { + AST_Node.warn("Boolean || always true [{start}]", self); + return make_sequence(self, [ self.left, make_node(AST_True, self) ]).optimize(compressor); + } else self.truthy = true; + } else if ((in_bool || parent.operator == "||" && parent.left === compressor.self()) + && !self.right.evaluate(compressor)) { + AST_Node.warn("Dropping side-effect-free {operator} [{start}]", self); + return self.left.optimize(compressor); + } + // x && true || y ---> x ? true : y + if (!nullish && self.left.operator == "&&") { + var lr = fuzzy_eval(compressor, self.left.right); + if (lr && !(lr instanceof AST_Node)) return make_node(AST_Conditional, self, { + condition: self.left.left, + consequent: self.left.right, + alternative: self.right, + }).optimize(compressor); + } + break; + case "+": + // "foo" + ("bar" + x) ---> "foobar" + x + if (self.left instanceof AST_Constant + && self.right instanceof AST_Binary + && self.right.operator == "+" + && self.right.left instanceof AST_Constant + && self.right.is_string(compressor)) { + self = make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_String, self.left, { + value: "" + self.left.value + self.right.left.value, + start: self.left.start, + end: self.right.left.end, + }), + right: self.right.right, + }); + } + // (x + "foo") + "bar" ---> x + "foobar" + if (self.right instanceof AST_Constant + && self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.right instanceof AST_Constant + && self.left.is_string(compressor)) { + self = make_node(AST_Binary, self, { + operator: "+", + left: self.left.left, + right: make_node(AST_String, self.right, { + value: "" + self.left.right.value + self.right.value, + start: self.left.right.start, + end: self.right.end, + }), + }); + } + // a + -b ---> a - b + if (self.right instanceof AST_UnaryPrefix + && self.right.operator == "-" + && self.left.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "-", + left: self.left, + right: self.right.expression, + }); + break; + } + // -a + b ---> b - a + if (self.left instanceof AST_UnaryPrefix + && self.left.operator == "-" + && reversible() + && self.right.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "-", + left: self.right, + right: self.left.expression, + }); + break; + } + // (a + b) + 3 ---> 3 + (a + b) + if (compressor.option("unsafe_math") + && self.left instanceof AST_Binary + && PRECEDENCE[self.left.operator] == PRECEDENCE[self.operator] + && self.right.is_constant() + && (self.right.is_boolean(compressor) || self.right.is_number(compressor)) + && self.left.is_number(compressor) + && !self.left.right.is_constant() + && (self.left.left.is_boolean(compressor) || self.left.left.is_number(compressor))) { + self = make_node(AST_Binary, self, { + operator: self.left.operator, + left: make_node(AST_Binary, self, { + operator: self.operator, + left: self.right, + right: self.left.left, + }), + right: self.left.right, + }); + break; + } + case "-": + // a - -b ---> a + b + if (self.right instanceof AST_UnaryPrefix + && self.right.operator == "-" + && self.left.is_number(compressor) + && self.right.expression.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "+", + left: self.left, + right: self.right.expression, + }); + break; + } + case "*": + case "/": + associative = compressor.option("unsafe_math"); + // +a - b ---> a - b + // a - +b ---> a - b + if (self.operator != "+") [ "left", "right" ].forEach(function(operand) { + var node = self[operand]; + if (node instanceof AST_UnaryPrefix && node.operator == "+") { + var exp = node.expression; + if (exp.is_boolean(compressor) || exp.is_number(compressor) || exp.is_string(compressor)) { + self[operand] = exp; + } + } + }); + case "&": + case "|": + case "^": + // a + +b ---> +b + a + if (self.operator != "-" + && self.operator != "/" + && (self.left.is_boolean(compressor) || self.left.is_number(compressor)) + && (self.right.is_boolean(compressor) || self.right.is_number(compressor)) + && reversible() + && !(self.left instanceof AST_Binary + && self.left.operator != self.operator + && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { + self = best_of(compressor, self, make_node(AST_Binary, self, { + operator: self.operator, + left: self.right, + right: self.left, + }), self.right instanceof AST_Constant && !(self.left instanceof AST_Constant)); + } + if (!associative || !self.is_number(compressor)) break; + // a + (b + c) ---> (a + b) + c + if (self.right instanceof AST_Binary + && self.right.operator != "%" + && PRECEDENCE[self.right.operator] == PRECEDENCE[self.operator] + && self.right.is_number(compressor) + && (self.operator != "+" + || self.right.left.is_boolean(compressor) + || self.right.left.is_number(compressor)) + && (self.operator != "-" || !self.left.is_negative_zero()) + && (self.right.left.is_constant_expression() + || !self.right.right.has_side_effects(compressor)) + && !is_modify_array(self.right.right)) { + self = make_node(AST_Binary, self, { + operator: align(self.operator, self.right.operator), + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left, + right: self.right.left, + start: self.left.start, + end: self.right.left.end, + }), + right: self.right.right, + }); + if (self.operator == "+" + && !self.right.is_boolean(compressor) + && !self.right.is_number(compressor)) { + self.right = make_node(AST_UnaryPrefix, self.right, { + operator: "+", + expression: self.right, + }); + } + } + // (2 * n) * 3 ---> 6 * n + // (n + 2) + 3 ---> n + 5 + if (self.right instanceof AST_Constant + && self.left instanceof AST_Binary + && self.left.operator != "%" + && PRECEDENCE[self.left.operator] == PRECEDENCE[self.operator] + && self.left.is_number(compressor)) { + if (self.left.left instanceof AST_Constant) { + var lhs = make_binary(self.operator, self.left.left, self.right, { + start: self.left.left.start, + end: self.right.end, + }); + self = make_binary(self.left.operator, try_evaluate(compressor, lhs), self.left.right, self); + } else if (self.left.right instanceof AST_Constant) { + var op = align(self.left.operator, self.operator); + var rhs = try_evaluate(compressor, make_binary(op, self.left.right, self.right, self.left)); + if (rhs.is_constant() + && !(self.left.operator == "-" + && self.right.value != 0 + && +rhs.value == 0 + && self.left.left.is_negative_zero())) { + self = make_binary(self.left.operator, self.left.left, rhs, self); + } + } + } + break; + case "instanceof": + if (is_lambda(self.right)) return make_sequence(self, [ + self, + make_node(AST_False, self), + ]).optimize(compressor); + break; + } + if (!(parent instanceof AST_UnaryPrefix && parent.operator == "delete")) { + if (self.left instanceof AST_Number && !self.right.is_constant()) switch (self.operator) { + // 0 + n ---> n + case "+": + if (self.left.value == 0) { + if (self.right.is_boolean(compressor)) return make_node(AST_UnaryPrefix, self, { + operator: "+", + expression: self.right, + }).optimize(compressor); + if (self.right.is_number(compressor) && !self.right.is_negative_zero()) return self.right; + } + break; + // 1 * n ---> n + case "*": + if (self.left.value == 1) return make_node(AST_UnaryPrefix, self, { + operator: "+", + expression: self.right, + }).optimize(compressor); + break; + } + if (self.right instanceof AST_Number && !self.left.is_constant()) switch (self.operator) { + // n + 0 ---> n + case "+": + if (self.right.value == 0) { + if (self.left.is_boolean(compressor)) return make_node(AST_UnaryPrefix, self, { + operator: "+", + expression: self.left, + }).optimize(compressor); + if (self.left.is_number(compressor) && !self.left.is_negative_zero()) return self.left; + } + break; + // n - 0 ---> n + case "-": + if (self.right.value == 0) return make_node(AST_UnaryPrefix, self, { + operator: "+", + expression: self.left, + }).optimize(compressor); + break; + // n / 1 ---> n + case "/": + if (self.right.value == 1) return make_node(AST_UnaryPrefix, self, { + operator: "+", + expression: self.left, + }).optimize(compressor); + break; + } + } + } + if (compressor.option("typeofs")) switch (self.operator) { + case "&&": + mark_locally_defined(self.left, self.right, null); + break; + case "||": + mark_locally_defined(self.left, null, self.right); + break; + } + if (compressor.option("unsafe")) { + var indexRight = is_indexFn(self.right); + if (in_bool + && indexRight + && (self.operator == "==" || self.operator == "!=") + && self.left instanceof AST_Number + && self.left.value == 0) { + return (self.operator == "==" ? make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: self.right, + }) : self.right).optimize(compressor); + } + var indexLeft = is_indexFn(self.left); + if (compressor.option("comparisons") && is_indexOf_match_pattern()) { + var node = make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: make_node(AST_UnaryPrefix, self, { + operator: "~", + expression: indexLeft ? self.left : self.right, + }), + }); + switch (self.operator) { + case "<": + if (indexLeft) break; + case "<=": + case "!=": + node = make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: node, + }); + break; + } + return node.optimize(compressor); + } + } + return try_evaluate(compressor, self); + + function is_modify_array(node) { + var found = false; + node.walk(new TreeWalker(function(node) { + if (found) return true; + if (node instanceof AST_Assign) { + if (node.left instanceof AST_PropAccess) return found = true; + } else if (node instanceof AST_Unary) { + if (unary_side_effects[node.operator] && node.expression instanceof AST_PropAccess) { + return found = true; + } + } + })); + return found; + } + + function align(ref, op) { + switch (ref) { + case "-": + return op == "+" ? "-" : "+"; + case "/": + return op == "*" ? "/" : "*"; + default: + return op; + } + } + + function make_binary(op, left, right, orig) { + if (op == "+") { + if (!left.is_boolean(compressor) && !left.is_number(compressor)) { + left = make_node(AST_UnaryPrefix, left, { + operator: "+", + expression: left, + }); + } + if (!right.is_boolean(compressor) && !right.is_number(compressor)) { + right = make_node(AST_UnaryPrefix, right, { + operator: "+", + expression: right, + }); + } + } + return make_node(AST_Binary, orig, { + operator: op, + left: left, + right: right, + }); + } + + function is_indexFn(node) { + return node.TYPE == "Call" + && node.expression instanceof AST_Dot + && indexFns[node.expression.property]; + } + + function is_indexOf_match_pattern() { + switch (self.operator) { + case "<=": + // 0 <= array.indexOf(string) ---> !!~array.indexOf(string) + return indexRight && self.left instanceof AST_Number && self.left.value == 0; + case "<": + // array.indexOf(string) < 0 ---> !~array.indexOf(string) + if (indexLeft && self.right instanceof AST_Number && self.right.value == 0) return true; + // -1 < array.indexOf(string) ---> !!~array.indexOf(string) + case "==": + case "!=": + // -1 == array.indexOf(string) ---> !~array.indexOf(string) + // -1 != array.indexOf(string) ---> !!~array.indexOf(string) + if (!indexRight) return false; + return self.left instanceof AST_Number && self.left.value == -1 + || self.left instanceof AST_UnaryPrefix && self.left.operator == "-" + && self.left.expression instanceof AST_Number && self.left.expression.value == 1; + } + } + + function reversible() { + return self.left.is_constant() + || self.right.is_constant() + || !self.left.has_side_effects(compressor) + && !self.right.has_side_effects(compressor); + } + + function reverse(op) { + if (reversible()) { + if (op) self.operator = op; + var tmp = self.left; + self.left = self.right; + self.right = tmp; + } + } + }); + + OPT(AST_SymbolExport, function(self) { + return self; + }); + + function recursive_ref(compressor, def, fn) { + var level = 0, node = compressor.self(); + do { + if (node === fn) return node; + if (is_lambda(node) && node.name && node.name.definition() === def) return node; + } while (node = compressor.parent(level++)); + } + + function same_scope(def) { + var scope = def.scope.resolve(); + return all(def.references, function(ref) { + return scope === ref.scope.resolve(); + }); + } + + OPT(AST_SymbolRef, function(self, compressor) { + if (!compressor.option("ie") + && is_undeclared_ref(self) + // testing against `self.scope.uses_with` is an optimization + && !(self.scope.resolve().uses_with && compressor.find_parent(AST_With))) { + switch (self.name) { + case "undefined": + return make_node(AST_Undefined, self).optimize(compressor); + case "NaN": + return make_node(AST_NaN, self).optimize(compressor); + case "Infinity": + return make_node(AST_Infinity, self).optimize(compressor); + } + } + var parent = compressor.parent(); + if (compressor.option("reduce_vars") && is_lhs(compressor.self(), parent) !== compressor.self()) { + var def = self.definition(); + var fixed = self.fixed_value(); + var single_use = def.single_use && !(parent instanceof AST_Call && parent.is_expr_pure(compressor)); + if (single_use) { + if (is_lambda(fixed)) { + if ((def.scope !== self.scope.resolve(true) || def.in_loop) + && (!compressor.option("reduce_funcs") || def.escaped.depth == 1 || fixed.inlined)) { + single_use = false; + } else if (def.redefined()) { + single_use = false; + } else if (recursive_ref(compressor, def, fixed)) { + single_use = false; + } else if (fixed.name && fixed.name.definition() !== def) { + single_use = false; + } else if (fixed.parent_scope !== self.scope || is_funarg(def)) { + if (!safe_from_strict_mode(fixed, compressor)) { + single_use = false; + } else if ((single_use = fixed.is_constant_expression(self.scope)) == "f") { + var scope = self.scope; + do { + if (scope instanceof AST_LambdaDefinition || scope instanceof AST_LambdaExpression) { + scope.inlined = true; + } + } while (scope = scope.parent_scope); + } + } else if (fixed.name && (fixed.name.name == "await" && is_async(fixed) + || fixed.name.name == "yield" && is_generator(fixed))) { + single_use = false; + } else if (fixed.has_side_effects(compressor)) { + single_use = false; + } else if (compressor.option("ie") && fixed instanceof AST_Class) { + single_use = false; + } + if (single_use) fixed.parent_scope = self.scope; + } else if (!fixed + || def.recursive_refs > 0 + || !fixed.is_constant_expression() + || fixed.drop_side_effect_free(compressor)) { + single_use = false; + } + } + if (single_use) { + def.single_use = false; + fixed._squeezed = true; + fixed.single_use = true; + if (fixed instanceof AST_DefClass) fixed = to_class_expr(fixed); + if (fixed instanceof AST_LambdaDefinition) fixed = to_func_expr(fixed); + if (is_lambda(fixed)) { + var scopes = []; + var scope = self.scope; + do { + scopes.push(scope); + if (scope === def.scope) break; + } while (scope = scope.parent_scope); + fixed.enclosed.forEach(function(def) { + if (fixed.variables.has(def.name)) return; + for (var i = 0; i < scopes.length; i++) { + var scope = scopes[i]; + if (!push_uniq(scope.enclosed, def)) return; + scope.var_names().set(def.name, true); + } + }); + } + var value; + if (def.recursive_refs > 0) { + value = fixed.clone(true); + var defun_def = value.name.definition(); + var lambda_def = value.variables.get(value.name.name); + var name = lambda_def && lambda_def.orig[0]; + var def_fn_name, symbol_type; + if (value instanceof AST_Class) { + def_fn_name = "def_function"; + symbol_type = AST_SymbolClass; + } else { + def_fn_name = "def_variable"; + symbol_type = AST_SymbolLambda; + } + if (!(name instanceof symbol_type)) { + name = make_node(symbol_type, value.name); + name.scope = value; + value.name = name; + lambda_def = value[def_fn_name](name); + lambda_def.recursive_refs = def.recursive_refs; + } + value.walk(new TreeWalker(function(node) { + if (node instanceof AST_SymbolDeclaration) { + if (node !== name) { + var def = node.definition(); + def.orig.push(node); + def.eliminated++; + } + return; + } + if (!(node instanceof AST_SymbolRef)) return; + var def = node.definition(); + if (def === defun_def) { + node.thedef = def = lambda_def; + } else { + def.single_use = false; + var fn = node.fixed_value(); + if (is_lambda(fn) + && fn.name + && fn.name.definition() === def + && def.scope === fn.name.scope + && fixed.variables.get(fn.name.name) === def) { + fn.name = fn.name.clone(); + node.thedef = def = value.variables.get(fn.name.name) || value[def_fn_name](fn.name); + } + } + def.references.push(node); + })); + } else { + if (fixed instanceof AST_Scope) { + compressor.push(fixed); + value = fixed.optimize(compressor); + compressor.pop(); + } else { + value = fixed.optimize(compressor); + } + value = value.transform(new TreeTransformer(function(node, descend) { + if (node instanceof AST_Scope) return node; + node = node.clone(); + descend(node, this); + return node; + })); + } + def.replaced++; + return value; + } + var state; + if (fixed && (state = self.fixed || def.fixed).should_replace !== false) { + var ev, init; + if (fixed instanceof AST_This) { + if (!is_funarg(def) && same_scope(def) && !cross_class(def)) init = fixed; + } else if ((ev = fixed.evaluate(compressor, true)) !== fixed + && typeof ev != "function" + && (ev === null + || typeof ev != "object" + || compressor.option("unsafe_regexp") + && ev instanceof RegExp && !def.cross_loop && same_scope(def))) { + init = make_node_from_constant(ev, fixed); + } + if (init) { + if (state.should_replace === undefined) { + var value_length = init.optimize(compressor).print_to_string().length; + if (!has_symbol_ref(fixed)) { + value_length = Math.min(value_length, fixed.print_to_string().length); + } + var name_length = def.name.length; + if (compressor.option("unused") && !compressor.exposed(def)) { + var refs = def.references.length - def.replaced - def.assignments; + refs = Math.min(refs, def.references.filter(function(ref) { + return ref.fixed === state; + }).length); + name_length += (name_length + 2 + value_length) / Math.max(1, refs); + } + state.should_replace = value_length - Math.floor(name_length) < compressor.eval_threshold; + } + if (state.should_replace) { + var value; + if (has_symbol_ref(fixed)) { + value = init.optimize(compressor); + if (value === init) value = value.clone(true); + } else { + value = best_of_expression(init.optimize(compressor), fixed); + if (value === init || value === fixed) value = value.clone(true); + } + def.replaced++; + return value; + } + } + } + } + return self; + + function cross_class(def) { + var scope = self.scope; + while (scope !== def.scope) { + if (scope instanceof AST_Class) return true; + scope = scope.parent_scope; + } + } + + function has_symbol_ref(value) { + var found; + value.walk(new TreeWalker(function(node) { + if (node instanceof AST_SymbolRef) found = true; + if (found) return true; + })); + return found; + } + }); + + function is_raw_tag(compressor, tag) { + return compressor.option("unsafe") + && tag instanceof AST_Dot + && tag.property == "raw" + && is_undeclared_ref(tag.expression) + && tag.expression.name == "String"; + } + + function decode_template(str) { + var malformed = false; + str = str.replace(/\\(u\{[^{}]*\}?|u[\s\S]{0,4}|x[\s\S]{0,2}|[0-9]+|[\s\S])/g, function(match, seq) { + var ch = decode_escape_sequence(seq); + if (typeof ch == "string") return ch; + malformed = true; + }); + if (!malformed) return str; + } + + OPT(AST_Template, function(self, compressor) { + if (!compressor.option("templates")) return self; + var tag = self.tag; + if (!tag || is_raw_tag(compressor, tag)) { + var exprs = []; + var strs = []; + for (var i = 0, status; i < self.strings.length; i++) { + var str = self.strings[i]; + if (!tag) { + var trimmed = decode_template(str); + if (trimmed) str = escape_literal(trimmed); + } + if (i > 0) { + var node = self.expressions[i - 1]; + var value = should_join(node); + if (value) { + var prev = strs[strs.length - 1]; + var joined = prev + value + str; + var decoded; + if (tag || typeof (decoded = decode_template(joined)) == status) { + strs[strs.length - 1] = decoded ? escape_literal(decoded) : joined; + continue; + } + } + exprs.push(node); + } + strs.push(str); + if (!tag) status = typeof trimmed; + } + if (!tag && strs.length > 1) { + if (strs[strs.length - 1] == "") return make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_Template, self, { + expressions: exprs.slice(0, -1), + strings: strs.slice(0, -1), + }).transform(compressor), + right: exprs[exprs.length - 1], + }).optimize(compressor); + if (strs[0] == "") { + var left = make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_String, self, { value: "" }), + right: exprs[0], + }); + for (var i = 1; strs[i] == "" && i < exprs.length; i++) { + left = make_node(AST_Binary, self, { + operator: "+", + left: left, + right: exprs[i], + }); + } + return best_of(compressor, self, make_node(AST_Binary, self, { + operator: "+", + left: left.transform(compressor), + right: make_node(AST_Template, self, { + expressions: exprs.slice(i), + strings: strs.slice(i), + }).transform(compressor), + }).optimize(compressor)); + } + } + self.expressions = exprs; + self.strings = strs; + } + return try_evaluate(compressor, self); + + function escape_literal(str) { + return str.replace(/\r|\\|`|\${/g, function(s) { + return "\\" + (s == "\r" ? "r" : s); + }); + } + + function should_join(node) { + var ev = node.evaluate(compressor); + if (ev === node) return; + if (tag && /\r|\\|`/.test(ev)) return; + ev = escape_literal("" + ev); + if (ev.length > node.print_to_string().length + "${}".length) return; + return ev; + } + }); + + function is_atomic(lhs, self) { + return lhs instanceof AST_SymbolRef || lhs.TYPE === self.TYPE; + } + + OPT(AST_Undefined, function(self, compressor) { + if (compressor.option("unsafe_undefined")) { + var undef = find_scope(compressor).find_variable("undefined"); + if (undef) { + var ref = make_node(AST_SymbolRef, self, { + name: "undefined", + scope: undef.scope, + thedef: undef, + }); + ref.is_undefined = true; + return ref; + } + } + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && is_atomic(lhs, self)) return self; + return make_node(AST_UnaryPrefix, self, { + operator: "void", + expression: make_node(AST_Number, self, { value: 0 }), + }); + }); + + OPT(AST_Infinity, function(self, compressor) { + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && is_atomic(lhs, self)) return self; + if (compressor.option("keep_infinity") && !lhs && !find_scope(compressor).find_variable("Infinity")) { + return self; + } + return make_node(AST_Binary, self, { + operator: "/", + left: make_node(AST_Number, self, { value: 1 }), + right: make_node(AST_Number, self, { value: 0 }), + }); + }); + + OPT(AST_NaN, function(self, compressor) { + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && is_atomic(lhs, self)) return self; + if (!lhs && !find_scope(compressor).find_variable("NaN")) return self; + return make_node(AST_Binary, self, { + operator: "/", + left: make_node(AST_Number, self, { value: 0 }), + right: make_node(AST_Number, self, { value: 0 }), + }); + }); + + function is_reachable(self, defs) { + var reachable = false; + var find_ref = new TreeWalker(function(node) { + if (reachable) return true; + if (node instanceof AST_SymbolRef && member(node.definition(), defs)) return reachable = true; + }); + var scan_scope = new TreeWalker(function(node) { + if (reachable) return true; + if (node instanceof AST_Lambda && node !== self) { + if (!(node.name || is_async(node) || is_generator(node))) { + var parent = scan_scope.parent(); + if (parent instanceof AST_Call && parent.expression === node) return; + } + node.walk(find_ref); + return true; + } + }); + self.walk(scan_scope); + return reachable; + } + + var ASSIGN_OPS = makePredicate("+ - * / % >> << >>> | ^ &"); + var ASSIGN_OPS_COMMUTATIVE = makePredicate("* | ^ &"); + OPT(AST_Assign, function(self, compressor) { + if (compressor.option("dead_code")) { + if (self.left instanceof AST_PropAccess) { + if (self.operator == "=") { + if (self.redundant) { + var exprs = [ self.left.expression ]; + if (self.left instanceof AST_Sub) exprs.push(self.left.property); + exprs.push(self.right); + return make_sequence(self, exprs).optimize(compressor); + } + if (self.left.equals(self.right) && !self.left.has_side_effects(compressor)) { + return self.right; + } + var exp = self.left.expression; + if (exp instanceof AST_Lambda + || !compressor.has_directive("use strict") + && exp instanceof AST_Constant + && !exp.may_throw_on_access(compressor)) { + return self.left instanceof AST_Dot ? self.right : make_sequence(self, [ + self.left.property, + self.right + ]).optimize(compressor); + } + } + } else if (self.left instanceof AST_SymbolRef && can_drop_symbol(self.left, compressor)) { + var parent; + if (self.operator == "=" && self.left.equals(self.right) + && !((parent = compressor.parent()) instanceof AST_UnaryPrefix && parent.operator == "delete")) { + return self.right; + } + if (self.left.is_immutable()) return strip_assignment(); + var def = self.left.definition(); + var scope = def.scope.resolve(); + var local = scope === compressor.find_parent(AST_Lambda); + var level = 0, node; + parent = compressor.self(); + if (!(scope.uses_arguments && is_funarg(def)) || compressor.has_directive("use strict")) do { + node = parent; + parent = compressor.parent(level++); + if (parent instanceof AST_Assign) { + if (parent.left instanceof AST_SymbolRef && parent.left.definition() === def) { + if (in_try(level, parent, !local)) break; + return strip_assignment(def); + } + if (parent.left.match_symbol(function(node) { + if (node instanceof AST_PropAccess) return true; + })) break; + continue; + } + if (parent instanceof AST_Exit) { + if (!local) break; + if (in_try(level, parent)) break; + if (is_reachable(scope, [ def ])) break; + return strip_assignment(def); + } + if (parent instanceof AST_SimpleStatement) { + if (!local) break; + if (is_reachable(scope, [ def ])) break; + var stat; + do { + stat = parent; + parent = compressor.parent(level++); + if (parent === scope && is_last_statement(parent.body, stat)) return strip_assignment(def); + } while (is_tail_block(stat, parent)); + break; + } + if (parent instanceof AST_VarDef) { + if (!(parent.name instanceof AST_SymbolDeclaration)) continue; + if (parent.name.definition() !== def) continue; + if (in_try(level, parent)) break; + return strip_assignment(def); + } + } while (is_tail(node, parent)); + } + } + if (compressor.option("sequences")) { + var seq = self.lift_sequences(compressor); + if (seq !== self) return seq.optimize(compressor); + } + if (compressor.option("assignments")) { + if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary) { + // x = expr1 OP expr2 + if (self.right.left instanceof AST_SymbolRef + && self.right.left.name == self.left.name + && ASSIGN_OPS[self.right.operator]) { + // x = x - 2 ---> x -= 2 + return make_compound(self.right.right); + } + if (self.right.right instanceof AST_SymbolRef + && self.right.right.name == self.left.name + && ASSIGN_OPS_COMMUTATIVE[self.right.operator] + && !self.right.left.has_side_effects(compressor)) { + // x = 2 & x ---> x &= 2 + return make_compound(self.right.left); + } + } + if ((self.operator == "-=" || self.operator == "+=" + && (self.left.is_boolean(compressor) || self.left.is_number(compressor))) + && self.right instanceof AST_Number + && self.right.value == 1) { + var op = self.operator.slice(0, -1); + return make_node(AST_UnaryPrefix, self, { + operator: op + op, + expression: self.left, + }); + } + } + return try_evaluate(compressor, self); + + function is_tail(node, parent) { + if (parent instanceof AST_Binary) switch (node) { + case parent.left: + return parent.right.is_constant_expression(scope); + case parent.right: + return true; + default: + return false; + } + if (parent instanceof AST_Conditional) switch (node) { + case parent.condition: + return parent.consequent.is_constant_expression(scope) + && parent.alternative.is_constant_expression(scope); + case parent.consequent: + case parent.alternative: + return true; + default: + return false; + } + if (parent instanceof AST_Sequence) { + var exprs = parent.expressions; + var stop = exprs.indexOf(node); + if (stop < 0) return false; + for (var i = exprs.length; --i > stop;) { + if (!exprs[i].is_constant_expression(scope)) return false; + } + return true; + } + return parent instanceof AST_UnaryPrefix; + } + + function is_tail_block(stat, parent) { + if (parent instanceof AST_BlockStatement) return is_last_statement(parent.body, stat); + if (parent instanceof AST_Catch) return is_last_statement(parent.body, stat); + if (parent instanceof AST_Finally) return is_last_statement(parent.body, stat); + if (parent instanceof AST_If) return parent.body === stat || parent.alternative === stat; + if (parent instanceof AST_Try) return parent.bfinally ? parent.bfinally === stat : parent.bcatch === stat; + } + + function in_try(level, node, sync) { + var right = self.right; + self.right = make_node(AST_Null, right); + var may_throw = node.may_throw(compressor); + self.right = right; + return find_try(compressor, level, node, scope, may_throw, sync); + } + + function make_compound(rhs) { + var fixed = self.left.fixed; + if (fixed) fixed.to_binary = replace_ref(function(node) { + return node.left; + }, fixed); + return make_node(AST_Assign, self, { + operator: self.right.operator + "=", + left: self.left, + right: rhs, + }); + } + + function strip_assignment(def) { + if (def) def.fixed = false; + return (self.operator != "=" ? make_node(AST_Binary, self, { + operator: self.operator.slice(0, -1), + left: self.left, + right: self.right, + }) : maintain_this_binding(compressor.parent(), self, self.right)).optimize(compressor); + } + }); + + OPT(AST_Conditional, function(self, compressor) { + if (compressor.option("sequences") && self.condition instanceof AST_Sequence) { + var expressions = self.condition.expressions.slice(); + var node = self.clone(); + node.condition = expressions.pop(); + expressions.push(node); + return make_sequence(self, expressions).optimize(compressor); + } + if (!compressor.option("conditionals")) return self; + var condition = self.condition; + if (compressor.option("booleans") && !condition.has_side_effects(compressor)) { + mark_duplicate_condition(compressor, condition); + } + condition = fuzzy_eval(compressor, condition); + if (!condition) { + AST_Node.warn("Condition always false [{start}]", self); + return make_sequence(self, [ self.condition, self.alternative ]).optimize(compressor); + } else if (!(condition instanceof AST_Node)) { + AST_Node.warn("Condition always true [{start}]", self); + return make_sequence(self, [ self.condition, self.consequent ]).optimize(compressor); + } + var first = first_in_statement(compressor); + var negated = condition.negate(compressor, first); + if ((first ? best_of_statement : best_of_expression)(condition, negated) === negated) { + self = make_node(AST_Conditional, self, { + condition: negated, + consequent: self.alternative, + alternative: self.consequent, + }); + negated = condition; + condition = self.condition; + } + var consequent = self.consequent; + var alternative = self.alternative; + var cond_lhs = extract_lhs(condition, compressor); + if (repeatable(compressor, cond_lhs)) { + // x ? x : y ---> x || y + if (cond_lhs.equals(consequent)) return make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative, + }).optimize(compressor); + // x ? y : x ---> x && y + if (cond_lhs.equals(alternative)) return make_node(AST_Binary, self, { + operator: "&&", + left: condition, + right: consequent, + }).optimize(compressor); + } + // if (foo) exp = something; else exp = something_else; + // | + // v + // exp = foo ? something : something_else; + var seq_tail = consequent.tail_node(); + if (seq_tail instanceof AST_Assign) { + var is_eq = seq_tail.operator == "="; + var alt_tail = is_eq ? alternative.tail_node() : alternative; + if ((is_eq || consequent === seq_tail) + && alt_tail instanceof AST_Assign + && seq_tail.operator == alt_tail.operator + && seq_tail.left.equals(alt_tail.left) + && (is_eq && seq_tail.left instanceof AST_SymbolRef + || !condition.has_side_effects(compressor) + && can_shift_lhs_of_tail(consequent) + && can_shift_lhs_of_tail(alternative))) { + return make_node(AST_Assign, self, { + operator: seq_tail.operator, + left: seq_tail.left, + right: make_node(AST_Conditional, self, { + condition: condition, + consequent: pop_lhs(consequent), + alternative: pop_lhs(alternative), + }), + }); + } + } + var alt_tail = alternative.tail_node(); + // x ? y : y ---> x, y + // x ? (a, c) : (b, c) ---> x ? a : b, c + if (seq_tail.equals(alt_tail)) return make_sequence(self, consequent.equals(alternative) ? [ + condition, + consequent, + ] : [ + make_node(AST_Conditional, self, { + condition: condition, + consequent: pop_seq(consequent), + alternative: pop_seq(alternative), + }), + alt_tail, + ]).optimize(compressor); + // x ? y.p : z.p ---> (x ? y : z).p + // x ? y(a) : z(a) ---> (x ? y : z)(a) + // x ? y.f(a) : z.f(a) ---> (x ? y : z).f(a) + var combined = combine_tail(consequent, alternative, true); + if (combined) return combined; + // x ? y(a) : y(b) ---> y(x ? a : b) + var arg_index; + if (consequent instanceof AST_Call + && alternative.TYPE == consequent.TYPE + && (arg_index = arg_diff(consequent, alternative)) >= 0 + && consequent.expression.equals(alternative.expression) + && !condition.has_side_effects(compressor) + && !consequent.expression.has_side_effects(compressor)) { + var node = consequent.clone(); + var arg = consequent.args[arg_index]; + node.args[arg_index] = arg instanceof AST_Spread ? make_node(AST_Spread, self, { + expression: make_node(AST_Conditional, self, { + condition: condition, + consequent: arg.expression, + alternative: alternative.args[arg_index].expression, + }), + }) : make_node(AST_Conditional, self, { + condition: condition, + consequent: arg, + alternative: alternative.args[arg_index], + }); + return node; + } + // x ? (y ? a : b) : b ---> x && y ? a : b + if (seq_tail instanceof AST_Conditional + && seq_tail.alternative.equals(alternative)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + left: condition, + operator: "&&", + right: fuse(consequent, seq_tail, "condition"), + }), + consequent: seq_tail.consequent, + alternative: merge_expression(seq_tail.alternative, alternative), + }); + } + // x ? (y ? a : b) : a ---> !x || y ? a : b + if (seq_tail instanceof AST_Conditional + && seq_tail.consequent.equals(alternative)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + left: negated, + operator: "||", + right: fuse(consequent, seq_tail, "condition"), + }), + consequent: merge_expression(seq_tail.consequent, alternative), + alternative: seq_tail.alternative, + }); + } + // x ? a : (y ? a : b) ---> x || y ? a : b + if (alt_tail instanceof AST_Conditional + && consequent.equals(alt_tail.consequent)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + left: condition, + operator: "||", + right: fuse(alternative, alt_tail, "condition"), + }), + consequent: merge_expression(consequent, alt_tail.consequent), + alternative: alt_tail.alternative, + }); + } + // x ? b : (y ? a : b) ---> !x && y ? a : b + if (alt_tail instanceof AST_Conditional + && consequent.equals(alt_tail.alternative)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + left: negated, + operator: "&&", + right: fuse(alternative, alt_tail, "condition"), + }), + consequent: alt_tail.consequent, + alternative: merge_expression(consequent, alt_tail.alternative), + }); + } + // x ? y && a : a ---> (!x || y) && a + if (seq_tail instanceof AST_Binary + && seq_tail.operator == "&&" + && seq_tail.right.equals(alternative)) { + return make_node(AST_Binary, self, { + operator: "&&", + left: make_node(AST_Binary, self, { + operator: "||", + left: negated, + right: fuse(consequent, seq_tail, "left"), + }), + right: merge_expression(seq_tail.right, alternative), + }).optimize(compressor); + } + // x ? y || a : a ---> x && y || a + if (seq_tail instanceof AST_Binary + && seq_tail.operator == "||" + && seq_tail.right.equals(alternative)) { + return make_node(AST_Binary, self, { + operator: "||", + left: make_node(AST_Binary, self, { + operator: "&&", + left: condition, + right: fuse(consequent, seq_tail, "left"), + }), + right: merge_expression(seq_tail.right, alternative), + }).optimize(compressor); + } + // x ? a : y && a ---> (x || y) && a + if (alt_tail instanceof AST_Binary + && alt_tail.operator == "&&" + && alt_tail.right.equals(consequent)) { + return make_node(AST_Binary, self, { + operator: "&&", + left: make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: fuse(alternative, alt_tail, "left"), + }), + right: merge_expression(consequent, alt_tail.right), + }).optimize(compressor); + } + // x ? a : y || a ---> !x && y || a + if (alt_tail instanceof AST_Binary + && alt_tail.operator == "||" + && alt_tail.right.equals(consequent)) { + return make_node(AST_Binary, self, { + operator: "||", + left: make_node(AST_Binary, self, { + operator: "&&", + left: negated, + right: fuse(alternative, alt_tail, "left"), + }), + right: merge_expression(consequent, alt_tail.right), + }).optimize(compressor); + } + var in_bool = compressor.option("booleans") && compressor.in_boolean_context(); + if (is_true(consequent)) { + // c ? true : false ---> !!c + if (is_false(alternative)) return booleanize(condition); + // c ? true : x ---> !!c || x + return make_node(AST_Binary, self, { + operator: "||", + left: booleanize(condition), + right: alternative, + }).optimize(compressor); + } + if (is_false(consequent)) { + // c ? false : true ---> !c + if (is_true(alternative)) return booleanize(condition.negate(compressor)); + // c ? false : x ---> !c && x + return make_node(AST_Binary, self, { + operator: "&&", + left: booleanize(condition.negate(compressor)), + right: alternative, + }).optimize(compressor); + } + // c ? x : true ---> !c || x + if (is_true(alternative)) return make_node(AST_Binary, self, { + operator: "||", + left: booleanize(condition.negate(compressor)), + right: consequent, + }).optimize(compressor); + // c ? x : false ---> !!c && x + if (is_false(alternative)) return make_node(AST_Binary, self, { + operator: "&&", + left: booleanize(condition), + right: consequent, + }).optimize(compressor); + if (compressor.option("typeofs")) mark_locally_defined(condition, consequent, alternative); + return self; + + function booleanize(node) { + if (node.is_boolean(compressor)) return node; + // !!expression + return make_node(AST_UnaryPrefix, node, { + operator: "!", + expression: node.negate(compressor), + }); + } + + // AST_True or !0 + function is_true(node) { + return node instanceof AST_True + || in_bool + && node instanceof AST_Constant + && node.value + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && !node.expression.value); + } + // AST_False or !1 or void 0 + function is_false(node) { + return node instanceof AST_False + || in_bool + && (node instanceof AST_Constant + && !node.value + || node instanceof AST_UnaryPrefix + && node.operator == "void" + && !node.expression.has_side_effects(compressor)) + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && node.expression.value); + } + + function arg_diff(consequent, alternative) { + var a = consequent.args; + var b = alternative.args; + var len = a.length; + if (len != b.length) return -2; + for (var i = 0; i < len; i++) { + if (!a[i].equals(b[i])) { + if (a[i] instanceof AST_Spread !== b[i] instanceof AST_Spread) return -3; + for (var j = i + 1; j < len; j++) { + if (!a[j].equals(b[j])) return -2; + } + return i; + } + } + return -1; + } + + function fuse(node, tail, prop) { + if (node === tail) return tail[prop]; + var exprs = node.expressions.slice(0, -1); + exprs.push(tail[prop]); + return make_sequence(node, exprs); + } + + function is_tail_equivalent(consequent, alternative) { + if (consequent.TYPE != alternative.TYPE) return; + if (consequent.optional != alternative.optional) return; + if (consequent instanceof AST_Call) { + if (arg_diff(consequent, alternative) != -1) return; + return consequent.TYPE != "Call" + || !(consequent.expression instanceof AST_PropAccess + || alternative.expression instanceof AST_PropAccess) + || is_tail_equivalent(consequent.expression, alternative.expression); + } + if (!(consequent instanceof AST_PropAccess)) return; + var p = consequent.property; + var q = alternative.property; + return (p instanceof AST_Node ? p.equals(q) : p == q) + && !(consequent.expression instanceof AST_Super || alternative.expression instanceof AST_Super); + } + + function combine_tail(consequent, alternative, top) { + var seq_tail = consequent.tail_node(); + var alt_tail = alternative.tail_node(); + if (!is_tail_equivalent(seq_tail, alt_tail)) return !top && make_node(AST_Conditional, self, { + condition: condition, + consequent: consequent, + alternative: alternative, + }); + var node = seq_tail.clone(); + var seq_expr = fuse(consequent, seq_tail, "expression"); + var alt_expr = fuse(alternative, alt_tail, "expression"); + var combined = combine_tail(seq_expr, alt_expr); + if (seq_tail.expression instanceof AST_Sequence) { + combined = maintain_this_binding(seq_tail, seq_tail.expression, combined); + } + node.expression = combined; + return node; + } + + function can_shift_lhs_of_tail(node) { + return node === node.tail_node() || all(node.expressions.slice(0, -1), function(expr) { + return !expr.has_side_effects(compressor); + }); + } + + function pop_lhs(node) { + if (!(node instanceof AST_Sequence)) return node.right; + var exprs = node.expressions.slice(); + exprs.push(exprs.pop().right); + return make_sequence(node, exprs); + } + + function pop_seq(node) { + if (!(node instanceof AST_Sequence)) return make_node(AST_Number, node, { value: 0 }); + return make_sequence(node, node.expressions.slice(0, -1)); + } + }); + + OPT(AST_Boolean, function(self, compressor) { + if (!compressor.option("booleans")) return self; + if (compressor.in_boolean_context()) return make_node(AST_Number, self, { value: +self.value }); + var p = compressor.parent(); + if (p instanceof AST_Binary && (p.operator == "==" || p.operator == "!=")) { + AST_Node.warn("Non-strict equality against boolean: {operator} {value} [{start}]", { + operator: p.operator, + value: self.value, + start: p.start, + }); + return make_node(AST_Number, self, { value: +self.value }); + } + return make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: make_node(AST_Number, self, { value: 1 - self.value }), + }); + }); + + OPT(AST_Spread, function(self, compressor) { + var exp = self.expression; + if (compressor.option("spreads") && exp instanceof AST_Array && !(compressor.parent() instanceof AST_Object)) { + return List.splice(exp.elements.map(function(node) { + return node instanceof AST_Hole ? make_node(AST_Undefined, node).optimize(compressor) : node; + })); + } + return self; + }); + + function safe_to_flatten(value, compressor) { + if (!value) return false; + var parent = compressor.parent(); + if (parent.TYPE != "Call") return true; + if (parent.expression !== compressor.self()) return true; + if (value instanceof AST_SymbolRef) { + value = value.fixed_value(); + if (!value) return false; + } + return value instanceof AST_Lambda && !value.contains_this(); + } + + OPT(AST_Sub, function(self, compressor) { + var expr = self.expression; + var prop = self.property; + var terminated = trim_optional_chain(self, compressor); + if (terminated) return terminated; + if (compressor.option("properties")) { + var key = prop.evaluate(compressor); + if (key !== prop) { + if (typeof key == "string") { + if (key == "undefined") { + key = undefined; + } else { + var value = parseFloat(key); + if (value.toString() == key) { + key = value; + } + } + } + prop = self.property = best_of_expression(prop, make_node_from_constant(key, prop).transform(compressor)); + var property = "" + key; + if (is_identifier_string(property) + && property.length <= prop.print_to_string().length + 1) { + return make_node(AST_Dot, self, { + optional: self.optional, + expression: expr, + property: property, + quoted: true, + }).optimize(compressor); + } + } + } + var parent = compressor.parent(); + var assigned = is_lhs(compressor.self(), parent); + var def, fn, fn_parent, index; + if (compressor.option("arguments") + && expr instanceof AST_SymbolRef + && is_arguments(def = expr.definition()) + && !expr.in_arg + && prop instanceof AST_Number + && Math.floor(index = prop.value) == index + && (fn = def.scope) === find_lambda() + && fn.uses_arguments < (assigned ? 2 : 3)) { + if (parent instanceof AST_UnaryPrefix && parent.operator == "delete") { + if (!def.deleted) def.deleted = []; + def.deleted[index] = true; + } + var argname = fn.argnames[index]; + if (def.deleted && def.deleted[index]) { + argname = null; + } else if (argname) { + var arg_def; + if (!(argname instanceof AST_SymbolFunarg) + || argname.name == "await" + || expr.scope.find_variable(argname.name) !== (arg_def = argname.definition())) { + argname = null; + } else if (compressor.has_directive("use strict") + || fn.name + || fn.rest + || !(fn_parent instanceof AST_Call + && index < fn_parent.args.length + && all(fn_parent.args.slice(0, index + 1), function(arg) { + return !(arg instanceof AST_Spread); + })) + || !all(fn.argnames, function(argname) { + return argname instanceof AST_SymbolFunarg; + })) { + if (has_reassigned() || arg_def.assignments || arg_def.orig.length > 1) argname = null; + } + } else if ((assigned || !has_reassigned()) + && index < fn.argnames.length + 5 + && compressor.drop_fargs(fn, fn_parent) + && !fn.rest) { + while (index >= fn.argnames.length) { + argname = fn.make_var(AST_SymbolFunarg, fn, "argument_" + fn.argnames.length); + fn.argnames.push(argname); + } + } + if (argname && find_if(function(node) { + return node.name === argname.name; + }, fn.argnames) === argname) { + if (assigned) def.reassigned--; + var sym = make_node(AST_SymbolRef, argname); + sym.reference(); + argname.unused = undefined; + return sym; + } + } + if (assigned) return self; + if (compressor.option("sequences") + && parent.TYPE != "Call" + && !(parent instanceof AST_ForEnumeration && parent.init === self)) { + var seq = lift_sequence_in_expression(self, compressor); + if (seq !== self) return seq.optimize(compressor); + } + if (key !== prop) { + var sub = self.flatten_object(property, compressor); + if (sub) { + expr = self.expression = sub.expression; + prop = self.property = sub.property; + } + } + var elements; + if (compressor.option("properties") + && compressor.option("side_effects") + && prop instanceof AST_Number + && expr instanceof AST_Array + && all(elements = expr.elements, function(value) { + return !(value instanceof AST_Spread); + })) { + var index = prop.value; + var retValue = elements[index]; + if (safe_to_flatten(retValue, compressor)) { + var is_hole = retValue instanceof AST_Hole; + var flatten = !is_hole; + var values = []; + for (var i = elements.length; --i > index;) { + var value = elements[i].drop_side_effect_free(compressor); + if (value) { + values.unshift(value); + if (flatten && value.has_side_effects(compressor)) flatten = false; + } + } + if (!flatten) values.unshift(retValue); + while (--i >= 0) { + var value = elements[i].drop_side_effect_free(compressor); + if (value) { + values.unshift(value); + } else if (is_hole) { + values.unshift(make_node(AST_Hole, elements[i])); + } else { + index--; + } + } + if (flatten) { + values.push(retValue); + return make_sequence(self, values).optimize(compressor); + } + return make_node(AST_Sub, self, { + expression: make_node(AST_Array, expr, { elements: values }), + property: make_node(AST_Number, prop, { value: index }), + }); + } + } + return try_evaluate(compressor, self); + + function find_lambda() { + var i = 0, p; + while (p = compressor.parent(i++)) { + if (p instanceof AST_Lambda) { + if (p instanceof AST_Accessor) return; + if (is_arrow(p)) continue; + fn_parent = compressor.parent(i); + return p; + } + } + } + + function has_reassigned() { + return !compressor.option("reduce_vars") || def.reassigned; + } + }); + + AST_LambdaExpression.DEFMETHOD("contains_super", function() { + var result = false; + var self = this; + self.walk(new TreeWalker(function(node) { + if (result) return true; + if (node instanceof AST_Super) return result = true; + if (node !== self && node instanceof AST_Scope && !is_arrow(node)) return true; + })); + return result; + }); + + // contains_this() + // returns false only if context bound by the specified scope (or scope + // containing the specified expression) is not referenced by `this` + (function(def) { + // scope of arrow function cannot bind to any context + def(AST_Arrow, return_false); + def(AST_AsyncArrow, return_false); + def(AST_Node, function() { + var result = false; + var self = this; + self.walk(new TreeWalker(function(node) { + if (result) return true; + if (node instanceof AST_This) return result = true; + if (node !== self && node instanceof AST_Scope && !is_arrow(node)) return true; + })); + return result; + }); + })(function(node, func) { + node.DEFMETHOD("contains_this", func); + }); + + function can_hoist_property(prop) { + return prop instanceof AST_ObjectKeyVal + && typeof prop.key == "string" + && !(prop instanceof AST_ObjectMethod && prop.value.contains_super()); + } + + AST_PropAccess.DEFMETHOD("flatten_object", function(key, compressor) { + if (!compressor.option("properties")) return; + if (key === "__proto__") return; + var self = this; + var expr = self.expression; + if (!(expr instanceof AST_Object)) return; + var props = expr.properties; + for (var i = props.length; --i >= 0;) { + var prop = props[i]; + if (prop.key !== key) continue; + if (!all(props, can_hoist_property)) return; + if (!safe_to_flatten(prop.value, compressor)) return; + var call, scope, values = []; + for (var j = 0; j < props.length; j++) { + var value = props[j].value; + if (props[j] instanceof AST_ObjectMethod) { + var arrow = !(value.uses_arguments || is_generator(value) || value.contains_this()); + if (arrow) { + if (!scope) scope = compressor.find_parent(AST_Scope); + var avoid = avoid_await_yield(compressor, scope); + value.each_argname(function(argname) { + if (avoid[argname.name]) arrow = false; + }); + } + var ctor; + if (arrow) { + ctor = is_async(value) ? AST_AsyncArrow : AST_Arrow; + } else if (i != j + || (call = compressor.parent()) instanceof AST_Call && call.expression === self) { + ctor = value.CTOR; + } else { + return; + } + value = make_node(ctor, value); + } + values.push(value); + } + return make_node(AST_Sub, self, { + expression: make_node(AST_Array, expr, { elements: values }), + property: make_node(AST_Number, self, { value: i }), + }); + } + }); + + OPT(AST_Dot, function(self, compressor) { + if (self.property == "arguments" || self.property == "caller") { + AST_Node.warn("Function.prototype.{property} not supported [{start}]", self); + } + var parent = compressor.parent(); + if (is_lhs(compressor.self(), parent)) return self; + var terminated = trim_optional_chain(self, compressor); + if (terminated) return terminated; + if (compressor.option("sequences") + && parent.TYPE != "Call" + && !(parent instanceof AST_ForEnumeration && parent.init === self)) { + var seq = lift_sequence_in_expression(self, compressor); + if (seq !== self) return seq.optimize(compressor); + } + if (compressor.option("unsafe_proto") + && self.expression instanceof AST_Dot + && self.expression.property == "prototype") { + var exp = self.expression.expression; + if (is_undeclared_ref(exp)) switch (exp.name) { + case "Array": + self.expression = make_node(AST_Array, self.expression, { elements: [] }); + break; + case "Function": + self.expression = make_node(AST_Function, self.expression, { + argnames: [], + body: [], + }).init_vars(exp.scope); + break; + case "Number": + self.expression = make_node(AST_Number, self.expression, { value: 0 }); + break; + case "Object": + self.expression = make_node(AST_Object, self.expression, { properties: [] }); + break; + case "RegExp": + self.expression = make_node(AST_RegExp, self.expression, { value: /t/ }); + break; + case "String": + self.expression = make_node(AST_String, self.expression, { value: "" }); + break; + } + } + var sub = self.flatten_object(self.property, compressor); + if (sub) return sub.optimize(compressor); + return try_evaluate(compressor, self); + }); + + OPT(AST_DestructuredArray, function(self, compressor) { + if (compressor.option("rests") && self.rest instanceof AST_DestructuredArray) { + return make_node(AST_DestructuredArray, self, { + elements: self.elements.concat(self.rest.elements), + rest: self.rest.rest, + }); + } + return self; + }); + + OPT(AST_DestructuredKeyVal, function(self, compressor) { + if (compressor.option("objects")) { + var key = self.key; + if (key instanceof AST_Node) { + key = key.evaluate(compressor); + if (key !== self.key) self.key = "" + key; + } + } + return self; + }); + + OPT(AST_Object, function(self, compressor) { + if (!compressor.option("objects")) return self; + var changed = false; + var found = false; + var generated = false; + var keep_duplicate = compressor.has_directive("use strict"); + var keys = []; + var map = new Dictionary(); + var values = []; + self.properties.forEach(function(prop) { + if (!(prop instanceof AST_Spread)) return process(prop); + found = true; + var exp = prop.expression; + if (compressor.option("spreads") && exp instanceof AST_Object && all(exp.properties, function(prop) { + if (prop instanceof AST_ObjectGetter) return false; + if (prop instanceof AST_Spread) return false; + if (prop.key !== "__proto__") return true; + if (prop instanceof AST_ObjectSetter) return true; + return !prop.value.has_side_effects(compressor); + })) { + changed = true; + exp.properties.forEach(function(prop) { + var key = prop.key; + var setter = prop instanceof AST_ObjectSetter; + if (key === "__proto__") { + if (!setter) return; + key = make_node_from_constant(key, prop); + } + process(setter ? make_node(AST_ObjectKeyVal, prop, { + key: key, + value: make_node(AST_Undefined, prop).optimize(compressor), + }) : prop); + }); + } else { + generated = true; + flush(); + values.push(prop); + } + }); + flush(); + if (!changed) return self; + if (found && generated && values.length == 1) { + var value = values[0]; + if (value instanceof AST_ObjectProperty && value.key instanceof AST_Number) { + value.key = "" + value.key.value; + } + } + return make_node(AST_Object, self, { properties: values }); + + function flush() { + keys.forEach(function(key) { + var props = map.get(key); + switch (props.length) { + case 0: + return; + case 1: + return values.push(props[0]); + } + changed = true; + var tail = keep_duplicate && !generated && props.pop(); + values.push(props.length == 1 ? props[0] : make_node(AST_ObjectKeyVal, self, { + key: props[0].key, + value: make_sequence(self, props.map(function(prop) { + return prop.value; + })), + })); + if (tail) values.push(tail); + props.length = 0; + }); + keys = []; + map = new Dictionary(); + } + + function process(prop) { + var key = prop.key; + if (key instanceof AST_Node) { + found = true; + key = key.evaluate(compressor); + if (key === prop.key || key === "__proto__") { + generated = true; + } else { + key = prop.key = "" + key; + } + } + if (can_hoist_property(prop)) { + if (prop.value.has_side_effects(compressor)) flush(); + keys.push(key); + map.add(key, prop); + } else { + flush(); + values.push(prop); + } + if (found && !generated && typeof key == "string" && RE_POSITIVE_INTEGER.test(key)) { + generated = true; + if (map.has(key)) prop = map.get(key)[0]; + prop.key = make_node(AST_Number, prop, { value: +key }); + } + } + }); + + function flatten_var(name) { + var redef = name.definition().redefined(); + if (redef) { + name = name.clone(); + name.thedef = redef; + } + return name; + } + + function has_arg_refs(fn, node) { + var found = false; + node.walk(new TreeWalker(function(node) { + if (found) return true; + if (node instanceof AST_SymbolRef && fn.variables.get(node.name) === node.definition()) { + return found = true; + } + })); + return found; + } + + function insert_assign(def, assign) { + var visited = []; + def.references.forEach(function(ref) { + var fixed = ref.fixed; + if (!fixed || !push_uniq(visited, fixed)) return; + if (fixed.assigns) { + fixed.assigns.unshift(assign); + } else { + fixed.assigns = [ assign ]; + } + }); + } + + function init_ref(compressor, name) { + var sym = make_node(AST_SymbolRef, name); + var assign = make_node(AST_Assign, name, { + operator: "=", + left: sym, + right: make_node(AST_Undefined, name).transform(compressor), + }); + var def = name.definition(); + if (def.fixed) { + sym.fixed = function() { + return assign.right; + }; + sym.fixed.assigns = [ assign ]; + insert_assign(def, assign); + } + def.assignments++; + def.references.push(sym); + return assign; + } + + (function(def) { + def(AST_Node, noop); + def(AST_Assign, noop); + def(AST_Await, function(compressor, scope, no_return, in_loop) { + if (!compressor.option("awaits")) return; + var self = this; + var inlined = self.expression.try_inline(compressor, scope, no_return, in_loop, true); + if (!inlined) return; + if (!no_return) scan_local_returns(inlined, function(node) { + node.in_bool = false; + var value = node.value; + if (value instanceof AST_Await) return; + node.value = make_node(AST_Await, self, { + expression: value || make_node(AST_Undefined, node).transform(compressor), + }); + }); + return aborts(inlined) ? inlined : make_node(AST_BlockStatement, self, { + body: [ inlined, make_node(AST_SimpleStatement, self, { + body: make_node(AST_Await, self, { expression: make_node(AST_Number, self, { value: 0 })}), + }) ], + }); + }); + def(AST_Binary, function(compressor, scope, no_return, in_loop, in_await) { + if (no_return === undefined) return; + var self = this; + var op = self.operator; + if (!lazy_op[op]) return; + var inlined = self.right.try_inline(compressor, scope, no_return, in_loop, in_await); + if (!inlined) return; + return make_node(AST_If, self, { + condition: make_condition(self.left), + body: inlined, + alternative: no_return ? null : make_node(AST_Return, self, { + value: make_node(AST_Undefined, self).transform(compressor), + }), + }); + + function make_condition(cond) { + switch (op) { + case "&&": + return cond; + case "||": + return cond.negate(compressor); + case "??": + return make_node(AST_Binary, self, { + operator: "==", + left: make_node(AST_Null, self), + right: cond, + }); + } + } + }); + def(AST_BlockStatement, function(compressor, scope, no_return, in_loop) { + if (no_return) return; + if (!this.variables) return; + var body = this.body; + var last = body.length - 1; + if (last < 0) return; + var inlined = body[last].try_inline(compressor, this, no_return, in_loop); + if (!inlined) return; + body[last] = inlined; + return this; + }); + def(AST_Call, function(compressor, scope, no_return, in_loop, in_await) { + if (compressor.option("inline") < 4) return; + var call = this; + if (call.is_expr_pure(compressor)) return; + var fn = call.expression; + if (!(fn instanceof AST_LambdaExpression)) return; + if (fn.name) return; + if (fn.uses_arguments) return; + if (fn.pinned()) return; + if (is_generator(fn)) return; + var arrow = is_arrow(fn); + if (arrow && fn.value) return; + if (fn.body[0] instanceof AST_Directive) return; + if (fn.contains_this()) return; + if (!scope) scope = find_scope(compressor); + var defined = new Dictionary(); + defined.set("NaN", true); + while (!(scope instanceof AST_Scope)) { + scope.variables.each(function(def) { + defined.set(def.name, true); + }); + scope = scope.parent_scope; + } + if (!member(scope, compressor.stack)) return; + if (scope.pinned() && fn.variables.size() > (arrow ? 0 : 1)) return; + if (scope instanceof AST_Toplevel) { + if (fn.variables.size() > (arrow ? 0 : 1)) { + if (!compressor.toplevel.vars) return; + if (fn.functions.size() > 0 && !compressor.toplevel.funcs) return; + } + defined.set("arguments", true); + } + var async = !in_await && is_async(fn); + if (async) { + if (!compressor.option("awaits")) return; + if (!is_async(scope)) return; + if (call.may_throw(compressor)) return; + } + var names = scope.var_names(); + if (in_loop) in_loop = []; + if (!fn.variables.all(function(def, name) { + if (in_loop) in_loop.push(def); + if (!defined.has(name) && !names.has(name)) return true; + return !arrow && name == "arguments" && def.orig.length == 1; + })) return; + if (in_loop && in_loop.length > 0 && is_reachable(fn, in_loop)) return; + var simple_argnames = true; + if (!all(fn.argnames, function(argname) { + var abort = false; + var tw = new TreeWalker(function(node) { + if (abort) return true; + if (node instanceof AST_DefaultValue) { + if (has_arg_refs(fn, node.value)) return abort = true; + node.name.walk(tw); + return true; + } + if (node instanceof AST_DestructuredKeyVal) { + if (node.key instanceof AST_Node && has_arg_refs(fn, node.key)) return abort = true; + node.value.walk(tw); + return true; + } + if (node instanceof AST_SymbolFunarg && !all(node.definition().orig, function(sym) { + return !(sym instanceof AST_SymbolDefun); + })) return abort = true; + }); + argname.walk(tw); + if (abort) return false; + if (!(argname instanceof AST_SymbolFunarg)) simple_argnames = false; + return true; + })) return; + if (fn.rest) { + if (has_arg_refs(fn, fn.rest)) return; + simple_argnames = false; + } + var verify_body; + if (no_return) { + verify_body = function(stat) { + var abort = false; + stat.walk(new TreeWalker(function(node) { + if (abort) return true; + if (async && (node instanceof AST_Await || node instanceof AST_ForAwaitOf) + || node instanceof AST_Return) { + return abort = true; + } + if (node instanceof AST_Scope) return true; + })); + return !abort; + }; + } else if (in_await || is_async(fn) || in_async_generator(scope)) { + verify_body = function(stat) { + var abort = false; + var find_return = new TreeWalker(function(node) { + if (abort) return true; + if (node instanceof AST_Return) return abort = true; + if (node instanceof AST_Scope) return true; + }); + stat.walk(new TreeWalker(function(node) { + if (abort) return true; + if (node instanceof AST_Try) { + if (node.bfinally && all(node.body, function(stat) { + stat.walk(find_return); + return !abort; + }) && node.bcatch) node.bcatch.walk(find_return); + return true; + } + if (node instanceof AST_Scope) return true; + })); + return !abort; + }; + } + if (verify_body && !all(fn.body, verify_body)) return; + if (!safe_from_await_yield(fn, avoid_await_yield(compressor, scope))) return; + fn.functions.each(function(def, name) { + scope.functions.set(name, def); + }); + var body = []; + fn.variables.each(function(def, name) { + if (!arrow && name == "arguments" && def.orig.length == 1) return; + names.set(name, true); + scope.enclosed.push(def); + scope.variables.set(name, def); + def.single_use = false; + if (!in_loop) return; + if (def.references.length == def.replaced) return; + if (def.orig.length == def.eliminated) return; + if (def.orig.length == 1 && fn.functions.has(name)) return; + if (!all(def.orig, function(sym) { + if (sym instanceof AST_SymbolConst) return false; + if (sym instanceof AST_SymbolFunarg) return !sym.unused && def.scope.resolve() !== fn; + if (sym instanceof AST_SymbolLet) return false; + return true; + })) return; + var sym = def.orig[0]; + if (sym instanceof AST_SymbolCatch) return; + body.push(make_node(AST_SimpleStatement, sym, { body: init_ref(compressor, flatten_var(sym)) })); + }); + var defs = Object.create(null), syms = new Dictionary(); + if (simple_argnames && all(call.args, function(arg) { + return !(arg instanceof AST_Spread); + })) { + var values = call.args.slice(); + fn.argnames.forEach(function(argname) { + var value = values.shift(); + if (argname.unused) { + if (value) body.push(make_node(AST_SimpleStatement, call, { body: value })); + return; + } + var defn = make_node(AST_VarDef, call, { + name: argname.convert_symbol(AST_SymbolVar, process), + value: value || make_node(AST_Undefined, call).transform(compressor), + }); + if (argname instanceof AST_SymbolFunarg) insert_assign(argname.definition(), defn); + body.push(make_node(AST_Var, call, { definitions: [ defn ] })); + }); + if (values.length) body.push(make_node(AST_SimpleStatement, call, { + body: make_sequence(call, values), + })); + } else { + body.push(make_node(AST_Var, call, { + definitions: [ make_node(AST_VarDef, call, { + name: make_node(AST_DestructuredArray, call, { + elements: fn.argnames.map(function(argname) { + if (argname.unused) return make_node(AST_Hole, argname); + return argname.convert_symbol(AST_SymbolVar, process); + }), + rest: fn.rest && fn.rest.convert_symbol(AST_SymbolVar, process), + }), + value: make_node(AST_Array, call, { elements: call.args.slice() }), + }) ], + })); + } + syms.each(function(orig, id) { + var def = defs[id]; + [].unshift.apply(def.orig, orig); + def.eliminated += orig.length; + }); + [].push.apply(body, in_loop ? fn.body.filter(function(stat) { + if (!(stat instanceof AST_LambdaDefinition)) return true; + var name = make_node(AST_SymbolVar, flatten_var(stat.name)); + var def = name.definition(); + def.fixed = false; + def.orig.push(name); + def.eliminated++; + body.push(make_node(AST_Var, stat, { + definitions: [ make_node(AST_VarDef, stat, { + name: name, + value: to_func_expr(stat, true), + }) ], + })); + return false; + }) : fn.body); + var inlined = make_node(AST_BlockStatement, call, { body: body }); + if (!no_return) { + if (async) scan_local_returns(inlined, function(node) { + var value = node.value; + if (is_undefined(value)) return; + node.value = make_node(AST_Await, call, { expression: value }); + }); + body.push(make_node(AST_Return, call, { + value: in_async_generator(scope) ? make_node(AST_Undefined, call).transform(compressor) : null, + })); + } + return inlined; + + function process(sym, argname) { + var def = argname.definition(); + defs[def.id] = def; + syms.add(def.id, sym); + } + }); + def(AST_Conditional, function(compressor, scope, no_return, in_loop, in_await) { + var self = this; + var body = self.consequent.try_inline(compressor, scope, no_return, in_loop, in_await); + var alt = self.alternative.try_inline(compressor, scope, no_return, in_loop, in_await); + if (!body && !alt) return; + return make_node(AST_If, self, { + condition: self.condition, + body: body || make_body(self.consequent), + alternative: alt || make_body(self.alternative), + }); + + function make_body(value) { + if (no_return) return make_node(AST_SimpleStatement, value, { body: value }); + return make_node(AST_Return, value, { value: value }); + } + }); + def(AST_For, function(compressor, scope, no_return, in_loop) { + var body = this.body.try_inline(compressor, scope, true, true); + if (body) this.body = body; + var inlined = this.init; + if (inlined) { + inlined = inlined.try_inline(compressor, scope, true, in_loop); + if (inlined) { + this.init = null; + if (inlined instanceof AST_BlockStatement) { + inlined.body.push(this); + return inlined; + } + return make_node(AST_BlockStatement, inlined, { body: [ inlined, this ] }); + } + } + return body && this; + }); + def(AST_ForEnumeration, function(compressor, scope, no_return, in_loop) { + var body = this.body.try_inline(compressor, scope, true, true); + if (body) this.body = body; + var obj = this.object; + if (obj instanceof AST_Sequence) { + var inlined = inline_sequence(compressor, scope, true, in_loop, false, obj, 1); + if (inlined) { + this.object = obj.tail_node(); + inlined.body.push(this); + return inlined; + } + } + return body && this; + }); + def(AST_If, function(compressor, scope, no_return, in_loop) { + var body = this.body.try_inline(compressor, scope, no_return, in_loop); + if (body) this.body = body; + var alt = this.alternative; + if (alt) { + alt = alt.try_inline(compressor, scope, no_return, in_loop); + if (alt) this.alternative = alt; + } + var cond = this.condition; + if (cond instanceof AST_Sequence) { + var inlined = inline_sequence(compressor, scope, true, in_loop, false, cond, 1); + if (inlined) { + this.condition = cond.tail_node(); + inlined.body.push(this); + return inlined; + } + } + return (body || alt) && this; + }); + def(AST_IterationStatement, function(compressor, scope, no_return, in_loop) { + var body = this.body.try_inline(compressor, scope, true, true); + if (!body) return; + this.body = body; + return this; + }); + def(AST_LabeledStatement, function(compressor, scope, no_return, in_loop) { + var body = this.body.try_inline(compressor, scope, no_return, in_loop); + if (!body) return; + if (this.body instanceof AST_IterationStatement && body instanceof AST_BlockStatement) { + var loop = body.body.pop(); + this.body = loop; + body.body.push(this); + return body; + } + this.body = body; + return this; + }); + def(AST_New, noop); + def(AST_Return, function(compressor, scope, no_return, in_loop) { + var value = this.value; + return value && value.try_inline(compressor, scope, undefined, in_loop === "try"); + }); + function inline_sequence(compressor, scope, no_return, in_loop, in_await, node, skip) { + var body = [], exprs = node.expressions, no_ret = no_return; + for (var i = exprs.length - (skip || 0), j = i; --i >= 0; no_ret = true, in_await = false) { + var inlined = exprs[i].try_inline(compressor, scope, no_ret, in_loop, in_await); + if (!inlined) continue; + flush(); + body.push(inlined); + } + if (body.length == 0) return; + flush(); + if (!no_return && body[0] instanceof AST_SimpleStatement) { + body[0] = make_node(AST_Return, node, { value: body[0].body }); + } + return make_node(AST_BlockStatement, node, { body: body.reverse() }); + + function flush() { + if (j > i + 1) body.push(make_node(AST_SimpleStatement, node, { + body: make_sequence(node, exprs.slice(i + 1, j)), + })); + j = i; + } + } + def(AST_Sequence, function(compressor, scope, no_return, in_loop, in_await) { + return inline_sequence(compressor, scope, no_return, in_loop, in_await, this); + }); + def(AST_SimpleStatement, function(compressor, scope, no_return, in_loop) { + var body = this.body; + while (body instanceof AST_UnaryPrefix) { + var op = body.operator; + if (unary_side_effects[op]) break; + if (op == "void") break; + body = body.expression; + } + if (!no_return && !is_undefined(body)) body = make_node(AST_UnaryPrefix, this, { + operator: "void", + expression: body, + }); + return body.try_inline(compressor, scope, no_return || false, in_loop); + }); + def(AST_UnaryPrefix, function(compressor, scope, no_return, in_loop, in_await) { + var self = this; + var op = self.operator; + if (unary_side_effects[op]) return; + if (!no_return && op == "void") no_return = false; + var inlined = self.expression.try_inline(compressor, scope, no_return, in_loop, in_await); + if (!inlined) return; + if (!no_return) scan_local_returns(inlined, function(node) { + node.in_bool = false; + var value = node.value; + if (op == "void" && is_undefined(value)) return; + node.value = make_node(AST_UnaryPrefix, self, { + operator: op, + expression: value || make_node(AST_Undefined, node).transform(compressor), + }); + }); + return inlined; + }); + def(AST_With, function(compressor, scope, no_return, in_loop) { + var body = this.body.try_inline(compressor, scope, no_return, in_loop); + if (body) this.body = body; + var exp = this.expression; + if (exp instanceof AST_Sequence) { + var inlined = inline_sequence(compressor, scope, true, in_loop, false, exp, 1); + if (inlined) { + this.expression = exp.tail_node(); + inlined.body.push(this); + return inlined; + } + } + return body && this; + }); + def(AST_Yield, function(compressor, scope, no_return, in_loop) { + if (!compressor.option("yields")) return; + if (!this.nested) return; + var call = this.expression; + if (call.TYPE != "Call") return; + var fn = call.expression; + switch (fn.CTOR) { + case AST_AsyncGeneratorFunction: + fn = make_node(AST_AsyncFunction, fn); + break; + case AST_GeneratorFunction: + fn = make_node(AST_Function, fn); + break; + default: + return; + } + call = call.clone(); + call.expression = fn; + return call.try_inline(compressor, scope, no_return, in_loop); + }); + })(function(node, func) { + node.DEFMETHOD("try_inline", func); + }); + + OPT(AST_Return, function(self, compressor) { + var value = self.value; + if (value && compressor.option("side_effects") + && is_undefined(value, compressor) + && !in_async_generator(compressor.find_parent(AST_Scope))) { + self.value = null; + } + return self; + }); +})(function(node, optimizer) { + node.DEFMETHOD("optimize", function(compressor) { + var self = this; + if (self._optimized) return self; + if (compressor.has_directive("use asm")) return self; + var opt = optimizer(self, compressor); + opt._optimized = true; + return opt; + }); +}); diff --git a/node_modules/uglify-js/lib/minify.js b/node_modules/uglify-js/lib/minify.js new file mode 100644 index 0000000..c7a1341 --- /dev/null +++ b/node_modules/uglify-js/lib/minify.js @@ -0,0 +1,276 @@ +"use strict"; + +var to_ascii, to_base64; +if (typeof Buffer == "undefined") { + to_ascii = atob; + to_base64 = btoa; +} else if (typeof Buffer.alloc == "undefined") { + to_ascii = function(b64) { + return new Buffer(b64, "base64").toString(); + }; + to_base64 = function(str) { + return new Buffer(str).toString("base64"); + }; +} else { + to_ascii = function(b64) { + return Buffer.from(b64, "base64").toString(); + }; + to_base64 = function(str) { + return Buffer.from(str).toString("base64"); + }; +} + +function read_source_map(name, toplevel) { + var comments = toplevel.end.comments_after; + for (var i = comments.length; --i >= 0;) { + var comment = comments[i]; + if (comment.type != "comment1") break; + var match = /^# ([^\s=]+)=(\S+)\s*$/.exec(comment.value); + if (!match) break; + if (match[1] == "sourceMappingURL") { + match = /^data:application\/json(;.*?)?;base64,([^,]+)$/.exec(match[2]); + if (!match) break; + return to_ascii(match[2]); + } + } + AST_Node.warn("inline source map not found: {name}", { + name: name, + }); +} + +function parse_source_map(content) { + try { + return JSON.parse(content); + } catch (ex) { + throw new Error("invalid input source map: " + content); + } +} + +function set_shorthand(name, options, keys) { + keys.forEach(function(key) { + if (options[key]) { + if (typeof options[key] != "object") options[key] = {}; + if (!(name in options[key])) options[key][name] = options[name]; + } + }); +} + +function init_cache(cache) { + if (!cache) return; + if (!("props" in cache)) { + cache.props = new Dictionary(); + } else if (!(cache.props instanceof Dictionary)) { + cache.props = Dictionary.fromObject(cache.props); + } +} + +function to_json(cache) { + return { + props: cache.props.toObject() + }; +} + +function minify(files, options) { + try { + options = defaults(options, { + annotations: undefined, + compress: {}, + enclose: false, + expression: false, + ie: false, + ie8: false, + keep_fargs: false, + keep_fnames: false, + mangle: {}, + module: false, + nameCache: null, + output: {}, + parse: {}, + rename: undefined, + sourceMap: false, + timings: false, + toplevel: !!(options && options["module"]), + v8: false, + validate: false, + warnings: false, + webkit: false, + wrap: false, + }, true); + if (options.validate) AST_Node.enable_validation(); + var timings = options.timings && { start: Date.now() }; + if (options.annotations !== undefined) set_shorthand("annotations", options, [ "compress", "output" ]); + if (options.expression) set_shorthand("expression", options, [ "compress", "parse" ]); + if (options.ie8) options.ie = options.ie || options.ie8; + if (options.ie) set_shorthand("ie", options, [ "compress", "mangle", "output", "rename" ]); + if (options.keep_fargs) set_shorthand("keep_fargs", options, [ "compress", "mangle", "rename" ]); + if (options.keep_fnames) set_shorthand("keep_fnames", options, [ "compress", "mangle", "rename" ]); + if (options.module) set_shorthand("module", options, [ "compress", "parse" ]); + if (options.toplevel) set_shorthand("toplevel", options, [ "compress", "mangle", "rename" ]); + if (options.v8) set_shorthand("v8", options, [ "mangle", "output", "rename" ]); + if (options.webkit) set_shorthand("webkit", options, [ "compress", "mangle", "output", "rename" ]); + var quoted_props; + if (options.mangle) { + options.mangle = defaults(options.mangle, { + cache: options.nameCache && (options.nameCache.vars || {}), + eval: false, + ie: false, + keep_fargs: false, + keep_fnames: false, + properties: false, + reserved: [], + toplevel: false, + v8: false, + webkit: false, + }, true); + if (options.mangle.properties) { + if (typeof options.mangle.properties != "object") { + options.mangle.properties = {}; + } + if (options.mangle.properties.keep_quoted) { + quoted_props = options.mangle.properties.reserved; + if (!Array.isArray(quoted_props)) quoted_props = []; + options.mangle.properties.reserved = quoted_props; + } + if (options.nameCache && !("cache" in options.mangle.properties)) { + options.mangle.properties.cache = options.nameCache.props || {}; + } + } + init_cache(options.mangle.cache); + init_cache(options.mangle.properties.cache); + } + if (options.rename === undefined) options.rename = options.compress && options.mangle; + if (options.sourceMap) { + options.sourceMap = defaults(options.sourceMap, { + content: null, + filename: null, + includeSources: false, + names: true, + root: null, + url: null, + }, true); + } + var warnings = []; + if (options.warnings) AST_Node.log_function(function(warning) { + warnings.push(warning); + }, options.warnings == "verbose"); + if (timings) timings.parse = Date.now(); + var toplevel; + options.parse = options.parse || {}; + if (files instanceof AST_Node) { + toplevel = files; + } else { + if (typeof files == "string") files = [ files ]; + options.parse.toplevel = null; + var source_map_content = options.sourceMap && options.sourceMap.content; + if (typeof source_map_content == "string" && source_map_content != "inline") { + source_map_content = parse_source_map(source_map_content); + } + if (source_map_content) options.sourceMap.orig = Object.create(null); + for (var name in files) if (HOP(files, name)) { + options.parse.filename = name; + options.parse.toplevel = toplevel = parse(files[name], options.parse); + if (source_map_content == "inline") { + var inlined_content = read_source_map(name, toplevel); + if (inlined_content) options.sourceMap.orig[name] = parse_source_map(inlined_content); + } else if (source_map_content) { + options.sourceMap.orig[name] = source_map_content; + } + } + } + if (options.parse.expression) toplevel = toplevel.wrap_expression(); + if (quoted_props) reserve_quoted_keys(toplevel, quoted_props); + [ "enclose", "wrap" ].forEach(function(action) { + var option = options[action]; + if (!option) return; + var orig = toplevel.print_to_string().slice(0, -1); + toplevel = toplevel[action](option); + files[toplevel.start.file] = toplevel.print_to_string().replace(orig, ""); + }); + if (options.validate) toplevel.validate_ast(); + if (timings) timings.rename = Date.now(); + if (options.rename) { + toplevel.figure_out_scope(options.rename); + toplevel.expand_names(options.rename); + } + if (timings) timings.compress = Date.now(); + if (options.compress) { + toplevel = new Compressor(options.compress).compress(toplevel); + if (options.validate) toplevel.validate_ast(); + } + if (timings) timings.scope = Date.now(); + if (options.mangle) toplevel.figure_out_scope(options.mangle); + if (timings) timings.mangle = Date.now(); + if (options.mangle) { + toplevel.compute_char_frequency(options.mangle); + toplevel.mangle_names(options.mangle); + } + if (timings) timings.properties = Date.now(); + if (quoted_props) reserve_quoted_keys(toplevel, quoted_props); + if (options.mangle && options.mangle.properties) mangle_properties(toplevel, options.mangle.properties); + if (options.parse.expression) toplevel = toplevel.unwrap_expression(); + if (timings) timings.output = Date.now(); + var result = {}; + var output = defaults(options.output, { + ast: false, + code: true, + }); + if (output.ast) result.ast = toplevel; + if (output.code) { + if (options.sourceMap) { + output.source_map = SourceMap(options.sourceMap); + if (options.sourceMap.includeSources) { + if (files instanceof AST_Toplevel) { + throw new Error("original source content unavailable"); + } else for (var name in files) if (HOP(files, name)) { + output.source_map.setSourceContent(name, files[name]); + } + } + } + delete output.ast; + delete output.code; + var stream = OutputStream(output); + toplevel.print(stream); + result.code = stream.get(); + if (options.sourceMap) { + result.map = output.source_map.toString(); + var url = options.sourceMap.url; + if (url) { + result.code = result.code.replace(/\n\/\/# sourceMappingURL=\S+\s*$/, ""); + if (url == "inline") { + result.code += "\n//# sourceMappingURL=data:application/json;charset=utf-8;base64," + to_base64(result.map); + } else { + result.code += "\n//# sourceMappingURL=" + url; + } + } + } + } + if (options.nameCache && options.mangle) { + if (options.mangle.cache) options.nameCache.vars = to_json(options.mangle.cache); + if (options.mangle.properties && options.mangle.properties.cache) { + options.nameCache.props = to_json(options.mangle.properties.cache); + } + } + if (timings) { + timings.end = Date.now(); + result.timings = { + parse: 1e-3 * (timings.rename - timings.parse), + rename: 1e-3 * (timings.compress - timings.rename), + compress: 1e-3 * (timings.scope - timings.compress), + scope: 1e-3 * (timings.mangle - timings.scope), + mangle: 1e-3 * (timings.properties - timings.mangle), + properties: 1e-3 * (timings.output - timings.properties), + output: 1e-3 * (timings.end - timings.output), + total: 1e-3 * (timings.end - timings.start) + }; + } + if (warnings.length) { + result.warnings = warnings; + } + return result; + } catch (ex) { + return { error: ex }; + } finally { + AST_Node.log_function(); + AST_Node.disable_validation(); + } +} diff --git a/node_modules/uglify-js/lib/mozilla-ast.js b/node_modules/uglify-js/lib/mozilla-ast.js new file mode 100644 index 0000000..3e0534c --- /dev/null +++ b/node_modules/uglify-js/lib/mozilla-ast.js @@ -0,0 +1,1310 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +(function() { + var MOZ_TO_ME = { + Program: function(M) { + return new AST_Toplevel({ + start: my_start_token(M), + end: my_end_token(M), + body: normalize_directives(M.body.map(from_moz)), + }); + }, + ArrowFunctionExpression: function(M) { + var argnames = [], rest = null; + M.params.forEach(function(param) { + if (param.type == "RestElement") { + rest = from_moz(param.argument); + } else { + argnames.push(from_moz(param)); + } + }); + var fn = new (M.async ? AST_AsyncArrow : AST_Arrow)({ + start: my_start_token(M), + end: my_end_token(M), + argnames: argnames, + rest: rest, + }); + var node = from_moz(M.body); + if (node instanceof AST_BlockStatement) { + fn.body = normalize_directives(node.body); + fn.value = null; + } else { + fn.body = []; + fn.value = node; + } + return fn; + }, + FunctionDeclaration: function(M) { + var ctor; + if (M.async) { + ctor = M.generator ? AST_AsyncGeneratorDefun : AST_AsyncDefun; + } else { + ctor = M.generator ? AST_GeneratorDefun : AST_Defun; + } + var argnames = [], rest = null; + M.params.forEach(function(param) { + if (param.type == "RestElement") { + rest = from_moz(param.argument); + } else { + argnames.push(from_moz(param)); + } + }); + return new ctor({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + argnames: argnames, + rest: rest, + body: normalize_directives(from_moz(M.body).body), + }); + }, + FunctionExpression: function(M) { + var ctor; + if (M.async) { + ctor = M.generator ? AST_AsyncGeneratorFunction : AST_AsyncFunction; + } else { + ctor = M.generator ? AST_GeneratorFunction : AST_Function; + } + var argnames = [], rest = null; + M.params.forEach(function(param) { + if (param.type == "RestElement") { + rest = from_moz(param.argument); + } else { + argnames.push(from_moz(param)); + } + }); + return new ctor({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + argnames: argnames, + rest: rest, + body: normalize_directives(from_moz(M.body).body), + }); + }, + ClassDeclaration: function(M) { + return new AST_DefClass({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + extends: from_moz(M.superClass), + properties: M.body.body.map(from_moz), + }); + }, + ClassExpression: function(M) { + return new AST_ClassExpression({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + extends: from_moz(M.superClass), + properties: M.body.body.map(from_moz), + }); + }, + MethodDefinition: function(M) { + var key = M.key, internal = false; + if (M.computed) { + key = from_moz(key); + } else if (key.type == "PrivateIdentifier") { + internal = true; + key = "#" + key.name; + } else { + key = read_name(key); + } + var ctor = AST_ClassMethod, value = from_moz(M.value); + switch (M.kind) { + case "get": + ctor = AST_ClassGetter; + value = new AST_Accessor(value); + break; + case "set": + ctor = AST_ClassSetter; + value = new AST_Accessor(value); + break; + } + return new ctor({ + start: my_start_token(M), + end: my_end_token(M), + key: key, + private: internal, + static: M.static, + value: value, + }); + }, + PropertyDefinition: function(M) { + var key = M.key, internal = false; + if (M.computed) { + key = from_moz(key); + } else if (key.type == "PrivateIdentifier") { + internal = true; + key = "#" + key.name; + } else { + key = read_name(key); + } + return new AST_ClassField({ + start: my_start_token(M), + end: my_end_token(M), + key: key, + private: internal, + static: M.static, + value: from_moz(M.value), + }); + }, + StaticBlock: function(M) { + var start = my_start_token(M); + var end = my_end_token(M); + return new AST_ClassInit({ + start: start, + end: end, + value: new AST_ClassInitBlock({ + start: start, + end: end, + body: normalize_directives(M.body.map(from_moz)), + }), + }); + }, + ForOfStatement: function(M) { + return new (M.await ? AST_ForAwaitOf : AST_ForOf)({ + start: my_start_token(M), + end: my_end_token(M), + init: from_moz(M.left), + object: from_moz(M.right), + body: from_moz(M.body), + }); + }, + TryStatement: function(M) { + var handlers = M.handlers || [M.handler]; + if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) { + throw new Error("Multiple catch clauses are not supported."); + } + return new AST_Try({ + start : my_start_token(M), + end : my_end_token(M), + body : from_moz(M.block).body, + bcatch : from_moz(handlers[0]), + bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null, + }); + }, + Property: function(M) { + var key = M.computed ? from_moz(M.key) : read_name(M.key); + var args = { + start: my_start_token(M), + end: my_end_token(M), + key: key, + value: from_moz(M.value), + }; + if (M.kind == "init") return new (M.method ? AST_ObjectMethod : AST_ObjectKeyVal)(args); + args.value = new AST_Accessor(args.value); + if (M.kind == "get") return new AST_ObjectGetter(args); + if (M.kind == "set") return new AST_ObjectSetter(args); + }, + ArrayExpression: function(M) { + return new AST_Array({ + start: my_start_token(M), + end: my_end_token(M), + elements: M.elements.map(function(elem) { + return elem === null ? new AST_Hole() : from_moz(elem); + }), + }); + }, + ArrayPattern: function(M) { + var elements = [], rest = null; + M.elements.forEach(function(el) { + if (el === null) { + elements.push(new AST_Hole()); + } else if (el.type == "RestElement") { + rest = from_moz(el.argument); + } else { + elements.push(from_moz(el)); + } + }); + return new AST_DestructuredArray({ + start: my_start_token(M), + end: my_end_token(M), + elements: elements, + rest: rest, + }); + }, + ObjectPattern: function(M) { + var props = [], rest = null; + M.properties.forEach(function(prop) { + if (prop.type == "RestElement") { + rest = from_moz(prop.argument); + } else { + props.push(new AST_DestructuredKeyVal(from_moz(prop))); + } + }); + return new AST_DestructuredObject({ + start: my_start_token(M), + end: my_end_token(M), + properties: props, + rest: rest, + }); + }, + MemberExpression: function(M) { + return new (M.computed ? AST_Sub : AST_Dot)({ + start: my_start_token(M), + end: my_end_token(M), + optional: M.optional, + expression: from_moz(M.object), + property: M.computed ? from_moz(M.property) : M.property.name, + }); + }, + MetaProperty: function(M) { + var expr = from_moz(M.meta); + var prop = read_name(M.property); + if (expr.name == "new" && prop == "target") return new AST_NewTarget({ + start: my_start_token(M), + end: my_end_token(M), + name: "new.target", + }); + return new AST_Dot({ + start: my_start_token(M), + end: my_end_token(M), + expression: expr, + property: prop, + }); + }, + SwitchCase: function(M) { + return new (M.test ? AST_Case : AST_Default)({ + start : my_start_token(M), + end : my_end_token(M), + expression : from_moz(M.test), + body : M.consequent.map(from_moz), + }); + }, + ExportAllDeclaration: function(M) { + var start = my_start_token(M); + var end = my_end_token(M); + return new AST_ExportForeign({ + start: start, + end: end, + aliases: [ M.exported ? from_moz_alias(M.exported) : new AST_String({ + start: start, + value: "*", + end: end, + }) ], + keys: [ new AST_String({ + start: start, + value: "*", + end: end, + }) ], + path: from_moz(M.source), + }); + }, + ExportDefaultDeclaration: function(M) { + var decl = from_moz(M.declaration); + if (!decl.name) switch (decl.CTOR) { + case AST_AsyncDefun: + decl = new AST_AsyncFunction(decl); + break; + case AST_AsyncGeneratorDefun: + decl = new AST_AsyncGeneratorFunction(decl); + break; + case AST_DefClass: + decl = new AST_ClassExpression(decl); + break; + case AST_Defun: + decl = new AST_Function(decl); + break; + case AST_GeneratorDefun: + decl = new AST_GeneratorFunction(decl); + break; + } + return new AST_ExportDefault({ + start: my_start_token(M), + end: my_end_token(M), + body: decl, + }); + }, + ExportNamedDeclaration: function(M) { + if (M.declaration) return new AST_ExportDeclaration({ + start: my_start_token(M), + end: my_end_token(M), + body: from_moz(M.declaration), + }); + if (M.source) { + var aliases = [], keys = []; + M.specifiers.forEach(function(prop) { + aliases.push(from_moz_alias(prop.exported)); + keys.push(from_moz_alias(prop.local)); + }); + return new AST_ExportForeign({ + start: my_start_token(M), + end: my_end_token(M), + aliases: aliases, + keys: keys, + path: from_moz(M.source), + }); + } + return new AST_ExportReferences({ + start: my_start_token(M), + end: my_end_token(M), + properties: M.specifiers.map(function(prop) { + var sym = new AST_SymbolExport(from_moz(prop.local)); + sym.alias = from_moz_alias(prop.exported); + return sym; + }), + }); + }, + ImportDeclaration: function(M) { + var start = my_start_token(M); + var end = my_end_token(M); + var all = null, def = null, props = null; + M.specifiers.forEach(function(prop) { + var sym = new AST_SymbolImport(from_moz(prop.local)); + switch (prop.type) { + case "ImportDefaultSpecifier": + def = sym; + def.key = new AST_String({ + start: start, + value: "", + end: end, + }); + break; + case "ImportNamespaceSpecifier": + all = sym; + all.key = new AST_String({ + start: start, + value: "*", + end: end, + }); + break; + default: + sym.key = from_moz_alias(prop.imported); + if (!props) props = []; + props.push(sym); + break; + } + }); + return new AST_Import({ + start: start, + end: end, + all: all, + default: def, + properties: props, + path: from_moz(M.source), + }); + }, + ImportExpression: function(M) { + var start = my_start_token(M); + var arg = from_moz(M.source); + return new AST_Call({ + start: start, + end: my_end_token(M), + expression: new AST_SymbolRef({ + start: start, + end: arg.start, + name: "import", + }), + args: [ arg ], + }); + }, + VariableDeclaration: function(M) { + return new ({ + const: AST_Const, + let: AST_Let, + }[M.kind] || AST_Var)({ + start: my_start_token(M), + end: my_end_token(M), + definitions: M.declarations.map(from_moz), + }); + }, + Literal: function(M) { + var args = { + start: my_start_token(M), + end: my_end_token(M), + }; + if (M.bigint) { + args.value = M.bigint.toLowerCase() + "n"; + return new AST_BigInt(args); + } + var val = M.value; + if (val === null) return new AST_Null(args); + var rx = M.regex; + if (rx && rx.pattern) { + // RegExpLiteral as per ESTree AST spec + args.value = new RegExp(rx.pattern, rx.flags); + args.value.raw_source = rx.pattern; + return new AST_RegExp(args); + } else if (rx) { + // support legacy RegExp + args.value = M.regex && M.raw ? M.raw : val; + return new AST_RegExp(args); + } + switch (typeof val) { + case "string": + args.value = val; + return new AST_String(args); + case "number": + if (isNaN(val)) return new AST_NaN(args); + var negate, node; + if (isFinite(val)) { + negate = 1 / val < 0; + args.value = negate ? -val : val; + node = new AST_Number(args); + } else { + negate = val < 0; + node = new AST_Infinity(args); + } + return negate ? new AST_UnaryPrefix({ + start: args.start, + end: args.end, + operator: "-", + expression: node, + }) : node; + case "boolean": + return new (val ? AST_True : AST_False)(args); + } + }, + TemplateLiteral: function(M) { + return new AST_Template({ + start: my_start_token(M), + end: my_end_token(M), + expressions: M.expressions.map(from_moz), + strings: M.quasis.map(function(el) { + return el.value.raw; + }), + }); + }, + TaggedTemplateExpression: function(M) { + var tmpl = from_moz(M.quasi); + tmpl.start = my_start_token(M); + tmpl.end = my_end_token(M); + tmpl.tag = from_moz(M.tag); + return tmpl; + }, + Identifier: function(M) { + var p, level = FROM_MOZ_STACK.length - 1; + do { + p = FROM_MOZ_STACK[--level]; + } while (p.type == "ArrayPattern" + || p.type == "AssignmentPattern" && p.left === FROM_MOZ_STACK[level + 1] + || p.type == "ObjectPattern" + || p.type == "Property" && p.value === FROM_MOZ_STACK[level + 1] + || p.type == "VariableDeclarator" && p.id === FROM_MOZ_STACK[level + 1]); + var ctor = AST_SymbolRef; + switch (p.type) { + case "ArrowFunctionExpression": + if (p.body !== FROM_MOZ_STACK[level + 1]) ctor = AST_SymbolFunarg; + break; + case "BreakStatement": + case "ContinueStatement": + ctor = AST_LabelRef; + break; + case "CatchClause": + ctor = AST_SymbolCatch; + break; + case "ClassDeclaration": + if (p.id === FROM_MOZ_STACK[level + 1]) ctor = AST_SymbolDefClass; + break; + case "ClassExpression": + if (p.id === FROM_MOZ_STACK[level + 1]) ctor = AST_SymbolClass; + break; + case "FunctionDeclaration": + ctor = p.id === FROM_MOZ_STACK[level + 1] ? AST_SymbolDefun : AST_SymbolFunarg; + break; + case "FunctionExpression": + ctor = p.id === FROM_MOZ_STACK[level + 1] ? AST_SymbolLambda : AST_SymbolFunarg; + break; + case "LabeledStatement": + ctor = AST_Label; + break; + case "VariableDeclaration": + ctor = { + const: AST_SymbolConst, + let: AST_SymbolLet, + }[p.kind] || AST_SymbolVar; + break; + } + return new ctor({ + start: my_start_token(M), + end: my_end_token(M), + name: M.name, + }); + }, + Super: function(M) { + return new AST_Super({ + start: my_start_token(M), + end: my_end_token(M), + name: "super", + }); + }, + ThisExpression: function(M) { + return new AST_This({ + start: my_start_token(M), + end: my_end_token(M), + name: "this", + }); + }, + ParenthesizedExpression: function(M) { + var node = from_moz(M.expression); + if (!node.start.parens) node.start.parens = []; + node.start.parens.push(my_start_token(M)); + if (!node.end.parens) node.end.parens = []; + node.end.parens.push(my_end_token(M)); + return node; + }, + ChainExpression: function(M) { + var node = from_moz(M.expression); + node.terminal = true; + return node; + }, + }; + + MOZ_TO_ME.UpdateExpression = + MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) { + var prefix = "prefix" in M ? M.prefix + : M.type == "UnaryExpression" ? true : false; + return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({ + start : my_start_token(M), + end : my_end_token(M), + operator : M.operator, + expression : from_moz(M.argument) + }); + }; + + map("EmptyStatement", AST_EmptyStatement); + map("ExpressionStatement", AST_SimpleStatement, "expression>body"); + map("BlockStatement", AST_BlockStatement, "body@body"); + map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative"); + map("LabeledStatement", AST_LabeledStatement, "label>label, body>body"); + map("BreakStatement", AST_Break, "label>label"); + map("ContinueStatement", AST_Continue, "label>label"); + map("WithStatement", AST_With, "object>expression, body>body"); + map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body"); + map("ReturnStatement", AST_Return, "argument>value"); + map("ThrowStatement", AST_Throw, "argument>value"); + map("WhileStatement", AST_While, "test>condition, body>body"); + map("DoWhileStatement", AST_Do, "test>condition, body>body"); + map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body"); + map("ForInStatement", AST_ForIn, "left>init, right>object, body>body"); + map("DebuggerStatement", AST_Debugger); + map("VariableDeclarator", AST_VarDef, "id>name, init>value"); + map("CatchClause", AST_Catch, "param>argname, body%body"); + + map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right"); + map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right"); + map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right"); + map("AssignmentPattern", AST_DefaultValue, "left>name, right>value"); + map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative"); + map("NewExpression", AST_New, "callee>expression, arguments@args, pure=pure"); + map("CallExpression", AST_Call, "callee>expression, arguments@args, optional=optional, pure=pure"); + map("SequenceExpression", AST_Sequence, "expressions@expressions"); + map("SpreadElement", AST_Spread, "argument>expression"); + map("ObjectExpression", AST_Object, "properties@properties"); + map("AwaitExpression", AST_Await, "argument>expression"); + map("YieldExpression", AST_Yield, "argument>expression, delegate=nested"); + + def_to_moz(AST_Toplevel, function To_Moz_Program(M) { + return to_moz_scope("Program", M); + }); + + def_to_moz(AST_LambdaDefinition, function To_Moz_FunctionDeclaration(M) { + var params = M.argnames.map(to_moz); + if (M.rest) params.push({ + type: "RestElement", + argument: to_moz(M.rest), + }); + return { + type: "FunctionDeclaration", + id: to_moz(M.name), + async: is_async(M), + generator: is_generator(M), + params: params, + body: to_moz_scope("BlockStatement", M), + }; + }); + + def_to_moz(AST_Lambda, function To_Moz_FunctionExpression(M) { + var params = M.argnames.map(to_moz); + if (M.rest) params.push({ + type: "RestElement", + argument: to_moz(M.rest), + }); + if (is_arrow(M)) return { + type: "ArrowFunctionExpression", + async: is_async(M), + params: params, + body: M.value ? to_moz(M.value) : to_moz_scope("BlockStatement", M), + }; + return { + type: "FunctionExpression", + id: to_moz(M.name), + async: is_async(M), + generator: is_generator(M), + params: params, + body: to_moz_scope("BlockStatement", M), + }; + }); + + def_to_moz(AST_DefClass, function To_Moz_ClassDeclaration(M) { + return { + type: "ClassDeclaration", + id: to_moz(M.name), + superClass: to_moz(M.extends), + body: { + type: "ClassBody", + body: M.properties.map(to_moz), + }, + }; + }); + + def_to_moz(AST_ClassExpression, function To_Moz_ClassExpression(M) { + return { + type: "ClassExpression", + id: to_moz(M.name), + superClass: to_moz(M.extends), + body: { + type: "ClassBody", + body: M.properties.map(to_moz), + }, + }; + }); + + function To_Moz_MethodDefinition(kind) { + return function(M) { + var computed = M.key instanceof AST_Node; + var key = computed ? to_moz(M.key) : M.private ? { + type: "PrivateIdentifier", + name: M.key.slice(1), + } : { + type: "Literal", + value: M.key, + }; + return { + type: "MethodDefinition", + kind: kind, + computed: computed, + key: key, + static: M.static, + value: to_moz(M.value), + }; + }; + } + def_to_moz(AST_ClassGetter, To_Moz_MethodDefinition("get")); + def_to_moz(AST_ClassSetter, To_Moz_MethodDefinition("set")); + def_to_moz(AST_ClassMethod, To_Moz_MethodDefinition("method")); + + def_to_moz(AST_ClassField, function To_Moz_PropertyDefinition(M) { + var computed = M.key instanceof AST_Node; + var key = computed ? to_moz(M.key) : M.private ? { + type: "PrivateIdentifier", + name: M.key.slice(1), + } : { + type: "Literal", + value: M.key, + }; + return { + type: "PropertyDefinition", + computed: computed, + key: key, + static: M.static, + value: to_moz(M.value), + }; + }); + + def_to_moz(AST_ClassInit, function To_Moz_StaticBlock(M) { + return to_moz_scope("StaticBlock", M.value); + }); + + function To_Moz_ForOfStatement(is_await) { + return function(M) { + return { + type: "ForOfStatement", + await: is_await, + left: to_moz(M.init), + right: to_moz(M.object), + body: to_moz(M.body), + }; + }; + } + def_to_moz(AST_ForAwaitOf, To_Moz_ForOfStatement(true)); + def_to_moz(AST_ForOf, To_Moz_ForOfStatement(false)); + + def_to_moz(AST_Directive, function To_Moz_Directive(M) { + return { + type: "ExpressionStatement", + expression: set_moz_loc(M, { + type: "Literal", + value: M.value, + }), + }; + }); + + def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) { + return { + type: "SwitchCase", + test: to_moz(M.expression), + consequent: M.body.map(to_moz), + }; + }); + + def_to_moz(AST_Try, function To_Moz_TryStatement(M) { + return { + type: "TryStatement", + block: to_moz_block(M), + handler: to_moz(M.bcatch), + guardedHandlers: [], + finalizer: to_moz(M.bfinally), + }; + }); + + def_to_moz(AST_Catch, function To_Moz_CatchClause(M) { + return { + type: "CatchClause", + param: to_moz(M.argname), + guard: null, + body: to_moz_block(M), + }; + }); + + def_to_moz(AST_ExportDeclaration, function To_Moz_ExportNamedDeclaration_declaration(M) { + return { + type: "ExportNamedDeclaration", + declaration: to_moz(M.body), + }; + }); + + def_to_moz(AST_ExportDefault, function To_Moz_ExportDefaultDeclaration(M) { + return { + type: "ExportDefaultDeclaration", + declaration: to_moz(M.body), + }; + }); + + def_to_moz(AST_ExportForeign, function To_Moz_ExportAllDeclaration_ExportNamedDeclaration(M) { + if (M.keys[0].value == "*") return { + type: "ExportAllDeclaration", + exported: M.aliases[0].value == "*" ? null : to_moz_alias(M.aliases[0]), + source: to_moz(M.path), + }; + var specifiers = []; + for (var i = 0; i < M.aliases.length; i++) { + specifiers.push(set_moz_loc({ + start: M.keys[i].start, + end: M.aliases[i].end, + }, { + type: "ExportSpecifier", + local: to_moz_alias(M.keys[i]), + exported: to_moz_alias(M.aliases[i]), + })); + } + return { + type: "ExportNamedDeclaration", + specifiers: specifiers, + source: to_moz(M.path), + }; + }); + + def_to_moz(AST_ExportReferences, function To_Moz_ExportNamedDeclaration_specifiers(M) { + return { + type: "ExportNamedDeclaration", + specifiers: M.properties.map(function(prop) { + return set_moz_loc({ + start: prop.start, + end: prop.alias.end, + }, { + type: "ExportSpecifier", + local: to_moz(prop), + exported: to_moz_alias(prop.alias), + }); + }), + }; + }); + + def_to_moz(AST_Import, function To_Moz_ImportDeclaration(M) { + var specifiers = M.properties ? M.properties.map(function(prop) { + return set_moz_loc({ + start: prop.key.start, + end: prop.end, + }, { + type: "ImportSpecifier", + local: to_moz(prop), + imported: to_moz_alias(prop.key), + }); + }) : []; + if (M.all) specifiers.unshift(set_moz_loc(M.all, { + type: "ImportNamespaceSpecifier", + local: to_moz(M.all), + })); + if (M.default) specifiers.unshift(set_moz_loc(M.default, { + type: "ImportDefaultSpecifier", + local: to_moz(M.default), + })); + return { + type: "ImportDeclaration", + specifiers: specifiers, + source: to_moz(M.path), + }; + }); + + def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) { + return { + type: "VariableDeclaration", + kind: M.TYPE.toLowerCase(), + declarations: M.definitions.map(to_moz), + }; + }); + + def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) { + var computed = M instanceof AST_Sub; + var expr = { + type: "MemberExpression", + object: to_moz(M.expression), + computed: computed, + optional: M.optional, + property: computed ? to_moz(M.property) : { + type: "Identifier", + name: M.property, + }, + }; + return M.terminal ? { + type: "ChainExpression", + expression: expr, + } : expr; + }); + + def_to_moz(AST_Unary, function To_Moz_Unary(M) { + return { + type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression", + operator: M.operator, + prefix: M instanceof AST_UnaryPrefix, + argument: to_moz(M.expression) + }; + }); + + def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) { + return { + type: M.operator == "&&" || M.operator == "||" ? "LogicalExpression" : "BinaryExpression", + left: to_moz(M.left), + operator: M.operator, + right: to_moz(M.right) + }; + }); + + def_to_moz(AST_Array, function To_Moz_ArrayExpression(M) { + return { + type: "ArrayExpression", + elements: M.elements.map(to_moz), + }; + }); + + def_to_moz(AST_DestructuredArray, function To_Moz_ArrayPattern(M) { + var elements = M.elements.map(to_moz); + if (M.rest) elements.push({ + type: "RestElement", + argument: to_moz(M.rest), + }); + return { + type: "ArrayPattern", + elements: elements, + }; + }); + + def_to_moz(AST_DestructuredKeyVal, function To_Moz_Property(M) { + var computed = M.key instanceof AST_Node; + var key = computed ? to_moz(M.key) : { + type: "Literal", + value: M.key, + }; + return { + type: "Property", + kind: "init", + computed: computed, + key: key, + value: to_moz(M.value), + }; + }); + + def_to_moz(AST_DestructuredObject, function To_Moz_ObjectPattern(M) { + var props = M.properties.map(to_moz); + if (M.rest) props.push({ + type: "RestElement", + argument: to_moz(M.rest), + }); + return { + type: "ObjectPattern", + properties: props, + }; + }); + + def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) { + var computed = M.key instanceof AST_Node; + var key = computed ? to_moz(M.key) : { + type: "Literal", + value: M.key, + }; + var kind; + if (M instanceof AST_ObjectKeyVal) { + kind = "init"; + } else if (M instanceof AST_ObjectGetter) { + kind = "get"; + } else if (M instanceof AST_ObjectSetter) { + kind = "set"; + } + return { + type: "Property", + kind: kind, + computed: computed, + method: M instanceof AST_ObjectMethod, + key: key, + value: to_moz(M.value), + }; + }); + + def_to_moz(AST_Symbol, function To_Moz_Identifier(M) { + var def = M.definition(); + return { + type: "Identifier", + name: def && def.mangled_name || M.name, + }; + }); + + def_to_moz(AST_Super, function To_Moz_Super() { + return { type: "Super" }; + }); + + def_to_moz(AST_This, function To_Moz_ThisExpression() { + return { type: "ThisExpression" }; + }); + + def_to_moz(AST_NewTarget, function To_Moz_MetaProperty() { + return { + type: "MetaProperty", + meta: { + type: "Identifier", + name: "new", + }, + property: { + type: "Identifier", + name: "target", + }, + }; + }); + + def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) { + var flags = M.value.toString().match(/\/([gimuy]*)$/)[1]; + var value = "/" + M.value.raw_source + "/" + flags; + return { + type: "Literal", + value: value, + raw: value, + regex: { + pattern: M.value.raw_source, + flags: flags, + }, + }; + }); + + def_to_moz(AST_BigInt, function To_Moz_BigInt(M) { + var value = M.value; + return { + type: "Literal", + bigint: value.slice(0, -1), + raw: value, + }; + }); + + function To_Moz_Literal(M) { + var value = M.value; + if (typeof value === "number" && (value < 0 || (value === 0 && 1 / value < 0))) { + return { + type: "UnaryExpression", + operator: "-", + prefix: true, + argument: { + type: "Literal", + value: -value, + raw: M.start.raw, + }, + }; + } + return { + type: "Literal", + value: value, + raw: M.start.raw, + }; + } + def_to_moz(AST_Boolean, To_Moz_Literal); + def_to_moz(AST_Constant, To_Moz_Literal); + def_to_moz(AST_Null, To_Moz_Literal); + + def_to_moz(AST_Atom, function To_Moz_Atom(M) { + return { + type: "Identifier", + name: String(M.value), + }; + }); + + def_to_moz(AST_Template, function To_Moz_TemplateLiteral_TaggedTemplateExpression(M) { + var last = M.strings.length - 1; + var tmpl = { + type: "TemplateLiteral", + expressions: M.expressions.map(to_moz), + quasis: M.strings.map(function(str, index) { + return { + type: "TemplateElement", + tail: index == last, + value: { raw: str }, + }; + }), + }; + if (!M.tag) return tmpl; + return { + type: "TaggedTemplateExpression", + tag: to_moz(M.tag), + quasi: tmpl, + }; + }); + + AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast); + AST_Hole.DEFMETHOD("to_mozilla_ast", return_null); + AST_Node.DEFMETHOD("to_mozilla_ast", function() { + throw new Error("Cannot convert AST_" + this.TYPE); + }); + + /* -----[ tools ]----- */ + + function normalize_directives(body) { + for (var i = 0; i < body.length; i++) { + var stat = body[i]; + if (!(stat instanceof AST_SimpleStatement)) break; + var node = stat.body; + if (!(node instanceof AST_String)) break; + if (stat.start.pos !== node.start.pos) break; + body[i] = new AST_Directive(node); + } + return body; + } + + function raw_token(moznode) { + if (moznode.type == "Literal") { + return moznode.raw != null ? moznode.raw : moznode.value + ""; + } + } + + function my_start_token(moznode) { + var loc = moznode.loc, start = loc && loc.start; + var range = moznode.range; + return new AST_Token({ + file : loc && loc.source, + line : start && start.line, + col : start && start.column, + pos : range ? range[0] : moznode.start, + endline : start && start.line, + endcol : start && start.column, + endpos : range ? range[0] : moznode.start, + raw : raw_token(moznode), + }); + } + + function my_end_token(moznode) { + var loc = moznode.loc, end = loc && loc.end; + var range = moznode.range; + return new AST_Token({ + file : loc && loc.source, + line : end && end.line, + col : end && end.column, + pos : range ? range[1] : moznode.end, + endline : end && end.line, + endcol : end && end.column, + endpos : range ? range[1] : moznode.end, + raw : raw_token(moznode), + }); + } + + function read_name(M) { + return "" + M[M.type == "Identifier" ? "name" : "value"]; + } + + function map(moztype, mytype, propmap) { + var moz_to_me = [ + "start: my_start_token(M)", + "end: my_end_token(M)", + ]; + var me_to_moz = [ + "type: " + JSON.stringify(moztype), + ]; + + if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop) { + var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop); + if (!m) throw new Error("Can't understand property map: " + prop); + var moz = m[1], how = m[2], my = m[3]; + switch (how) { + case "@": + moz_to_me.push(my + ": M." + moz + ".map(from_moz)"); + me_to_moz.push(moz + ": M." + my + ".map(to_moz)"); + break; + case ">": + moz_to_me.push(my + ": from_moz(M." + moz + ")"); + me_to_moz.push(moz + ": to_moz(M." + my + ")"); + break; + case "=": + moz_to_me.push(my + ": M." + moz); + me_to_moz.push(moz + ": M." + my); + break; + case "%": + moz_to_me.push(my + ": from_moz(M." + moz + ").body"); + me_to_moz.push(moz + ": to_moz_block(M)"); + break; + default: + throw new Error("Can't understand operator in propmap: " + prop); + } + }); + + MOZ_TO_ME[moztype] = new Function("U2", "my_start_token", "my_end_token", "from_moz", [ + "return function From_Moz_" + moztype + "(M) {", + " return new U2.AST_" + mytype.TYPE + "({", + moz_to_me.join(",\n"), + " });", + "};", + ].join("\n"))(exports, my_start_token, my_end_token, from_moz); + def_to_moz(mytype, new Function("to_moz", "to_moz_block", "to_moz_scope", [ + "return function To_Moz_" + moztype + "(M) {", + " return {", + me_to_moz.join(",\n"), + " };", + "};", + ].join("\n"))(to_moz, to_moz_block, to_moz_scope)); + } + + var FROM_MOZ_STACK = null; + + function from_moz(moz) { + FROM_MOZ_STACK.push(moz); + var node = null; + if (moz) { + if (!HOP(MOZ_TO_ME, moz.type)) throw new Error("Unsupported type: " + moz.type); + node = MOZ_TO_ME[moz.type](moz); + } + FROM_MOZ_STACK.pop(); + return node; + } + + function from_moz_alias(moz) { + return new AST_String({ + start: my_start_token(moz), + value: read_name(moz), + end: my_end_token(moz), + }); + } + + AST_Node.from_mozilla_ast = function(node) { + var save_stack = FROM_MOZ_STACK; + FROM_MOZ_STACK = []; + var ast = from_moz(node); + FROM_MOZ_STACK = save_stack; + ast.walk(new TreeWalker(function(node) { + if (node instanceof AST_LabelRef) { + for (var level = 0, parent; parent = this.parent(level); level++) { + if (parent instanceof AST_Scope) break; + if (parent instanceof AST_LabeledStatement && parent.label.name == node.name) { + node.thedef = parent.label; + break; + } + } + if (!node.thedef) { + var s = node.start; + js_error("Undefined label " + node.name, s.file, s.line, s.col, s.pos); + } + } + })); + return ast; + }; + + function set_moz_loc(mynode, moznode) { + var start = mynode.start; + var end = mynode.end; + if (start.pos != null && end.endpos != null) { + moznode.range = [start.pos, end.endpos]; + } + if (start.line) { + moznode.loc = { + start: {line: start.line, column: start.col}, + end: end.endline ? {line: end.endline, column: end.endcol} : null, + }; + if (start.file) { + moznode.loc.source = start.file; + } + } + return moznode; + } + + function def_to_moz(mytype, handler) { + mytype.DEFMETHOD("to_mozilla_ast", function() { + return set_moz_loc(this, handler(this)); + }); + } + + function to_moz(node) { + return node != null ? node.to_mozilla_ast() : null; + } + + function to_moz_alias(alias) { + return is_identifier_string(alias.value) ? set_moz_loc(alias, { + type: "Identifier", + name: alias.value, + }) : to_moz(alias); + } + + function to_moz_block(node) { + return { + type: "BlockStatement", + body: node.body.map(to_moz), + }; + } + + function to_moz_scope(type, node) { + var body = node.body.map(to_moz); + if (node.body[0] instanceof AST_SimpleStatement && node.body[0].body instanceof AST_String) { + body.unshift(to_moz(new AST_EmptyStatement(node.body[0]))); + } + return { + type: type, + body: body, + }; + } +})(); diff --git a/node_modules/uglify-js/lib/output.js b/node_modules/uglify-js/lib/output.js new file mode 100644 index 0000000..7e93d05 --- /dev/null +++ b/node_modules/uglify-js/lib/output.js @@ -0,0 +1,1956 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function is_some_comments(comment) { + // multiline comment + return comment.type == "comment2" && /@preserve|@license|@cc_on/i.test(comment.value); +} + +function OutputStream(options) { + options = defaults(options, { + annotations : false, + ascii_only : false, + beautify : false, + braces : false, + comments : false, + extendscript : false, + galio : false, + ie : false, + indent_level : 4, + indent_start : 0, + inline_script : true, + keep_quoted_props: false, + max_line_len : false, + preamble : null, + preserve_line : false, + quote_keys : false, + quote_style : 0, + semicolons : true, + shebang : true, + source_map : null, + v8 : false, + webkit : false, + width : 80, + wrap_iife : false, + }, true); + + // Convert comment option to RegExp if necessary and set up comments filter + var comment_filter = return_false; // Default case, throw all comments away + if (options.comments) { + var comments = options.comments; + if (typeof options.comments === "string" && /^\/.*\/[a-zA-Z]*$/.test(options.comments)) { + var regex_pos = options.comments.lastIndexOf("/"); + comments = new RegExp( + options.comments.substr(1, regex_pos - 1), + options.comments.substr(regex_pos + 1) + ); + } + if (comments instanceof RegExp) { + comment_filter = function(comment) { + return comment.type != "comment5" && comments.test(comment.value); + }; + } else if (typeof comments === "function") { + comment_filter = function(comment) { + return comment.type != "comment5" && comments(this, comment); + }; + } else if (comments === "some") { + comment_filter = is_some_comments; + } else { // NOTE includes "all" option + comment_filter = return_true; + } + } + + function make_indent(value) { + if (typeof value == "number") return new Array(value + 1).join(" "); + if (!value) return ""; + if (!/^\s*$/.test(value)) throw new Error("unsupported indentation: " + JSON.stringify("" + value)); + return value; + } + + var current_col = 0; + var current_line = 1; + var current_indent = make_indent(options.indent_start); + var full_indent = make_indent(options.indent_level); + var half_indent = full_indent.length + 1 >> 1; + var last; + var line_end = 0; + var line_fixed = true; + var mappings = options.source_map && []; + var mapping_name; + var mapping_token; + var might_need_space; + var might_need_semicolon; + var need_newline_indented = false; + var need_space = false; + var output; + var stack; + var stored = ""; + + function reset() { + last = ""; + might_need_space = false; + might_need_semicolon = false; + stack = []; + var str = output; + output = ""; + return str; + } + + reset(); + var to_utf8 = options.ascii_only ? function(str, identifier) { + if (identifier) str = str.replace(/[\ud800-\udbff][\udc00-\udfff]/g, function(ch) { + return "\\u{" + (ch.charCodeAt(0) - 0xd7c0 << 10 | ch.charCodeAt(1) - 0xdc00).toString(16) + "}"; + }); + return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) { + var code = ch.charCodeAt(0).toString(16); + if (code.length <= 2 && !identifier) { + while (code.length < 2) code = "0" + code; + return "\\x" + code; + } else { + while (code.length < 4) code = "0" + code; + return "\\u" + code; + } + }); + } : function(str) { + var s = ""; + for (var i = 0, j = 0; i < str.length; i++) { + var code = str.charCodeAt(i); + if (is_surrogate_pair_head(code)) { + if (is_surrogate_pair_tail(str.charCodeAt(i + 1))) { + i++; + continue; + } + } else if (!is_surrogate_pair_tail(code)) { + continue; + } + s += str.slice(j, i) + "\\u" + code.toString(16); + j = i + 1; + } + return j == 0 ? str : s + str.slice(j); + }; + + function quote_single(str) { + return "'" + str.replace(/\x27/g, "\\'") + "'"; + } + + function quote_double(str) { + return '"' + str.replace(/\x22/g, '\\"') + '"'; + } + + var quote_string = [ + null, + quote_single, + quote_double, + function(str, quote) { + return quote == "'" ? quote_single(str) : quote_double(str); + }, + ][options.quote_style] || function(str, quote, dq, sq) { + return dq > sq ? quote_single(str) : quote_double(str); + }; + + function make_string(str, quote) { + var dq = 0, sq = 0; + str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g, function(s, i) { + switch (s) { + case '"': ++dq; return '"'; + case "'": ++sq; return "'"; + case "\\": return "\\\\"; + case "\n": return "\\n"; + case "\r": return "\\r"; + case "\t": return "\\t"; + case "\b": return "\\b"; + case "\f": return "\\f"; + case "\x0B": return options.ie ? "\\x0B" : "\\v"; + case "\u2028": return "\\u2028"; + case "\u2029": return "\\u2029"; + case "\ufeff": return "\\ufeff"; + case "\0": + return /[0-9]/.test(str.charAt(i+1)) ? "\\x00" : "\\0"; + } + return s; + }); + return quote_string(to_utf8(str), quote, dq, sq); + } + + /* -----[ beautification/minification ]----- */ + + var adjust_mappings = mappings ? function(line, col) { + mappings.forEach(function(mapping) { + mapping.line += line; + mapping.col += col; + }); + } : noop; + + var flush_mappings = mappings ? function() { + mappings.forEach(function(mapping) { + options.source_map.add( + mapping.token.file, + mapping.line, mapping.col, + mapping.token.line, mapping.token.col, + !mapping.name && mapping.token.type == "name" ? mapping.token.value : mapping.name + ); + }); + mappings = []; + } : noop; + + function insert_newlines(count) { + stored += output.slice(0, line_end); + output = output.slice(line_end); + var new_col = output.length; + adjust_mappings(count, new_col - current_col); + current_line += count; + current_col = new_col; + while (count--) stored += "\n"; + } + + var fix_line = options.max_line_len ? function(flush) { + if (line_fixed) { + if (current_col > options.max_line_len) { + AST_Node.warn("Output exceeds {max_line_len} characters", options); + } + return; + } + if (current_col > options.max_line_len) { + insert_newlines(1); + line_fixed = true; + } + if (line_fixed || flush) flush_mappings(); + } : noop; + + var require_semicolon = makePredicate("( [ + * / - , ."); + + function require_space(prev, ch, str) { + return is_identifier_char(prev) && (is_identifier_char(ch) || ch == "\\") + || (ch == "/" && ch == prev) + || ((ch == "+" || ch == "-") && ch == last) + || last == "--" && ch == ">" + || last == "!" && str == "--" + || prev == "/" && (str == "in" || str == "instanceof"); + } + + var print = options.beautify + || options.comments + || options.max_line_len + || options.preserve_line + || options.shebang + || !options.semicolons + || options.source_map + || options.width ? function(str) { + var ch = str.charAt(0); + if (need_newline_indented && ch) { + need_newline_indented = false; + if (ch != "\n") { + print("\n"); + indent(); + } + } + if (need_space && ch) { + need_space = false; + if (!/[\s;})]/.test(ch)) { + space(); + } + } + var prev = last.slice(-1); + if (might_need_semicolon) { + might_need_semicolon = false; + if (prev == ":" && ch == "}" || prev != ";" && (!ch || ";}".indexOf(ch) < 0)) { + var need_semicolon = require_semicolon[ch]; + if (need_semicolon || options.semicolons) { + output += ";"; + current_col++; + if (!line_fixed) { + fix_line(); + if (line_fixed && !need_semicolon && output == ";") { + output = ""; + current_col = 0; + } + } + if (line_end == output.length - 1) line_end++; + } else { + fix_line(); + output += "\n"; + current_line++; + current_col = 0; + // reset the semicolon flag, since we didn't print one + // now and might still have to later + if (/^\s+$/.test(str)) might_need_semicolon = true; + } + if (!options.beautify) might_need_space = false; + } + } + + if (might_need_space) { + if (require_space(prev, ch, str)) { + output += " "; + current_col++; + } + if (prev != "<" || str != "!") might_need_space = false; + } + + if (mapping_token) { + mappings.push({ + token: mapping_token, + name: mapping_name, + line: current_line, + col: current_col, + }); + mapping_token = false; + if (line_fixed) flush_mappings(); + } + + output += str; + var a = str.split(/\r?\n/), n = a.length - 1; + current_line += n; + current_col += a[0].length; + if (n > 0) { + fix_line(); + current_col = a[n].length; + } + last = str; + } : function(str) { + var ch = str.charAt(0); + var prev = last.slice(-1); + if (might_need_semicolon) { + might_need_semicolon = false; + if (prev == ":" && ch == "}" || (!ch || ";}".indexOf(ch) < 0) && prev != ";") { + output += ";"; + might_need_space = false; + } + } + if (might_need_space) { + if (require_space(prev, ch, str)) output += " "; + if (prev != "<" || str != "!") might_need_space = false; + } + output += str; + last = str; + }; + + var space = options.beautify ? function() { + print(" "); + } : function() { + might_need_space = true; + }; + + var indent = options.beautify ? function(half) { + if (need_newline_indented) print("\n"); + print(half ? current_indent.slice(0, -half_indent) : current_indent); + } : noop; + + var with_indent = options.beautify ? function(cont) { + var save_indentation = current_indent; + current_indent += full_indent; + cont(); + current_indent = save_indentation; + } : function(cont) { cont() }; + + var may_add_newline = options.max_line_len || options.preserve_line ? function() { + fix_line(); + line_end = output.length; + line_fixed = false; + } : noop; + + var newline = options.beautify ? function() { + print("\n"); + line_end = output.length; + } : may_add_newline; + + var semicolon = options.beautify ? function() { + print(";"); + } : function() { + might_need_semicolon = true; + }; + + function force_semicolon() { + if (might_need_semicolon) print(";"); + print(";"); + } + + function with_block(cont, end) { + print("{"); + newline(); + with_indent(cont); + add_mapping(end); + indent(); + print("}"); + } + + function with_parens(cont) { + print("("); + may_add_newline(); + cont(); + may_add_newline(); + print(")"); + } + + function with_square(cont) { + print("["); + may_add_newline(); + cont(); + may_add_newline(); + print("]"); + } + + function comma() { + may_add_newline(); + print(","); + may_add_newline(); + space(); + } + + function colon() { + print(":"); + space(); + } + + var add_mapping = mappings ? function(token, name) { + mapping_token = token; + mapping_name = name; + } : noop; + + function get() { + if (!line_fixed) fix_line(true); + return stored + output; + } + + function has_nlb() { + return /(^|\n) *$/.test(output); + } + + function pad_comment(token, force) { + if (need_newline_indented) return; + if (token.nlb && (force || !has_nlb())) { + need_newline_indented = true; + } else if (force) { + need_space = true; + } + } + + function print_comment(comment) { + var value = comment.value.replace(/[@#]__PURE__/g, " "); + if (/^\s*$/.test(value) && !/^\s*$/.test(comment.value)) return false; + if (/comment[134]/.test(comment.type)) { + print("//" + value); + need_newline_indented = true; + } else if (comment.type == "comment2") { + print("/*" + value + "*/"); + } + return true; + } + + function should_merge_comments(node, parent) { + if (parent instanceof AST_Binary) return parent.left === node; + if (parent.TYPE == "Call") return parent.expression === node; + if (parent instanceof AST_Conditional) return parent.condition === node; + if (parent instanceof AST_Dot) return parent.expression === node; + if (parent instanceof AST_Exit) return true; + if (parent instanceof AST_Sequence) return parent.expressions[0] === node; + if (parent instanceof AST_Sub) return parent.expression === node; + if (parent instanceof AST_UnaryPostfix) return true; + if (parent instanceof AST_Yield) return true; + } + + function prepend_comments(node) { + var self = this; + var scan; + if (node instanceof AST_Exit) { + scan = node.value; + } else if (node instanceof AST_Yield) { + scan = node.expression; + } + var comments = dump(node); + if (!comments) comments = []; + + if (scan) { + var tw = new TreeWalker(function(node) { + if (!should_merge_comments(node, tw.parent())) return true; + var before = dump(node); + if (before) comments = comments.concat(before); + }); + tw.push(node); + scan.walk(tw); + } + + if (current_line == 1 && current_col == 0) { + if (comments.length > 0 && options.shebang && comments[0].type == "comment5") { + print("#!" + comments.shift().value + "\n"); + indent(); + } + var preamble = options.preamble; + if (preamble) print(preamble.replace(/\r\n?|\u2028|\u2029|(^|\S)\s*$/g, "$1\n")); + } + + comments = comments.filter(comment_filter, node); + var printed = false; + comments.forEach(function(comment, index) { + pad_comment(comment, index); + if (print_comment(comment)) printed = true; + }); + if (printed) pad_comment(node.start, true); + + function dump(node) { + var token = node.start; + if (!token) { + if (!scan) return; + node.start = token = new AST_Token(); + } + var comments = token.comments_before; + if (!comments) { + if (!scan) return; + token.comments_before = comments = []; + } + if (comments._dumped === self) return; + comments._dumped = self; + return comments; + } + } + + function append_comments(node, tail) { + var self = this; + var token = node.end; + if (!token) return; + var comments = token[tail ? "comments_before" : "comments_after"]; + if (!comments || comments._dumped === self) return; + if (!(node instanceof AST_Statement || all(comments, function(c) { + return !/comment[134]/.test(c.type); + }))) return; + comments._dumped = self; + comments.filter(comment_filter, node).forEach(function(comment, index) { + pad_comment(comment, index || !tail); + print_comment(comment); + }); + } + + return { + get : get, + reset : reset, + indent : indent, + should_break : options.beautify && options.width ? function() { + return current_col >= options.width; + } : return_false, + has_parens : function() { return last.slice(-1) == "(" }, + newline : newline, + print : print, + space : space, + comma : comma, + colon : colon, + last : function() { return last }, + semicolon : semicolon, + force_semicolon : force_semicolon, + to_utf8 : to_utf8, + print_name : function(name) { print(to_utf8(name.toString(), true)) }, + print_string : options.inline_script ? function(str, quote) { + str = make_string(str, quote).replace(/<\x2f(script)([>\/\t\n\f\r ])/gi, "<\\/$1$2"); + print(str.replace(/\x3c!--/g, "\\x3c!--").replace(/--\x3e/g, "--\\x3e")); + } : function(str, quote) { + print(make_string(str, quote)); + }, + with_indent : with_indent, + with_block : with_block, + with_parens : with_parens, + with_square : with_square, + add_mapping : add_mapping, + option : function(opt) { return options[opt] }, + prepend_comments: options.comments || options.shebang ? prepend_comments : noop, + append_comments : options.comments ? append_comments : noop, + push_node : function(node) { stack.push(node) }, + pop_node : options.preserve_line ? function() { + var node = stack.pop(); + if (node.start && node.start.line > current_line) { + insert_newlines(node.start.line - current_line); + } + } : function() { + stack.pop(); + }, + parent : function(n) { + return stack[stack.length - 2 - (n || 0)]; + }, + }; +} + +/* -----[ code generators ]----- */ + +(function() { + + /* -----[ utils ]----- */ + + function DEFPRINT(nodetype, generator) { + nodetype.DEFMETHOD("_codegen", generator); + } + + var use_asm = false; + + AST_Node.DEFMETHOD("print", function(stream, force_parens) { + var self = this; + stream.push_node(self); + if (force_parens || self.needs_parens(stream)) { + stream.with_parens(doit); + } else { + doit(); + } + stream.pop_node(); + + function doit() { + stream.prepend_comments(self); + self.add_source_map(stream); + self._codegen(stream); + stream.append_comments(self); + } + }); + var readonly = OutputStream({ + inline_script: false, + shebang: false, + width: false, + }); + AST_Node.DEFMETHOD("print_to_string", function(options) { + if (options) { + var stream = OutputStream(options); + this.print(stream); + return stream.get(); + } + this.print(readonly); + return readonly.reset(); + }); + + /* -----[ PARENTHESES ]----- */ + + function PARENS(nodetype, func) { + nodetype.DEFMETHOD("needs_parens", func); + } + + PARENS(AST_Node, return_false); + + // a function expression needs parens around it when it's provably + // the first token to appear in a statement. + function needs_parens_function(output) { + var p = output.parent(); + if (!output.has_parens() && first_in_statement(output, false, true)) { + // export default function() {} + // export default (function foo() {}); + // export default (function() {})(foo); + // export default (function() {})`foo`; + // export default (function() {}) ? foo : bar; + return this.name || !(p instanceof AST_ExportDefault); + } + if (output.option("webkit") && p instanceof AST_PropAccess && p.expression === this) return true; + if (output.option("wrap_iife") && p instanceof AST_Call && p.expression === this) return true; + } + PARENS(AST_AsyncFunction, needs_parens_function); + PARENS(AST_AsyncGeneratorFunction, needs_parens_function); + PARENS(AST_ClassExpression, needs_parens_function); + PARENS(AST_Function, needs_parens_function); + PARENS(AST_GeneratorFunction, needs_parens_function); + + // same goes for an object literal, because otherwise it would be + // interpreted as a block of code. + function needs_parens_obj(output) { + return !output.has_parens() && first_in_statement(output, true); + } + PARENS(AST_Object, needs_parens_obj); + + function needs_parens_unary(output) { + var p = output.parent(); + // (-x) ** y + if (p instanceof AST_Binary) return p.operator == "**" && p.left === this; + // (await x)(y) + // new (await x) + if (p instanceof AST_Call) return p.expression === this; + // class extends (x++) {} + // class x extends (typeof y) {} + if (p instanceof AST_Class) return true; + // (x++)[y] + // (typeof x).y + // https://github.com/mishoo/UglifyJS/issues/115 + if (p instanceof AST_PropAccess) return p.expression === this; + // (~x)`foo` + if (p instanceof AST_Template) return p.tag === this; + } + PARENS(AST_Await, needs_parens_unary); + PARENS(AST_Unary, needs_parens_unary); + + PARENS(AST_Sequence, function(output) { + var p = output.parent(); + // [ 1, (2, 3), 4 ] ---> [ 1, 3, 4 ] + return p instanceof AST_Array + // () ---> (foo, bar) + || is_arrow(p) && p.value === this + // await (foo, bar) + || p instanceof AST_Await + // 1 + (2, 3) + 4 ---> 8 + || p instanceof AST_Binary + // new (foo, bar) or foo(1, (2, 3), 4) + || p instanceof AST_Call + // class extends (foo, bar) {} + // class foo extends (bar, baz) {} + || p instanceof AST_Class + // class { foo = (bar, baz) } + // class { [(foo, bar)]() {} } + || p instanceof AST_ClassProperty + // (false, true) ? (a = 10, b = 20) : (c = 30) + // ---> 20 (side effect, set a := 10 and b := 20) + || p instanceof AST_Conditional + // [ a = (1, 2) ] = [] ---> a == 2 + || p instanceof AST_DefaultValue + // { [(1, 2)]: foo } = bar + // { 1: (2, foo) } = bar + || p instanceof AST_DestructuredKeyVal + // export default (foo, bar) + || p instanceof AST_ExportDefault + // for (foo of (bar, baz)); + || p instanceof AST_ForOf + // { [(1, 2)]: 3 }[2] ---> 3 + // { foo: (1, 2) }.foo ---> 2 + || p instanceof AST_ObjectProperty + // (1, {foo:2}).foo or (1, {foo:2})["foo"] ---> 2 + || p instanceof AST_PropAccess && p.expression === this + // ...(foo, bar, baz) + || p instanceof AST_Spread + // (foo, bar)`baz` + || p instanceof AST_Template && p.tag === this + // !(foo, bar, baz) + || p instanceof AST_Unary + // var a = (1, 2), b = a + a; ---> b == 4 + || p instanceof AST_VarDef + // yield (foo, bar) + || p instanceof AST_Yield; + }); + + PARENS(AST_Binary, function(output) { + var p = output.parent(); + // await (foo && bar) + if (p instanceof AST_Await) return true; + // this deals with precedence: + // 3 * (2 + 1) + // 3 - (2 - 1) + // (1 ** 2) ** 3 + if (p instanceof AST_Binary) { + var po = p.operator, pp = PRECEDENCE[po]; + var so = this.operator, sp = PRECEDENCE[so]; + return pp > sp + || po == "??" && (so == "&&" || so == "||") + || (pp == sp && this === p[po == "**" ? "left" : "right"]); + } + // (foo && bar)() + if (p instanceof AST_Call) return p.expression === this; + // class extends (foo && bar) {} + // class foo extends (bar || null) {} + if (p instanceof AST_Class) return true; + // (foo && bar)["prop"], (foo && bar).prop + if (p instanceof AST_PropAccess) return p.expression === this; + // (foo && bar)`` + if (p instanceof AST_Template) return p.tag === this; + // typeof (foo && bar) + if (p instanceof AST_Unary) return true; + }); + + function need_chain_parens(node, parent) { + if (!node.terminal) return false; + if (!(parent instanceof AST_Call || parent instanceof AST_PropAccess)) return false; + return parent.expression === node; + } + + PARENS(AST_PropAccess, function(output) { + var node = this; + var p = output.parent(); + // i.e. new (foo().bar) + // + // if there's one call into this subtree, then we need + // parens around it too, otherwise the call will be + // interpreted as passing the arguments to the upper New + // expression. + if (p instanceof AST_New && p.expression === node && root_expr(node).TYPE == "Call") return true; + // (foo?.bar)() + // (foo?.bar).baz + // new (foo?.bar)() + return need_chain_parens(node, p); + }); + + PARENS(AST_Call, function(output) { + var node = this; + var p = output.parent(); + if (p instanceof AST_New) return p.expression === node; + // https://bugs.webkit.org/show_bug.cgi?id=123506 + if (output.option("webkit") + && node.expression instanceof AST_Function + && p instanceof AST_PropAccess + && p.expression === node) { + var g = output.parent(1); + if (g instanceof AST_Assign && g.left === p) return true; + } + // (foo?.())() + // (foo?.()).bar + // new (foo?.())() + return need_chain_parens(node, p); + }); + + PARENS(AST_New, function(output) { + if (need_constructor_parens(this, output)) return false; + var p = output.parent(); + // (new foo)(bar) + if (p instanceof AST_Call) return p.expression === this; + // (new Date).getTime(), (new Date)["getTime"]() + if (p instanceof AST_PropAccess) return true; + // (new foo)`bar` + if (p instanceof AST_Template) return p.tag === this; + }); + + PARENS(AST_Number, function(output) { + if (!output.option("galio")) return false; + // https://github.com/mishoo/UglifyJS/pull/1009 + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this && /^0/.test(make_num(this.value)); + }); + + function needs_parens_assign_cond(self, output) { + var p = output.parent(); + // await (a = foo) + if (p instanceof AST_Await) return true; + // 1 + (a = 2) + 3 → 6, side effect setting a = 2 + if (p instanceof AST_Binary) return !(p instanceof AST_Assign); + // (a = func)() —or— new (a = Object)() + if (p instanceof AST_Call) return p.expression === self; + // class extends (a = foo) {} + // class foo extends (bar ? baz : moo) {} + if (p instanceof AST_Class) return true; + // (a = foo) ? bar : baz + if (p instanceof AST_Conditional) return p.condition === self; + // (a = foo)["prop"] —or— (a = foo).prop + if (p instanceof AST_PropAccess) return p.expression === self; + // (a = foo)`bar` + if (p instanceof AST_Template) return p.tag === self; + // !(a = false) → true + if (p instanceof AST_Unary) return true; + } + PARENS(AST_Arrow, function(output) { + return needs_parens_assign_cond(this, output); + }); + PARENS(AST_Assign, function(output) { + if (needs_parens_assign_cond(this, output)) return true; + // v8 parser bug ---> workaround + // f([1], [a] = []) ---> f([1], ([a] = [])) + if (output.option("v8")) return this.left instanceof AST_Destructured; + // ({ p: a } = o); + if (this.left instanceof AST_DestructuredObject) return needs_parens_obj(output); + }); + PARENS(AST_AsyncArrow, function(output) { + return needs_parens_assign_cond(this, output); + }); + PARENS(AST_Conditional, function(output) { + return needs_parens_assign_cond(this, output) + // https://github.com/mishoo/UglifyJS/issues/1144 + || output.option("extendscript") && output.parent() instanceof AST_Conditional; + }); + PARENS(AST_Yield, function(output) { + return needs_parens_assign_cond(this, output); + }); + + /* -----[ PRINTERS ]----- */ + + DEFPRINT(AST_Directive, function(output) { + var quote = this.quote; + var value = this.value; + switch (output.option("quote_style")) { + case 0: + case 2: + if (value.indexOf('"') == -1) quote = '"'; + break; + case 1: + if (value.indexOf("'") == -1) quote = "'"; + break; + } + output.print(quote + value + quote); + output.semicolon(); + }); + DEFPRINT(AST_Debugger, function(output) { + output.print("debugger"); + output.semicolon(); + }); + + /* -----[ statements ]----- */ + + function display_body(body, is_toplevel, output, allow_directives) { + var last = body.length - 1; + var in_directive = allow_directives; + var was_asm = use_asm; + body.forEach(function(stmt, i) { + if (in_directive) { + if (stmt instanceof AST_Directive) { + if (stmt.value == "use asm") use_asm = true; + } else if (!(stmt instanceof AST_EmptyStatement)) { + if (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String) { + output.force_semicolon(); + } + in_directive = false; + } + } + if (stmt instanceof AST_EmptyStatement) return; + output.indent(); + stmt.print(output); + if (i == last && is_toplevel) return; + output.newline(); + if (is_toplevel) output.newline(); + }); + use_asm = was_asm; + } + + DEFPRINT(AST_Toplevel, function(output) { + display_body(this.body, true, output, true); + output.print(""); + }); + DEFPRINT(AST_LabeledStatement, function(output) { + this.label.print(output); + output.colon(); + this.body.print(output); + }); + DEFPRINT(AST_SimpleStatement, function(output) { + this.body.print(output); + output.semicolon(); + }); + function print_braced_empty(self, output) { + output.print("{"); + output.with_indent(function() { + output.append_comments(self, true); + }); + output.print("}"); + } + function print_braced(self, output, allow_directives) { + if (self.body.length > 0) { + output.with_block(function() { + display_body(self.body, false, output, allow_directives); + }, self.end); + } else print_braced_empty(self, output); + } + DEFPRINT(AST_BlockStatement, function(output) { + print_braced(this, output); + }); + DEFPRINT(AST_EmptyStatement, function(output) { + output.semicolon(); + }); + DEFPRINT(AST_Do, function(output) { + var self = this; + output.print("do"); + make_block(self.body, output); + output.space(); + output.print("while"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.semicolon(); + }); + DEFPRINT(AST_While, function(output) { + var self = this; + output.print("while"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + force_statement(self.body, output); + }); + DEFPRINT(AST_For, function(output) { + var self = this; + output.print("for"); + output.space(); + output.with_parens(function() { + if (self.init) { + if (self.init instanceof AST_Definitions) { + self.init.print(output); + } else { + parenthesize_for_no_in(self.init, output, true); + } + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.condition) { + self.condition.print(output); + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.step) { + self.step.print(output); + } + }); + force_statement(self.body, output); + }); + function print_for_enum(prefix, infix) { + return function(output) { + var self = this; + output.print(prefix); + output.space(); + output.with_parens(function() { + self.init.print(output); + output.space(); + output.print(infix); + output.space(); + self.object.print(output); + }); + force_statement(self.body, output); + }; + } + DEFPRINT(AST_ForAwaitOf, print_for_enum("for await", "of")); + DEFPRINT(AST_ForIn, print_for_enum("for", "in")); + DEFPRINT(AST_ForOf, print_for_enum("for", "of")); + DEFPRINT(AST_With, function(output) { + var self = this; + output.print("with"); + output.space(); + output.with_parens(function() { + self.expression.print(output); + }); + force_statement(self.body, output); + }); + DEFPRINT(AST_ExportDeclaration, function(output) { + output.print("export"); + output.space(); + this.body.print(output); + }); + DEFPRINT(AST_ExportDefault, function(output) { + output.print("export"); + output.space(); + output.print("default"); + output.space(); + var body = this.body; + body.print(output); + if (body instanceof AST_ClassExpression) { + if (!body.name) return; + } + if (body instanceof AST_DefClass) return; + if (body instanceof AST_LambdaDefinition) return; + if (body instanceof AST_LambdaExpression) { + if (!body.name && !is_arrow(body)) return; + } + output.semicolon(); + }); + function print_alias(alias, output) { + var value = alias.value; + if (value == "*" || is_identifier_string(value)) { + output.print_name(value); + } else { + output.print_string(value, alias.quote); + } + } + DEFPRINT(AST_ExportForeign, function(output) { + var self = this; + output.print("export"); + output.space(); + var len = self.keys.length; + if (len == 0) { + print_braced_empty(self, output); + } else if (self.keys[0].value == "*") { + print_entry(0); + } else output.with_block(function() { + output.indent(); + print_entry(0); + for (var i = 1; i < len; i++) { + output.print(","); + output.newline(); + output.indent(); + print_entry(i); + } + output.newline(); + }, self.end); + output.space(); + output.print("from"); + output.space(); + self.path.print(output); + output.semicolon(); + + function print_entry(index) { + var alias = self.aliases[index]; + var key = self.keys[index]; + print_alias(key, output); + if (alias.value != key.value) { + output.space(); + output.print("as"); + output.space(); + print_alias(alias, output); + } + } + }); + DEFPRINT(AST_ExportReferences, function(output) { + var self = this; + output.print("export"); + output.space(); + print_properties(self, output); + output.semicolon(); + }); + DEFPRINT(AST_Import, function(output) { + var self = this; + output.print("import"); + output.space(); + if (self.default) self.default.print(output); + if (self.all) { + if (self.default) output.comma(); + self.all.print(output); + } + if (self.properties) { + if (self.default) output.comma(); + print_properties(self, output); + } + if (self.all || self.default || self.properties) { + output.space(); + output.print("from"); + output.space(); + } + self.path.print(output); + output.semicolon(); + }); + + /* -----[ functions ]----- */ + function print_funargs(self, output) { + output.with_parens(function() { + self.argnames.forEach(function(arg, i) { + if (i) output.comma(); + arg.print(output); + }); + if (self.rest) { + if (self.argnames.length) output.comma(); + output.print("..."); + self.rest.print(output); + } + }); + } + function print_arrow(self, output) { + var argname = self.argnames.length == 1 && !self.rest && self.argnames[0]; + if (argname instanceof AST_SymbolFunarg && argname.name != "yield") { + argname.print(output); + } else { + print_funargs(self, output); + } + output.space(); + output.print("=>"); + output.space(); + if (self.value) { + self.value.print(output); + } else { + print_braced(self, output, true); + } + } + DEFPRINT(AST_Arrow, function(output) { + print_arrow(this, output); + }); + DEFPRINT(AST_AsyncArrow, function(output) { + output.print("async"); + output.space(); + print_arrow(this, output); + }); + function print_lambda(self, output) { + if (self.name) { + output.space(); + self.name.print(output); + } + print_funargs(self, output); + output.space(); + print_braced(self, output, true); + } + DEFPRINT(AST_Lambda, function(output) { + output.print("function"); + print_lambda(this, output); + }); + function print_async(output) { + output.print("async"); + output.space(); + output.print("function"); + print_lambda(this, output); + } + DEFPRINT(AST_AsyncDefun, print_async); + DEFPRINT(AST_AsyncFunction, print_async); + function print_async_generator(output) { + output.print("async"); + output.space(); + output.print("function*"); + print_lambda(this, output); + } + DEFPRINT(AST_AsyncGeneratorDefun, print_async_generator); + DEFPRINT(AST_AsyncGeneratorFunction, print_async_generator); + function print_generator(output) { + output.print("function*"); + print_lambda(this, output); + } + DEFPRINT(AST_GeneratorDefun, print_generator); + DEFPRINT(AST_GeneratorFunction, print_generator); + + /* -----[ classes ]----- */ + DEFPRINT(AST_Class, function(output) { + var self = this; + output.print("class"); + if (self.name) { + output.space(); + self.name.print(output); + } + if (self.extends) { + output.space(); + output.print("extends"); + output.space(); + self.extends.print(output); + } + output.space(); + print_properties(self, output, true); + }); + DEFPRINT(AST_ClassField, function(output) { + var self = this; + if (self.static) { + output.print("static"); + output.space(); + } + print_property_key(self, output); + if (self.value) { + output.space(); + output.print("="); + output.space(); + self.value.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_ClassGetter, print_accessor("get")); + DEFPRINT(AST_ClassSetter, print_accessor("set")); + function print_method(self, output) { + var fn = self.value; + if (is_async(fn)) { + output.print("async"); + output.space(); + } + if (is_generator(fn)) output.print("*"); + print_property_key(self, output); + print_lambda(self.value, output); + } + DEFPRINT(AST_ClassMethod, function(output) { + var self = this; + if (self.static) { + output.print("static"); + output.space(); + } + print_method(self, output); + }); + DEFPRINT(AST_ClassInit, function(output) { + output.print("static"); + output.space(); + print_braced(this.value, output); + }); + + /* -----[ jumps ]----- */ + function print_jump(kind, prop) { + return function(output) { + output.print(kind); + var target = this[prop]; + if (target) { + output.space(); + target.print(output); + } + output.semicolon(); + }; + } + DEFPRINT(AST_Return, print_jump("return", "value")); + DEFPRINT(AST_Throw, print_jump("throw", "value")); + DEFPRINT(AST_Break, print_jump("break", "label")); + DEFPRINT(AST_Continue, print_jump("continue", "label")); + + /* -----[ if ]----- */ + function make_then(self, output) { + var b = self.body; + if (output.option("braces") && !(b instanceof AST_Const || b instanceof AST_Let) + || output.option("ie") && b instanceof AST_Do) + return make_block(b, output); + // The squeezer replaces "block"-s that contain only a single + // statement with the statement itself; technically, the AST + // is correct, but this can create problems when we output an + // IF having an ELSE clause where the THEN clause ends in an + // IF *without* an ELSE block (then the outer ELSE would refer + // to the inner IF). This function checks for this case and + // adds the block braces if needed. + if (!b) return output.force_semicolon(); + while (true) { + if (b instanceof AST_If) { + if (!b.alternative) { + make_block(self.body, output); + return; + } + b = b.alternative; + } else if (b instanceof AST_StatementWithBody) { + b = b.body; + } else break; + } + force_statement(self.body, output); + } + DEFPRINT(AST_If, function(output) { + var self = this; + output.print("if"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + if (self.alternative) { + make_then(self, output); + output.space(); + output.print("else"); + if (self.alternative instanceof AST_If) { + output.space(); + self.alternative.print(output); + } else { + force_statement(self.alternative, output); + } + } else { + force_statement(self.body, output); + } + }); + + /* -----[ switch ]----- */ + DEFPRINT(AST_Switch, function(output) { + var self = this; + output.print("switch"); + output.space(); + output.with_parens(function() { + self.expression.print(output); + }); + output.space(); + var last = self.body.length - 1; + if (last < 0) print_braced_empty(self, output); + else output.with_block(function() { + self.body.forEach(function(branch, i) { + output.indent(true); + branch.print(output); + if (i < last && branch.body.length > 0) + output.newline(); + }); + }, self.end); + }); + function print_branch_body(self, output) { + output.newline(); + self.body.forEach(function(stmt) { + output.indent(); + stmt.print(output); + output.newline(); + }); + } + DEFPRINT(AST_Default, function(output) { + output.print("default:"); + print_branch_body(this, output); + }); + DEFPRINT(AST_Case, function(output) { + var self = this; + output.print("case"); + output.space(); + self.expression.print(output); + output.print(":"); + print_branch_body(self, output); + }); + + /* -----[ exceptions ]----- */ + DEFPRINT(AST_Try, function(output) { + var self = this; + output.print("try"); + output.space(); + print_braced(self, output); + if (self.bcatch) { + output.space(); + self.bcatch.print(output); + } + if (self.bfinally) { + output.space(); + self.bfinally.print(output); + } + }); + DEFPRINT(AST_Catch, function(output) { + var self = this; + output.print("catch"); + if (self.argname) { + output.space(); + output.with_parens(function() { + self.argname.print(output); + }); + } + output.space(); + print_braced(self, output); + }); + DEFPRINT(AST_Finally, function(output) { + output.print("finally"); + output.space(); + print_braced(this, output); + }); + + function print_definitions(type) { + return function(output) { + var self = this; + output.print(type); + output.space(); + self.definitions.forEach(function(def, i) { + if (i) output.comma(); + def.print(output); + }); + var p = output.parent(); + if (!(p instanceof AST_IterationStatement && p.init === self)) output.semicolon(); + }; + } + DEFPRINT(AST_Const, print_definitions("const")); + DEFPRINT(AST_Let, print_definitions("let")); + DEFPRINT(AST_Var, print_definitions("var")); + + function parenthesize_for_no_in(node, output, no_in) { + var parens = false; + // need to take some precautions here: + // https://github.com/mishoo/UglifyJS/issues/60 + if (no_in) node.walk(new TreeWalker(function(node) { + if (parens) return true; + if (node instanceof AST_Binary && node.operator == "in") return parens = true; + if (node instanceof AST_Scope && !(is_arrow(node) && node.value)) return true; + })); + node.print(output, parens); + } + + DEFPRINT(AST_VarDef, function(output) { + var self = this; + self.name.print(output); + if (self.value) { + output.space(); + output.print("="); + output.space(); + var p = output.parent(1); + var no_in = p instanceof AST_For || p instanceof AST_ForEnumeration; + parenthesize_for_no_in(self.value, output, no_in); + } + }); + + DEFPRINT(AST_DefaultValue, function(output) { + var self = this; + self.name.print(output); + output.space(); + output.print("="); + output.space(); + self.value.print(output); + }); + + /* -----[ other expressions ]----- */ + function print_annotation(self, output) { + if (!output.option("annotations")) return; + if (!self.pure) return; + var level = 0, parent = self, node; + do { + node = parent; + parent = output.parent(level++); + if (parent instanceof AST_Call && parent.expression === node) return; + } while (parent instanceof AST_PropAccess && parent.expression === node); + output.print("/*@__PURE__*/"); + } + function print_call_args(self, output) { + output.with_parens(function() { + self.args.forEach(function(expr, i) { + if (i) output.comma(); + expr.print(output); + }); + output.add_mapping(self.end); + }); + } + DEFPRINT(AST_Call, function(output) { + var self = this; + print_annotation(self, output); + self.expression.print(output); + if (self.optional) output.print("?."); + print_call_args(self, output); + }); + DEFPRINT(AST_New, function(output) { + var self = this; + print_annotation(self, output); + output.print("new"); + output.space(); + self.expression.print(output); + if (need_constructor_parens(self, output)) print_call_args(self, output); + }); + DEFPRINT(AST_Sequence, function(output) { + this.expressions.forEach(function(node, index) { + if (index > 0) { + output.comma(); + if (output.should_break()) { + output.newline(); + output.indent(); + } + } + node.print(output); + }); + }); + DEFPRINT(AST_Dot, function(output) { + var self = this; + var expr = self.expression; + expr.print(output); + var prop = self.property; + if (output.option("ie") && RESERVED_WORDS[prop] || self.quoted && output.option("keep_quoted_props")) { + if (self.optional) output.print("?."); + output.with_square(function() { + output.add_mapping(self.end); + output.print_string(prop); + }); + } else { + if (expr instanceof AST_Number && !/[ex.)]/i.test(output.last())) output.print("."); + output.print(self.optional ? "?." : "."); + // the name after dot would be mapped about here. + output.add_mapping(self.end); + output.print_name(prop); + } + }); + DEFPRINT(AST_Sub, function(output) { + var self = this; + self.expression.print(output); + if (self.optional) output.print("?."); + output.with_square(function() { + self.property.print(output); + }); + }); + DEFPRINT(AST_Spread, function(output) { + output.print("..."); + this.expression.print(output); + }); + DEFPRINT(AST_UnaryPrefix, function(output) { + var op = this.operator; + var exp = this.expression; + output.print(op); + if (/^[a-z]/i.test(op) + || (/[+-]$/.test(op) + && exp instanceof AST_UnaryPrefix + && /^[+-]/.test(exp.operator))) { + output.space(); + } + exp.print(output); + }); + DEFPRINT(AST_UnaryPostfix, function(output) { + var self = this; + self.expression.print(output); + output.add_mapping(self.end); + output.print(self.operator); + }); + DEFPRINT(AST_Binary, function(output) { + var self = this; + self.left.print(output); + output.space(); + output.print(self.operator); + output.space(); + self.right.print(output); + }); + DEFPRINT(AST_Conditional, function(output) { + var self = this; + self.condition.print(output); + output.space(); + output.print("?"); + output.space(); + self.consequent.print(output); + output.space(); + output.colon(); + self.alternative.print(output); + }); + DEFPRINT(AST_Await, function(output) { + output.print("await"); + output.space(); + this.expression.print(output); + }); + DEFPRINT(AST_Yield, function(output) { + output.print(this.nested ? "yield*" : "yield"); + if (this.expression) { + output.space(); + this.expression.print(output); + } + }); + + /* -----[ literals ]----- */ + DEFPRINT(AST_Array, function(output) { + var a = this.elements, len = a.length; + output.with_square(len > 0 ? function() { + output.space(); + a.forEach(function(exp, i) { + if (i) output.comma(); + exp.print(output); + // If the final element is a hole, we need to make sure it + // doesn't look like a trailing comma, by inserting an actual + // trailing comma. + if (i === len - 1 && exp instanceof AST_Hole) + output.comma(); + }); + output.space(); + } : noop); + }); + DEFPRINT(AST_DestructuredArray, function(output) { + var a = this.elements, len = a.length, rest = this.rest; + output.with_square(len || rest ? function() { + output.space(); + a.forEach(function(exp, i) { + if (i) output.comma(); + exp.print(output); + }); + if (rest) { + if (len) output.comma(); + output.print("..."); + rest.print(output); + } else if (a[len - 1] instanceof AST_Hole) { + // If the final element is a hole, we need to make sure it + // doesn't look like a trailing comma, by inserting an actual + // trailing comma. + output.comma(); + } + output.space(); + } : noop); + }); + DEFPRINT(AST_DestructuredKeyVal, function(output) { + var self = this; + var key = print_property_key(self, output); + var value = self.value; + if (key) { + if (value instanceof AST_DefaultValue) { + if (value.name instanceof AST_Symbol && key == get_symbol_name(value.name)) { + output.space(); + output.print("="); + output.space(); + value.value.print(output); + return; + } + } else if (value instanceof AST_Symbol) { + if (key == get_symbol_name(value)) return; + } + } + output.colon(); + value.print(output); + }); + DEFPRINT(AST_DestructuredObject, function(output) { + var self = this; + var props = self.properties, len = props.length, rest = self.rest; + if (len || rest) output.with_block(function() { + props.forEach(function(prop, i) { + if (i) { + output.print(","); + output.newline(); + } + output.indent(); + prop.print(output); + }); + if (rest) { + if (len) { + output.print(","); + output.newline(); + } + output.indent(); + output.print("..."); + rest.print(output); + } + output.newline(); + }, self.end); + else print_braced_empty(self, output); + }); + function print_properties(self, output, no_comma) { + var props = self.properties; + if (props.length > 0) output.with_block(function() { + props.forEach(function(prop, i) { + if (i) { + if (!no_comma) output.print(","); + output.newline(); + } + output.indent(); + prop.print(output); + }); + output.newline(); + }, self.end); + else print_braced_empty(self, output); + } + DEFPRINT(AST_Object, function(output) { + print_properties(this, output); + }); + + function print_property_key(self, output) { + var key = self.key; + if (key instanceof AST_Node) return output.with_square(function() { + key.print(output); + }); + var quote = self.start && self.start.quote; + if (output.option("quote_keys") || quote && output.option("keep_quoted_props")) { + output.print_string(key, quote); + } else if ("" + +key == key && key >= 0) { + output.print(make_num(key)); + } else if (self.private) { + output.print_name(key); + } else if (RESERVED_WORDS[key] ? !output.option("ie") : is_identifier_string(key)) { + output.print_name(key); + return key; + } else { + output.print_string(key, quote); + } + } + DEFPRINT(AST_ObjectKeyVal, function(output) { + var self = this; + print_property_key(self, output); + output.colon(); + self.value.print(output); + }); + DEFPRINT(AST_ObjectMethod, function(output) { + print_method(this, output); + }); + function print_accessor(type) { + return function(output) { + var self = this; + if (self.static) { + output.print("static"); + output.space(); + } + output.print(type); + output.space(); + print_property_key(self, output); + print_lambda(self.value, output); + }; + } + DEFPRINT(AST_ObjectGetter, print_accessor("get")); + DEFPRINT(AST_ObjectSetter, print_accessor("set")); + function get_symbol_name(sym) { + var def = sym.definition(); + return def && def.mangled_name || sym.name; + } + DEFPRINT(AST_Symbol, function(output) { + output.print_name(get_symbol_name(this)); + }); + DEFPRINT(AST_SymbolExport, function(output) { + var self = this; + var name = get_symbol_name(self); + output.print_name(name); + var alias = self.alias; + if (alias.value != name) { + output.space(); + output.print("as"); + output.space(); + print_alias(alias, output); + } + }); + DEFPRINT(AST_SymbolImport, function(output) { + var self = this; + var name = get_symbol_name(self); + var key = self.key; + if (key.value && key.value != name) { + print_alias(key, output); + output.space(); + output.print("as"); + output.space(); + } + output.print_name(name); + }); + DEFPRINT(AST_Hole, noop); + DEFPRINT(AST_Template, function(output) { + var self = this; + if (self.tag) self.tag.print(output); + output.print("`"); + for (var i = 0; i < self.expressions.length; i++) { + output.print(self.strings[i]); + output.print("${"); + self.expressions[i].print(output); + output.print("}"); + } + output.print(self.strings[i]); + output.print("`"); + }); + DEFPRINT(AST_Constant, function(output) { + output.print("" + this.value); + }); + DEFPRINT(AST_String, function(output) { + output.print_string(this.value, this.quote); + }); + DEFPRINT(AST_Number, function(output) { + var start = this.start; + if (use_asm && start && start.raw != null) { + output.print(start.raw); + } else { + output.print(make_num(this.value)); + } + }); + + DEFPRINT(AST_RegExp, function(output) { + var regexp = this.value; + var str = regexp.toString(); + var end = str.lastIndexOf("/"); + if (regexp.raw_source) { + str = "/" + regexp.raw_source + str.slice(end); + } else if (end == 1) { + str = "/(?:)" + str.slice(end); + } else if (str.indexOf("/", 1) < end) { + str = "/" + str.slice(1, end).replace(/\\\\|[^/]?\//g, function(match) { + return match[0] == "\\" ? match : match.slice(0, -1) + "\\/"; + }) + str.slice(end); + } + output.print(output.to_utf8(str).replace(/\\(?:\0(?![0-9])|[^\0])/g, function(match) { + switch (match[1]) { + case "\n": return "\\n"; + case "\r": return "\\r"; + case "\t": return "\t"; + case "\b": return "\b"; + case "\f": return "\f"; + case "\0": return "\0"; + case "\x0B": return "\v"; + case "\u2028": return "\\u2028"; + case "\u2029": return "\\u2029"; + default: return match; + } + }).replace(/[\n\r\u2028\u2029]/g, function(c) { + switch (c) { + case "\n": return "\\n"; + case "\r": return "\\r"; + case "\u2028": return "\\u2028"; + case "\u2029": return "\\u2029"; + } + })); + }); + + function force_statement(stat, output) { + if (output.option("braces") && !(stat instanceof AST_Const || stat instanceof AST_Let)) { + make_block(stat, output); + } else if (stat instanceof AST_EmptyStatement) { + output.force_semicolon(); + } else { + output.space(); + stat.print(output); + } + } + + // self should be AST_New. decide if we want to show parens or not. + function need_constructor_parens(self, output) { + // Always print parentheses with arguments + if (self.args.length > 0) return true; + + return output.option("beautify"); + } + + function best_of(a) { + var best = a[0], len = best.length; + for (var i = 1; i < a.length; ++i) { + if (a[i].length < len) { + best = a[i]; + len = best.length; + } + } + return best; + } + + function make_num(num) { + var str = num.toString(10).replace(/^0\./, ".").replace("e+", "e"); + var candidates = [ str ]; + if (Math.floor(num) === num) { + if (num < 0) { + candidates.push("-0x" + (-num).toString(16).toLowerCase()); + } else { + candidates.push("0x" + num.toString(16).toLowerCase()); + } + } + var match, len, digits; + if (match = /^\.0+/.exec(str)) { + len = match[0].length; + digits = str.slice(len); + candidates.push(digits + "e-" + (digits.length + len - 1)); + } else if (match = /[^0]0+$/.exec(str)) { + len = match[0].length - 1; + candidates.push(str.slice(0, -len) + "e" + len); + } else if (match = /^(\d)\.(\d+)e(-?\d+)$/.exec(str)) { + candidates.push(match[1] + match[2] + "e" + (match[3] - match[2].length)); + } + return best_of(candidates); + } + + function make_block(stmt, output) { + output.space(); + if (stmt instanceof AST_EmptyStatement) { + print_braced_empty(stmt, output); + } else if (stmt instanceof AST_BlockStatement) { + stmt.print(output); + } else output.with_block(function() { + output.indent(); + stmt.print(output); + output.newline(); + }, stmt.end); + } + + /* -----[ source map generators ]----- */ + + function DEFMAP(nodetype, generator) { + nodetype.forEach(function(nodetype) { + nodetype.DEFMETHOD("add_source_map", generator); + }); + } + + DEFMAP([ + // We could easily add info for ALL nodes, but it seems to me that + // would be quite wasteful, hence this noop in the base class. + AST_Node, + // since the label symbol will mark it + AST_LabeledStatement, + ], noop); + + // XXX: I'm not exactly sure if we need it for all of these nodes, + // or if we should add even more. + DEFMAP([ + AST_Array, + AST_Await, + AST_BlockStatement, + AST_Catch, + AST_Constant, + AST_Debugger, + AST_Definitions, + AST_Destructured, + AST_Directive, + AST_Finally, + AST_Jump, + AST_Lambda, + AST_New, + AST_Object, + AST_Spread, + AST_StatementWithBody, + AST_Symbol, + AST_Switch, + AST_SwitchBranch, + AST_Try, + AST_UnaryPrefix, + AST_Yield, + ], function(output) { + output.add_mapping(this.start); + }); + + DEFMAP([ + AST_ClassProperty, + AST_DestructuredKeyVal, + AST_ObjectProperty, + ], function(output) { + if (typeof this.key == "string") output.add_mapping(this.start, this.key); + }); +})(); diff --git a/node_modules/uglify-js/lib/parse.js b/node_modules/uglify-js/lib/parse.js new file mode 100644 index 0000000..8fb7f38 --- /dev/null +++ b/node_modules/uglify-js/lib/parse.js @@ -0,0 +1,2585 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/). + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +var KEYWORDS = "break case catch class const continue debugger default delete do else extends finally for function if in instanceof new return switch throw try typeof var void while with"; +var KEYWORDS_ATOM = "false null true"; +var RESERVED_WORDS = [ + "abstract async await boolean byte char double enum export final float goto implements import int interface let long native package private protected public short static super synchronized this throws transient volatile yield", + KEYWORDS_ATOM, + KEYWORDS, +].join(" "); +var KEYWORDS_BEFORE_EXPRESSION = "return new delete throw else case"; + +KEYWORDS = makePredicate(KEYWORDS); +RESERVED_WORDS = makePredicate(RESERVED_WORDS); +KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION); +KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM); + +var RE_BIN_NUMBER = /^0b([01]+)$/i; +var RE_HEX_NUMBER = /^0x([0-9a-f]+)$/i; +var RE_OCT_NUMBER = /^0o?([0-7]+)$/i; + +var OPERATORS = makePredicate([ + "in", + "instanceof", + "typeof", + "new", + "void", + "delete", + "++", + "--", + "+", + "-", + "!", + "~", + "&", + "|", + "^", + "*", + "/", + "%", + "**", + ">>", + "<<", + ">>>", + "<", + ">", + "<=", + ">=", + "==", + "===", + "!=", + "!==", + "?", + "=", + "+=", + "-=", + "/=", + "*=", + "%=", + "**=", + ">>=", + "<<=", + ">>>=", + "&=", + "|=", + "^=", + "&&", + "||", + "??", + "&&=", + "||=", + "??=", +]); + +var NEWLINE_CHARS = "\n\r\u2028\u2029"; +var OPERATOR_CHARS = "+-*&%=<>!?|~^"; +var PUNC_OPENERS = "[{("; +var PUNC_SEPARATORS = ",;:"; +var PUNC_CLOSERS = ")}]"; +var PUNC_AFTER_EXPRESSION = PUNC_SEPARATORS + PUNC_CLOSERS; +var PUNC_BEFORE_EXPRESSION = PUNC_OPENERS + PUNC_SEPARATORS; +var PUNC_CHARS = PUNC_BEFORE_EXPRESSION + "`" + PUNC_CLOSERS; +var WHITESPACE_CHARS = NEWLINE_CHARS + " \u00a0\t\f\u000b\u200b\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\uFEFF"; +var NON_IDENTIFIER_CHARS = makePredicate(characters("./'\"#" + OPERATOR_CHARS + PUNC_CHARS + WHITESPACE_CHARS)); + +NEWLINE_CHARS = makePredicate(characters(NEWLINE_CHARS)); +OPERATOR_CHARS = makePredicate(characters(OPERATOR_CHARS)); +PUNC_AFTER_EXPRESSION = makePredicate(characters(PUNC_AFTER_EXPRESSION)); +PUNC_BEFORE_EXPRESSION = makePredicate(characters(PUNC_BEFORE_EXPRESSION)); +PUNC_CHARS = makePredicate(characters(PUNC_CHARS)); +WHITESPACE_CHARS = makePredicate(characters(WHITESPACE_CHARS)); + +/* -----[ Tokenizer ]----- */ + +function is_surrogate_pair_head(code) { + return code >= 0xd800 && code <= 0xdbff; +} + +function is_surrogate_pair_tail(code) { + return code >= 0xdc00 && code <= 0xdfff; +} + +function is_digit(code) { + return code >= 48 && code <= 57; +} + +function is_identifier_char(ch) { + return !NON_IDENTIFIER_CHARS[ch]; +} + +function is_identifier_string(str) { + return /^[a-z_$][a-z0-9_$]*$/i.test(str); +} + +function decode_escape_sequence(seq) { + switch (seq[0]) { + case "b": return "\b"; + case "f": return "\f"; + case "n": return "\n"; + case "r": return "\r"; + case "t": return "\t"; + case "u": + var code; + if (seq[1] == "{" && seq.slice(-1) == "}") { + code = seq.slice(2, -1); + } else if (seq.length == 5) { + code = seq.slice(1); + } else { + return; + } + var num = parseInt(code, 16); + if (num < 0 || isNaN(num)) return; + if (num < 0x10000) return String.fromCharCode(num); + if (num > 0x10ffff) return; + return String.fromCharCode((num >> 10) + 0xd7c0) + String.fromCharCode((num & 0x03ff) + 0xdc00); + case "v": return "\u000b"; + case "x": + if (seq.length != 3) return; + var num = parseInt(seq.slice(1), 16); + if (num < 0 || isNaN(num)) return; + return String.fromCharCode(num); + case "\r": + case "\n": + return ""; + default: + if (seq == "0") return "\0"; + if (seq[0] >= "0" && seq[0] <= "9") return; + return seq; + } +} + +function parse_js_number(num) { + var match; + if (match = RE_BIN_NUMBER.exec(num)) return parseInt(match[1], 2); + if (match = RE_HEX_NUMBER.exec(num)) return parseInt(match[1], 16); + if (match = RE_OCT_NUMBER.exec(num)) return parseInt(match[1], 8); + var val = parseFloat(num); + if (val == num) return val; +} + +function JS_Parse_Error(message, filename, line, col, pos) { + this.message = message; + this.filename = filename; + this.line = line; + this.col = col; + this.pos = pos; +} +JS_Parse_Error.prototype = Object.create(Error.prototype); +JS_Parse_Error.prototype.constructor = JS_Parse_Error; +JS_Parse_Error.prototype.name = "SyntaxError"; +configure_error_stack(JS_Parse_Error); + +function js_error(message, filename, line, col, pos) { + throw new JS_Parse_Error(message, filename, line, col, pos); +} + +function is_token(token, type, val) { + return token.type == type && (val == null || token.value == val); +} + +var EX_EOF = {}; + +function tokenizer($TEXT, filename, html5_comments, shebang) { + + var S = { + text : $TEXT, + filename : filename, + pos : 0, + tokpos : 0, + line : 1, + tokline : 0, + col : 0, + tokcol : 0, + newline_before : false, + regex_allowed : false, + comments_before : [], + directives : Object.create(null), + read_template : with_eof_error("Unterminated template literal", function(strings) { + var s = ""; + for (;;) { + var ch = read(); + switch (ch) { + case "\\": + ch += read(); + break; + case "`": + strings.push(s); + return; + case "$": + if (peek() == "{") { + next(); + strings.push(s); + S.regex_allowed = true; + return true; + } + } + s += ch; + } + + function read() { + var ch = next(true, true); + return ch == "\r" ? "\n" : ch; + } + }), + }; + var prev_was_dot = false; + + function peek() { + return S.text.charAt(S.pos); + } + + function next(signal_eof, in_string) { + var ch = S.text.charAt(S.pos++); + if (signal_eof && !ch) + throw EX_EOF; + if (NEWLINE_CHARS[ch]) { + S.col = 0; + S.line++; + if (!in_string) S.newline_before = true; + if (ch == "\r" && peek() == "\n") { + // treat `\r\n` as `\n` + S.pos++; + ch = "\n"; + } + } else { + S.col++; + } + return ch; + } + + function forward(i) { + while (i-- > 0) next(); + } + + function looking_at(str) { + return S.text.substr(S.pos, str.length) == str; + } + + function find_eol() { + var text = S.text; + for (var i = S.pos; i < S.text.length; ++i) { + if (NEWLINE_CHARS[text[i]]) return i; + } + return -1; + } + + function find(what, signal_eof) { + var pos = S.text.indexOf(what, S.pos); + if (signal_eof && pos == -1) throw EX_EOF; + return pos; + } + + function start_token() { + S.tokline = S.line; + S.tokcol = S.col; + S.tokpos = S.pos; + } + + function token(type, value, is_comment) { + S.regex_allowed = type == "operator" && !UNARY_POSTFIX[value] + || type == "keyword" && KEYWORDS_BEFORE_EXPRESSION[value] + || type == "punc" && PUNC_BEFORE_EXPRESSION[value]; + if (type == "punc" && value == ".") prev_was_dot = true; + else if (!is_comment) prev_was_dot = false; + var ret = { + type : type, + value : value, + line : S.tokline, + col : S.tokcol, + pos : S.tokpos, + endline : S.line, + endcol : S.col, + endpos : S.pos, + nlb : S.newline_before, + file : filename + }; + if (/^(?:num|string|regexp)$/i.test(type)) { + ret.raw = $TEXT.substring(ret.pos, ret.endpos); + } + if (!is_comment) { + ret.comments_before = S.comments_before; + ret.comments_after = S.comments_before = []; + } + S.newline_before = false; + return new AST_Token(ret); + } + + function skip_whitespace() { + while (WHITESPACE_CHARS[peek()]) + next(); + } + + function read_while(pred) { + var ret = "", ch; + while ((ch = peek()) && pred(ch, ret)) ret += next(); + return ret; + } + + function parse_error(err) { + js_error(err, filename, S.tokline, S.tokcol, S.tokpos); + } + + function is_octal(num) { + return /^0[0-7_]+$/.test(num); + } + + function read_num(prefix) { + var has_e = false, after_e = false, has_x = false, has_dot = prefix == "."; + var num = read_while(function(ch, str) { + switch (ch) { + case "x": case "X": + return has_x ? false : (has_x = true); + case "e": case "E": + return has_x ? true : has_e ? false : (has_e = after_e = true); + case "+": case "-": + return after_e; + case (after_e = false, "."): + return has_dot || has_e || has_x || is_octal(str) ? false : (has_dot = true); + } + return /[_0-9a-dfo]/i.test(ch); + }); + if (prefix) num = prefix + num; + if (is_octal(num)) { + if (next_token.has_directive("use strict")) parse_error("Legacy octal literals are not allowed in strict mode"); + } else { + num = num.replace(has_x ? /([1-9a-f]|.0)_(?=[0-9a-f])/gi : /([1-9]|.0)_(?=[0-9])/gi, "$1"); + } + var valid = parse_js_number(num); + if (isNaN(valid)) parse_error("Invalid syntax: " + num); + if (has_dot || has_e || peek() != "n") return token("num", valid); + return token("bigint", num.toLowerCase() + next()); + } + + function read_escaped_char(in_string) { + var seq = next(true, in_string); + if (seq >= "0" && seq <= "7") return read_octal_escape_sequence(seq); + if (seq == "u") { + var ch = next(true, in_string); + seq += ch; + if (ch != "{") { + seq += next(true, in_string) + next(true, in_string) + next(true, in_string); + } else do { + ch = next(true, in_string); + seq += ch; + } while (ch != "}"); + } else if (seq == "x") { + seq += next(true, in_string) + next(true, in_string); + } + var str = decode_escape_sequence(seq); + if (typeof str != "string") parse_error("Invalid escape sequence: \\" + seq); + return str; + } + + function read_octal_escape_sequence(ch) { + // Read + var p = peek(); + if (p >= "0" && p <= "7") { + ch += next(true); + if (ch[0] <= "3" && (p = peek()) >= "0" && p <= "7") + ch += next(true); + } + + // Parse + if (ch === "0") return "\0"; + if (ch.length > 0 && next_token.has_directive("use strict")) + parse_error("Legacy octal escape sequences are not allowed in strict mode"); + return String.fromCharCode(parseInt(ch, 8)); + } + + var read_string = with_eof_error("Unterminated string constant", function(quote_char) { + var quote = next(), ret = ""; + for (;;) { + var ch = next(true, true); + if (ch == "\\") ch = read_escaped_char(true); + else if (NEWLINE_CHARS[ch]) parse_error("Unterminated string constant"); + else if (ch == quote) break; + ret += ch; + } + var tok = token("string", ret); + tok.quote = quote_char; + return tok; + }); + + function skip_line_comment(type) { + var regex_allowed = S.regex_allowed; + var i = find_eol(), ret; + if (i == -1) { + ret = S.text.substr(S.pos); + S.pos = S.text.length; + } else { + ret = S.text.substring(S.pos, i); + S.pos = i; + } + S.col = S.tokcol + (S.pos - S.tokpos); + S.comments_before.push(token(type, ret, true)); + S.regex_allowed = regex_allowed; + return next_token; + } + + var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function() { + var regex_allowed = S.regex_allowed; + var i = find("*/", true); + var text = S.text.substring(S.pos, i).replace(/\r\n|\r|\u2028|\u2029/g, "\n"); + // update stream position + forward(text.length /* doesn't count \r\n as 2 char while S.pos - i does */ + 2); + S.comments_before.push(token("comment2", text, true)); + S.regex_allowed = regex_allowed; + return next_token; + }); + + function read_name() { + var backslash = false, ch, escaped = false, name = peek() == "#" ? next() : ""; + while (ch = peek()) { + if (!backslash) { + if (ch == "\\") escaped = backslash = true, next(); + else if (is_identifier_char(ch)) name += next(); + else break; + } else { + if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX"); + ch = read_escaped_char(); + if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier"); + name += ch; + backslash = false; + } + } + if (KEYWORDS[name] && escaped) { + var hex = name.charCodeAt(0).toString(16).toUpperCase(); + name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1); + } + return name; + } + + var read_regexp = with_eof_error("Unterminated regular expression", function(source) { + var prev_backslash = false, ch, in_class = false; + while ((ch = next(true))) if (NEWLINE_CHARS[ch]) { + parse_error("Unexpected line terminator"); + } else if (prev_backslash) { + source += "\\" + ch; + prev_backslash = false; + } else if (ch == "[") { + in_class = true; + source += ch; + } else if (ch == "]" && in_class) { + in_class = false; + source += ch; + } else if (ch == "/" && !in_class) { + break; + } else if (ch == "\\") { + prev_backslash = true; + } else { + source += ch; + } + var mods = read_name(); + try { + var regexp = new RegExp(source, mods); + regexp.raw_source = source; + return token("regexp", regexp); + } catch (e) { + parse_error(e.message); + } + }); + + function read_operator(prefix) { + function grow(op) { + if (!peek()) return op; + var bigger = op + peek(); + if (OPERATORS[bigger]) { + next(); + return grow(bigger); + } else { + return op; + } + } + return token("operator", grow(prefix || next())); + } + + function handle_slash() { + next(); + switch (peek()) { + case "/": + next(); + return skip_line_comment("comment1"); + case "*": + next(); + return skip_multiline_comment(); + } + return S.regex_allowed ? read_regexp("") : read_operator("/"); + } + + function handle_dot() { + next(); + if (looking_at("..")) return token("operator", "." + next() + next()); + return is_digit(peek().charCodeAt(0)) ? read_num(".") : token("punc", "."); + } + + function read_word() { + var word = read_name(); + if (prev_was_dot) return token("name", word); + return KEYWORDS_ATOM[word] ? token("atom", word) + : !KEYWORDS[word] ? token("name", word) + : OPERATORS[word] ? token("operator", word) + : token("keyword", word); + } + + function with_eof_error(eof_error, cont) { + return function(x) { + try { + return cont(x); + } catch (ex) { + if (ex === EX_EOF) parse_error(eof_error); + else throw ex; + } + }; + } + + function next_token(force_regexp) { + if (force_regexp != null) + return read_regexp(force_regexp); + if (shebang && S.pos == 0 && looking_at("#!")) { + start_token(); + forward(2); + skip_line_comment("comment5"); + } + for (;;) { + skip_whitespace(); + start_token(); + if (html5_comments) { + if (looking_at("") && S.newline_before) { + forward(3); + skip_line_comment("comment4"); + continue; + } + } + var ch = peek(); + if (!ch) return token("eof"); + var code = ch.charCodeAt(0); + switch (code) { + case 34: case 39: return read_string(ch); + case 46: return handle_dot(); + case 47: + var tok = handle_slash(); + if (tok === next_token) continue; + return tok; + } + if (is_digit(code)) return read_num(); + if (PUNC_CHARS[ch]) return token("punc", next()); + if (looking_at("=>")) return token("punc", next() + next()); + if (OPERATOR_CHARS[ch]) return read_operator(); + if (code == 35 || code == 92 || !NON_IDENTIFIER_CHARS[ch]) return read_word(); + break; + } + parse_error("Unexpected character '" + ch + "'"); + } + + next_token.context = function(nc) { + if (nc) S = nc; + return S; + }; + + next_token.add_directive = function(directive) { + S.directives[directive] = true; + } + + next_token.push_directives_stack = function() { + S.directives = Object.create(S.directives); + } + + next_token.pop_directives_stack = function() { + S.directives = Object.getPrototypeOf(S.directives); + } + + next_token.has_directive = function(directive) { + return !!S.directives[directive]; + } + + return next_token; +} + +/* -----[ Parser (constants) ]----- */ + +var UNARY_PREFIX = makePredicate("typeof void delete -- ++ ! ~ - +"); + +var UNARY_POSTFIX = makePredicate("-- ++"); + +var ASSIGNMENT = makePredicate("= += -= /= *= %= **= >>= <<= >>>= &= |= ^= &&= ||= ??="); + +var PRECEDENCE = function(a, ret) { + for (var i = 0; i < a.length;) { + var b = a[i++]; + for (var j = 0; j < b.length; j++) { + ret[b[j]] = i; + } + } + return ret; +}([ + ["??"], + ["||"], + ["&&"], + ["|"], + ["^"], + ["&"], + ["==", "===", "!=", "!=="], + ["<", ">", "<=", ">=", "in", "instanceof"], + [">>", "<<", ">>>"], + ["+", "-"], + ["*", "/", "%"], + ["**"], +], {}); + +var ATOMIC_START_TOKEN = makePredicate("atom bigint num regexp string"); + +/* -----[ Parser ]----- */ + +function parse($TEXT, options) { + options = defaults(options, { + bare_returns : false, + expression : false, + filename : null, + html5_comments : true, + module : false, + shebang : true, + strict : false, + toplevel : null, + }, true); + + var S = { + input : typeof $TEXT == "string" + ? tokenizer($TEXT, options.filename, options.html5_comments, options.shebang) + : $TEXT, + in_async : false, + in_directives : true, + in_funarg : -1, + in_function : 0, + in_generator : false, + in_loop : 0, + labels : [], + peeked : null, + prev : null, + token : null, + }; + + S.token = next(); + + function is(type, value) { + return is_token(S.token, type, value); + } + + function peek() { + return S.peeked || (S.peeked = S.input()); + } + + function next() { + S.prev = S.token; + if (S.peeked) { + S.token = S.peeked; + S.peeked = null; + } else { + S.token = S.input(); + } + S.in_directives = S.in_directives && ( + S.token.type == "string" || is("punc", ";") + ); + return S.token; + } + + function prev() { + return S.prev; + } + + function croak(msg, line, col, pos) { + var ctx = S.input.context(); + js_error(msg, + ctx.filename, + line != null ? line : ctx.tokline, + col != null ? col : ctx.tokcol, + pos != null ? pos : ctx.tokpos); + } + + function token_error(token, msg) { + croak(msg, token.line, token.col); + } + + function token_to_string(type, value) { + return type + (value === undefined ? "" : " «" + value + "»"); + } + + function unexpected(token) { + if (token == null) token = S.token; + token_error(token, "Unexpected token: " + token_to_string(token.type, token.value)); + } + + function expect_token(type, val) { + if (is(type, val)) return next(); + token_error(S.token, "Unexpected token: " + token_to_string(S.token.type, S.token.value) + ", expected: " + token_to_string(type, val)); + } + + function expect(punc) { + return expect_token("punc", punc); + } + + function has_newline_before(token) { + return token.nlb || !all(token.comments_before, function(comment) { + return !comment.nlb; + }); + } + + function can_insert_semicolon() { + return !options.strict + && (is("eof") || is("punc", "}") || has_newline_before(S.token)); + } + + function semicolon(optional) { + if (is("punc", ";")) next(); + else if (!optional && !can_insert_semicolon()) expect(";"); + } + + function parenthesized() { + expect("("); + var exp = expression(); + expect(")"); + return exp; + } + + function embed_tokens(parser) { + return function() { + var start = S.token; + var expr = parser.apply(null, arguments); + var end = prev(); + expr.start = start; + expr.end = end; + return expr; + }; + } + + function handle_regexp() { + if (is("operator", "/") || is("operator", "/=")) { + S.peeked = null; + S.token = S.input(S.token.value.substr(1)); // force regexp + } + } + + var statement = embed_tokens(function(toplevel) { + handle_regexp(); + switch (S.token.type) { + case "string": + var dir = S.in_directives; + var body = expression(); + if (dir) { + if (body instanceof AST_String) { + var value = body.start.raw.slice(1, -1); + S.input.add_directive(value); + body.value = value; + } else { + S.in_directives = dir = false; + } + } + semicolon(); + return dir ? new AST_Directive(body) : new AST_SimpleStatement({ body: body }); + case "num": + case "bigint": + case "regexp": + case "operator": + case "atom": + return simple_statement(); + + case "name": + switch (S.token.value) { + case "async": + if (is_token(peek(), "keyword", "function")) { + next(); + next(); + if (!is("operator", "*")) return function_(AST_AsyncDefun); + next(); + return function_(AST_AsyncGeneratorDefun); + } + break; + case "await": + if (S.in_async) return simple_statement(); + break; + case "export": + if (!toplevel && options.module !== "") unexpected(); + next(); + return export_(); + case "import": + var token = peek(); + if (token.type == "punc" && /^[(.]$/.test(token.value)) break; + if (!toplevel && options.module !== "") unexpected(); + next(); + return import_(); + case "let": + if (is_vardefs()) { + next(); + var node = let_(); + semicolon(); + return node; + } + break; + case "yield": + if (S.in_generator) return simple_statement(); + break; + } + return is_token(peek(), "punc", ":") + ? labeled_statement() + : simple_statement(); + + case "punc": + switch (S.token.value) { + case "{": + return new AST_BlockStatement({ + start : S.token, + body : block_(), + end : prev() + }); + case "[": + case "(": + case "`": + return simple_statement(); + case ";": + S.in_directives = false; + next(); + return new AST_EmptyStatement(); + default: + unexpected(); + } + + case "keyword": + switch (S.token.value) { + case "break": + next(); + return break_cont(AST_Break); + + case "class": + next(); + return class_(AST_DefClass); + + case "const": + next(); + var node = const_(); + semicolon(); + return node; + + case "continue": + next(); + return break_cont(AST_Continue); + + case "debugger": + next(); + semicolon(); + return new AST_Debugger(); + + case "do": + next(); + var body = in_loop(statement); + expect_token("keyword", "while"); + var condition = parenthesized(); + semicolon(true); + return new AST_Do({ + body : body, + condition : condition, + }); + + case "while": + next(); + return new AST_While({ + condition : parenthesized(), + body : in_loop(statement), + }); + + case "for": + next(); + return for_(); + + case "function": + next(); + if (!is("operator", "*")) return function_(AST_Defun); + next(); + return function_(AST_GeneratorDefun); + + case "if": + next(); + return if_(); + + case "return": + if (S.in_function == 0 && !options.bare_returns) + croak("'return' outside of function"); + next(); + var value = null; + if (is("punc", ";")) { + next(); + } else if (!can_insert_semicolon()) { + value = expression(); + semicolon(); + } + return new AST_Return({ value: value }); + + case "switch": + next(); + return new AST_Switch({ + expression : parenthesized(), + body : in_loop(switch_body_), + }); + + case "throw": + next(); + if (has_newline_before(S.token)) + croak("Illegal newline after 'throw'"); + var value = expression(); + semicolon(); + return new AST_Throw({ value: value }); + + case "try": + next(); + return try_(); + + case "var": + next(); + var node = var_(); + semicolon(); + return node; + + case "with": + if (S.input.has_directive("use strict")) { + croak("Strict mode may not include a with statement"); + } + next(); + return new AST_With({ + expression : parenthesized(), + body : statement(), + }); + } + } + unexpected(); + }); + + function labeled_statement() { + var label = as_symbol(AST_Label); + if (!all(S.labels, function(l) { + return l.name != label.name; + })) { + // ECMA-262, 12.12: An ECMAScript program is considered + // syntactically incorrect if it contains a + // LabelledStatement that is enclosed by a + // LabelledStatement with the same Identifier as label. + croak("Label " + label.name + " defined twice"); + } + expect(":"); + S.labels.push(label); + var stat = statement(); + S.labels.pop(); + if (!(stat instanceof AST_IterationStatement)) { + // check for `continue` that refers to this label. + // those should be reported as syntax errors. + // https://github.com/mishoo/UglifyJS/issues/287 + label.references.forEach(function(ref) { + if (ref instanceof AST_Continue) { + token_error(ref.label.start, "Continue label `" + label.name + "` must refer to IterationStatement"); + } + }); + } + return new AST_LabeledStatement({ body: stat, label: label }); + } + + function simple_statement() { + var body = expression(); + semicolon(); + return new AST_SimpleStatement({ body: body }); + } + + function break_cont(type) { + var label = null, ldef; + if (!can_insert_semicolon()) { + label = as_symbol(AST_LabelRef, true); + } + if (label != null) { + ldef = find_if(function(l) { + return l.name == label.name; + }, S.labels); + if (!ldef) token_error(label.start, "Undefined label " + label.name); + label.thedef = ldef; + } else if (S.in_loop == 0) croak(type.TYPE + " not inside a loop or switch"); + semicolon(); + var stat = new type({ label: label }); + if (ldef) ldef.references.push(stat); + return stat; + } + + function has_modifier(name, no_nlb) { + if (!is("name", name)) return; + var token = peek(); + if (!token) return; + if (is_token(token, "operator", "=")) return; + if (token.type == "punc" && /^[(;}]$/.test(token.value)) return; + if (no_nlb && has_newline_before(token)) return; + return next(); + } + + function class_(ctor) { + var was_async = S.in_async; + var was_gen = S.in_generator; + S.input.push_directives_stack(); + S.input.add_directive("use strict"); + var name; + if (ctor === AST_DefClass) { + name = as_symbol(AST_SymbolDefClass); + } else { + name = as_symbol(AST_SymbolClass, true); + } + var parent = null; + if (is("keyword", "extends")) { + next(); + handle_regexp(); + parent = expr_atom(true); + } + expect("{"); + var props = []; + while (!is("punc", "}")) { + if (is("punc", ";")) { + next(); + continue; + } + var start = S.token; + var fixed = !!has_modifier("static"); + var async = has_modifier("async", true); + if (is("operator", "*")) { + next(); + var internal = is("name") && /^#/.test(S.token.value); + var key = as_property_key(); + var gen_start = S.token; + var gen = function_(async ? AST_AsyncGeneratorFunction : AST_GeneratorFunction); + gen.start = gen_start; + gen.end = prev(); + props.push(new AST_ClassMethod({ + start: start, + static: fixed, + private: internal, + key: key, + value: gen, + end: prev(), + })); + continue; + } + if (fixed && is("punc", "{")) { + props.push(new AST_ClassInit({ + start: start, + value: new AST_ClassInitBlock({ + start: start, + body: block_(), + end: prev(), + }), + end: prev(), + })); + continue; + } + var internal = is("name") && /^#/.test(S.token.value); + var key = as_property_key(); + if (is("punc", "(")) { + var func_start = S.token; + var func = function_(async ? AST_AsyncFunction : AST_Function); + func.start = func_start; + func.end = prev(); + props.push(new AST_ClassMethod({ + start: start, + static: fixed, + private: internal, + key: key, + value: func, + end: prev(), + })); + continue; + } + if (async) unexpected(async); + var value = null; + if (is("operator", "=")) { + next(); + S.in_async = false; + S.in_generator = false; + value = maybe_assign(); + S.in_generator = was_gen; + S.in_async = was_async; + } else if (!(is("punc", ";") || is("punc", "}"))) { + var type = null; + switch (key) { + case "get": + type = AST_ClassGetter; + break; + case "set": + type = AST_ClassSetter; + break; + } + if (type) { + props.push(new type({ + start: start, + static: fixed, + private: is("name") && /^#/.test(S.token.value), + key: as_property_key(), + value: create_accessor(), + end: prev(), + })); + continue; + } + } + semicolon(); + props.push(new AST_ClassField({ + start: start, + static: fixed, + private: internal, + key: key, + value: value, + end: prev(), + })); + } + next(); + S.input.pop_directives_stack(); + S.in_generator = was_gen; + S.in_async = was_async; + return new ctor({ + extends: parent, + name: name, + properties: props, + }); + } + + function for_() { + var await_token = is("name", "await") && next(); + expect("("); + var init = null; + if (await_token || !is("punc", ";")) { + init = is("keyword", "const") + ? (next(), const_(true)) + : is("name", "let") && is_vardefs() + ? (next(), let_(true)) + : is("keyword", "var") + ? (next(), var_(true)) + : expression(true); + var ctor; + if (await_token) { + expect_token("name", "of"); + ctor = AST_ForAwaitOf; + } else if (is("operator", "in")) { + next(); + ctor = AST_ForIn; + } else if (is("name", "of")) { + next(); + ctor = AST_ForOf; + } + if (ctor) { + if (init instanceof AST_Definitions) { + if (init.definitions.length > 1) { + token_error(init.start, "Only one variable declaration allowed in for..in/of loop"); + } + if (ctor !== AST_ForIn && init.definitions[0].value) { + token_error(init.definitions[0].value.start, "No initializers allowed in for..of loop"); + } + } else if (!(is_assignable(init) || (init = to_destructured(init)) instanceof AST_Destructured)) { + token_error(init.start, "Invalid left-hand side in for..in/of loop"); + } + return for_enum(ctor, init); + } + } + return regular_for(init); + } + + function regular_for(init) { + expect(";"); + var test = is("punc", ";") ? null : expression(); + expect(";"); + var step = is("punc", ")") ? null : expression(); + expect(")"); + return new AST_For({ + init : init, + condition : test, + step : step, + body : in_loop(statement) + }); + } + + function for_enum(ctor, init) { + handle_regexp(); + var obj = expression(); + expect(")"); + return new ctor({ + init : init, + object : obj, + body : in_loop(statement) + }); + } + + function to_funarg(node) { + if (node instanceof AST_Array) { + var rest = null; + if (node.elements[node.elements.length - 1] instanceof AST_Spread) { + rest = to_funarg(node.elements.pop().expression); + } + return new AST_DestructuredArray({ + start: node.start, + elements: node.elements.map(to_funarg), + rest: rest, + end: node.end, + }); + } + if (node instanceof AST_Assign) return new AST_DefaultValue({ + start: node.start, + name: to_funarg(node.left), + value: node.right, + end: node.end, + }); + if (node instanceof AST_DefaultValue) { + node.name = to_funarg(node.name); + return node; + } + if (node instanceof AST_DestructuredArray) { + node.elements = node.elements.map(to_funarg); + if (node.rest) node.rest = to_funarg(node.rest); + return node; + } + if (node instanceof AST_DestructuredObject) { + node.properties.forEach(function(prop) { + prop.value = to_funarg(prop.value); + }); + if (node.rest) node.rest = to_funarg(node.rest); + return node; + } + if (node instanceof AST_Hole) return node; + if (node instanceof AST_Object) { + var rest = null; + if (node.properties[node.properties.length - 1] instanceof AST_Spread) { + rest = to_funarg(node.properties.pop().expression); + } + return new AST_DestructuredObject({ + start: node.start, + properties: node.properties.map(function(prop) { + if (!(prop instanceof AST_ObjectKeyVal)) token_error(prop.start, "Invalid destructuring assignment"); + return new AST_DestructuredKeyVal({ + start: prop.start, + key: prop.key, + value: to_funarg(prop.value), + end: prop.end, + }); + }), + rest: rest, + end: node.end, + }); + } + if (node instanceof AST_SymbolFunarg) return node; + if (node instanceof AST_SymbolRef) return new AST_SymbolFunarg(node); + if (node instanceof AST_Yield) return new AST_SymbolFunarg({ + start: node.start, + name: "yield", + end: node.end, + }); + token_error(node.start, "Invalid arrow parameter"); + } + + function arrow(exprs, start, async) { + var was_async = S.in_async; + var was_gen = S.in_generator; + S.in_async = async; + S.in_generator = false; + var was_funarg = S.in_funarg; + S.in_funarg = S.in_function; + var argnames = exprs.map(to_funarg); + var rest = exprs.rest || null; + if (rest) rest = to_funarg(rest); + S.in_funarg = was_funarg; + expect("=>"); + var body, value; + var loop = S.in_loop; + var labels = S.labels; + ++S.in_function; + S.input.push_directives_stack(); + S.in_loop = 0; + S.labels = []; + if (is("punc", "{")) { + S.in_directives = true; + body = block_(); + value = null; + } else { + body = []; + handle_regexp(); + value = maybe_assign(); + } + var is_strict = S.input.has_directive("use strict"); + S.input.pop_directives_stack(); + --S.in_function; + S.in_loop = loop; + S.labels = labels; + S.in_generator = was_gen; + S.in_async = was_async; + var node = new (async ? AST_AsyncArrow : AST_Arrow)({ + start: start, + argnames: argnames, + rest: rest, + body: body, + value: value, + end: prev(), + }); + if (is_strict) node.each_argname(strict_verify_symbol); + return node; + } + + var function_ = function(ctor) { + var was_async = S.in_async; + var was_gen = S.in_generator; + var name; + if (/Defun$/.test(ctor.TYPE)) { + name = as_symbol(AST_SymbolDefun); + S.in_async = /^Async/.test(ctor.TYPE); + S.in_generator = /Generator/.test(ctor.TYPE); + } else { + S.in_async = /^Async/.test(ctor.TYPE); + S.in_generator = /Generator/.test(ctor.TYPE); + name = as_symbol(AST_SymbolLambda, true); + } + if (name && ctor !== AST_Accessor && !(name instanceof AST_SymbolDeclaration)) + unexpected(prev()); + expect("("); + var was_funarg = S.in_funarg; + S.in_funarg = S.in_function; + var argnames = expr_list(")", !options.strict, false, function() { + return maybe_default(AST_SymbolFunarg); + }); + S.in_funarg = was_funarg; + var loop = S.in_loop; + var labels = S.labels; + ++S.in_function; + S.in_directives = true; + S.input.push_directives_stack(); + S.in_loop = 0; + S.labels = []; + var body = block_(); + var is_strict = S.input.has_directive("use strict"); + S.input.pop_directives_stack(); + --S.in_function; + S.in_loop = loop; + S.labels = labels; + S.in_generator = was_gen; + S.in_async = was_async; + var node = new ctor({ + name: name, + argnames: argnames, + rest: argnames.rest || null, + body: body, + }); + if (is_strict) { + if (name) strict_verify_symbol(name); + node.each_argname(strict_verify_symbol); + } + return node; + }; + + function if_() { + var cond = parenthesized(), body = statement(), alt = null; + if (is("keyword", "else")) { + next(); + alt = statement(); + } + return new AST_If({ + condition : cond, + body : body, + alternative : alt, + }); + } + + function is_alias() { + return is("name") || is("string") || is_identifier_string(S.token.value); + } + + function make_string(token) { + return new AST_String({ + start: token, + quote: token.quote, + value: token.value, + end: token, + }); + } + + function as_path() { + var path = S.token; + expect_token("string"); + semicolon(); + return make_string(path); + } + + function export_() { + if (is("operator", "*")) { + var key = S.token; + var alias = key; + next(); + if (is("name", "as")) { + next(); + if (!is_alias()) expect_token("name"); + alias = S.token; + next(); + } + expect_token("name", "from"); + return new AST_ExportForeign({ + aliases: [ make_string(alias) ], + keys: [ make_string(key) ], + path: as_path(), + }); + } + if (is("punc", "{")) { + next(); + var aliases = []; + var keys = []; + while (is_alias()) { + var key = S.token; + next(); + keys.push(key); + if (is("name", "as")) { + next(); + if (!is_alias()) expect_token("name"); + aliases.push(S.token); + next(); + } else { + aliases.push(key); + } + if (!is("punc", "}")) expect(","); + } + expect("}"); + if (is("name", "from")) { + next(); + return new AST_ExportForeign({ + aliases: aliases.map(make_string), + keys: keys.map(make_string), + path: as_path(), + }); + } + semicolon(); + return new AST_ExportReferences({ + properties: keys.map(function(token, index) { + if (!is_token(token, "name")) token_error(token, "Name expected"); + var sym = _make_symbol(AST_SymbolExport, token); + sym.alias = make_string(aliases[index]); + return sym; + }), + }); + } + if (is("keyword", "default")) { + next(); + var start = S.token; + var body = export_default_decl(); + if (body) { + body.start = start; + body.end = prev(); + } else { + handle_regexp(); + body = expression(); + semicolon(); + } + return new AST_ExportDefault({ body: body }); + } + return new AST_ExportDeclaration({ body: export_decl() }); + } + + function maybe_named(def, expr) { + if (expr.name) { + expr = new def(expr); + expr.name = new (def === AST_DefClass ? AST_SymbolDefClass : AST_SymbolDefun)(expr.name); + } + return expr; + } + + function export_default_decl() { + if (is("name", "async")) { + if (!is_token(peek(), "keyword", "function")) return; + next(); + next(); + if (!is("operator", "*")) return maybe_named(AST_AsyncDefun, function_(AST_AsyncFunction)); + next(); + return maybe_named(AST_AsyncGeneratorDefun, function_(AST_AsyncGeneratorFunction)); + } else if (is("keyword")) switch (S.token.value) { + case "class": + next(); + return maybe_named(AST_DefClass, class_(AST_ClassExpression)); + case "function": + next(); + if (!is("operator", "*")) return maybe_named(AST_Defun, function_(AST_Function)); + next(); + return maybe_named(AST_GeneratorDefun, function_(AST_GeneratorFunction)); + } + } + + var export_decl = embed_tokens(function() { + if (is("name")) switch (S.token.value) { + case "async": + next(); + expect_token("keyword", "function"); + if (!is("operator", "*")) return function_(AST_AsyncDefun); + next(); + return function_(AST_AsyncGeneratorDefun); + case "let": + next(); + var node = let_(); + semicolon(); + return node; + } else if (is("keyword")) switch (S.token.value) { + case "class": + next(); + return class_(AST_DefClass); + case "const": + next(); + var node = const_(); + semicolon(); + return node; + case "function": + next(); + if (!is("operator", "*")) return function_(AST_Defun); + next(); + return function_(AST_GeneratorDefun); + case "var": + next(); + var node = var_(); + semicolon(); + return node; + } + unexpected(); + }); + + function import_() { + var all = null; + var def = as_symbol(AST_SymbolImport, true); + var props = null; + var cont; + if (def) { + def.key = new AST_String({ + start: def.start, + value: "", + end: def.end, + }); + if (cont = is("punc", ",")) next(); + } else { + cont = !is("string"); + } + if (cont) { + if (is("operator", "*")) { + var key = S.token; + next(); + expect_token("name", "as"); + all = as_symbol(AST_SymbolImport); + all.key = make_string(key); + } else { + expect("{"); + props = []; + while (is_alias()) { + var alias; + if (is_token(peek(), "name", "as")) { + var key = S.token; + next(); + next(); + alias = as_symbol(AST_SymbolImport); + alias.key = make_string(key); + } else { + alias = as_symbol(AST_SymbolImport); + alias.key = new AST_String({ + start: alias.start, + value: alias.name, + end: alias.end, + }); + } + props.push(alias); + if (!is("punc", "}")) expect(","); + } + expect("}"); + } + } + if (all || def || props) expect_token("name", "from"); + return new AST_Import({ + all: all, + default: def, + path: as_path(), + properties: props, + }); + } + + function block_() { + expect("{"); + var a = []; + while (!is("punc", "}")) { + if (is("eof")) expect("}"); + a.push(statement()); + } + next(); + return a; + } + + function switch_body_() { + expect("{"); + var a = [], branch, cur, default_branch, tmp; + while (!is("punc", "}")) { + if (is("eof")) expect("}"); + if (is("keyword", "case")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Case({ + start : (tmp = S.token, next(), tmp), + expression : expression(), + body : cur + }); + a.push(branch); + expect(":"); + } else if (is("keyword", "default")) { + if (branch) branch.end = prev(); + if (default_branch) croak("More than one default clause in switch statement"); + cur = []; + branch = new AST_Default({ + start : (tmp = S.token, next(), expect(":"), tmp), + body : cur + }); + a.push(branch); + default_branch = branch; + } else { + if (!cur) unexpected(); + cur.push(statement()); + } + } + if (branch) branch.end = prev(); + next(); + return a; + } + + function try_() { + var body = block_(), bcatch = null, bfinally = null; + if (is("keyword", "catch")) { + var start = S.token; + next(); + var name = null; + if (is("punc", "(")) { + next(); + name = maybe_destructured(AST_SymbolCatch); + expect(")"); + } + bcatch = new AST_Catch({ + start : start, + argname : name, + body : block_(), + end : prev() + }); + } + if (is("keyword", "finally")) { + var start = S.token; + next(); + bfinally = new AST_Finally({ + start : start, + body : block_(), + end : prev() + }); + } + if (!bcatch && !bfinally) + croak("Missing catch/finally blocks"); + return new AST_Try({ + body : body, + bcatch : bcatch, + bfinally : bfinally + }); + } + + function vardefs(type, no_in) { + var a = []; + for (;;) { + var start = S.token; + var name = maybe_destructured(type); + var value = null; + if (is("operator", "=")) { + next(); + value = maybe_assign(no_in); + } else if (!no_in && (type === AST_SymbolConst || name instanceof AST_Destructured)) { + croak("Missing initializer in declaration"); + } + a.push(new AST_VarDef({ + start : start, + name : name, + value : value, + end : prev() + })); + if (!is("punc", ",")) + break; + next(); + } + return a; + } + + function is_vardefs() { + var token = peek(); + return is_token(token, "name") || is_token(token, "punc", "[") || is_token(token, "punc", "{"); + } + + var const_ = function(no_in) { + return new AST_Const({ + start : prev(), + definitions : vardefs(AST_SymbolConst, no_in), + end : prev() + }); + }; + + var let_ = function(no_in) { + return new AST_Let({ + start : prev(), + definitions : vardefs(AST_SymbolLet, no_in), + end : prev() + }); + }; + + var var_ = function(no_in) { + return new AST_Var({ + start : prev(), + definitions : vardefs(AST_SymbolVar, no_in), + end : prev() + }); + }; + + var new_ = function(allow_calls) { + var start = S.token; + expect_token("operator", "new"); + var call; + if (is("punc", ".") && is_token(peek(), "name", "target")) { + next(); + next(); + call = new AST_NewTarget(); + } else { + var exp = expr_atom(false), args; + if (is("punc", "(")) { + next(); + args = expr_list(")", !options.strict); + } else { + args = []; + } + call = new AST_New({ expression: exp, args: args }); + } + call.start = start; + call.end = prev(); + return subscripts(call, allow_calls); + }; + + function as_atom_node() { + var ret, tok = S.token, value = tok.value; + switch (tok.type) { + case "num": + if (isFinite(value)) { + ret = new AST_Number({ value: value }); + } else { + ret = new AST_Infinity(); + if (value < 0) ret = new AST_UnaryPrefix({ operator: "-", expression: ret }); + } + break; + case "bigint": + ret = new AST_BigInt({ value: value }); + break; + case "string": + ret = new AST_String({ value: value, quote: tok.quote }); + break; + case "regexp": + ret = new AST_RegExp({ value: value }); + break; + case "atom": + switch (value) { + case "false": + ret = new AST_False(); + break; + case "true": + ret = new AST_True(); + break; + case "null": + ret = new AST_Null(); + break; + default: + unexpected(); + } + break; + default: + unexpected(); + } + next(); + ret.start = ret.end = tok; + return ret; + } + + var expr_atom = function(allow_calls) { + if (is("operator", "new")) { + return new_(allow_calls); + } + var start = S.token; + if (is("punc")) { + switch (start.value) { + case "`": + return subscripts(template(null), allow_calls); + case "(": + next(); + if (is("punc", ")")) { + next(); + return arrow([], start); + } + var ex = expression(false, true); + var len = start.comments_before.length; + [].unshift.apply(ex.start.comments_before, start.comments_before); + start.comments_before.length = 0; + start.comments_before = ex.start.comments_before; + start.comments_before_length = len; + if (len == 0 && start.comments_before.length > 0) { + var comment = start.comments_before[0]; + if (!comment.nlb) { + comment.nlb = start.nlb; + start.nlb = false; + } + } + start.comments_after = ex.start.comments_after; + ex.start = start; + expect(")"); + var end = prev(); + end.comments_before = ex.end.comments_before; + end.comments_after.forEach(function(comment) { + ex.end.comments_after.push(comment); + if (comment.nlb) S.token.nlb = true; + }); + end.comments_after.length = 0; + end.comments_after = ex.end.comments_after; + ex.end = end; + if (is("punc", "=>")) return arrow(ex instanceof AST_Sequence ? ex.expressions : [ ex ], start); + return subscripts(ex, allow_calls); + case "[": + return subscripts(array_(), allow_calls); + case "{": + return subscripts(object_(), allow_calls); + } + unexpected(); + } + if (is("keyword")) switch (start.value) { + case "class": + next(); + var clazz = class_(AST_ClassExpression); + clazz.start = start; + clazz.end = prev(); + return subscripts(clazz, allow_calls); + case "function": + next(); + var func; + if (is("operator", "*")) { + next(); + func = function_(AST_GeneratorFunction); + } else { + func = function_(AST_Function); + } + func.start = start; + func.end = prev(); + return subscripts(func, allow_calls); + } + if (is("name")) { + var sym = _make_symbol(AST_SymbolRef, start); + next(); + if (sym.name == "async") { + if (is("keyword", "function")) { + next(); + var func; + if (is("operator", "*")) { + next(); + func = function_(AST_AsyncGeneratorFunction); + } else { + func = function_(AST_AsyncFunction); + } + func.start = start; + func.end = prev(); + return subscripts(func, allow_calls); + } + if (is("name") && is_token(peek(), "punc", "=>")) { + start = S.token; + sym = _make_symbol(AST_SymbolRef, start); + next(); + return arrow([ sym ], start, true); + } + if (is("punc", "(")) { + var call = subscripts(sym, allow_calls); + if (!is("punc", "=>")) return call; + var args = call.args; + if (args[args.length - 1] instanceof AST_Spread) { + args.rest = args.pop().expression; + } + return arrow(args, start, true); + } + } + return is("punc", "=>") ? arrow([ sym ], start) : subscripts(sym, allow_calls); + } + if (ATOMIC_START_TOKEN[S.token.type]) { + return subscripts(as_atom_node(), allow_calls); + } + unexpected(); + }; + + function expr_list(closing, allow_trailing_comma, allow_empty, parser) { + if (!parser) parser = maybe_assign; + var first = true, a = []; + while (!is("punc", closing)) { + if (first) first = false; else expect(","); + if (allow_trailing_comma && is("punc", closing)) break; + if (allow_empty && is("punc", ",")) { + a.push(new AST_Hole({ start: S.token, end: S.token })); + } else if (!is("operator", "...")) { + a.push(parser()); + } else if (parser === maybe_assign) { + a.push(new AST_Spread({ + start: S.token, + expression: (next(), parser()), + end: prev(), + })); + } else { + next(); + a.rest = parser(); + if (a.rest instanceof AST_DefaultValue) token_error(a.rest.start, "Invalid rest parameter"); + break; + } + } + expect(closing); + return a; + } + + var array_ = embed_tokens(function() { + expect("["); + return new AST_Array({ + elements: expr_list("]", !options.strict, true) + }); + }); + + var create_accessor = embed_tokens(function() { + return function_(AST_Accessor); + }); + + var object_ = embed_tokens(function() { + expect("{"); + var first = true, a = []; + while (!is("punc", "}")) { + if (first) first = false; else expect(","); + // allow trailing comma + if (!options.strict && is("punc", "}")) break; + var start = S.token; + if (is("operator", "*")) { + next(); + var key = as_property_key(); + var gen_start = S.token; + var gen = function_(AST_GeneratorFunction); + gen.start = gen_start; + gen.end = prev(); + a.push(new AST_ObjectMethod({ + start: start, + key: key, + value: gen, + end: prev(), + })); + continue; + } + if (is("operator", "...")) { + next(); + a.push(new AST_Spread({ + start: start, + expression: maybe_assign(), + end: prev(), + })); + continue; + } + if (is_token(peek(), "operator", "=")) { + var name = as_symbol(AST_SymbolRef); + next(); + a.push(new AST_ObjectKeyVal({ + start: start, + key: start.value, + value: new AST_Assign({ + start: start, + left: name, + operator: "=", + right: maybe_assign(), + end: prev(), + }), + end: prev(), + })); + continue; + } + if (is_token(peek(), "punc", ",") || is_token(peek(), "punc", "}")) { + a.push(new AST_ObjectKeyVal({ + start: start, + key: start.value, + value: as_symbol(AST_SymbolRef), + end: prev(), + })); + continue; + } + var key = as_property_key(); + if (is("punc", "(")) { + var func_start = S.token; + var func = function_(AST_Function); + func.start = func_start; + func.end = prev(); + a.push(new AST_ObjectMethod({ + start: start, + key: key, + value: func, + end: prev(), + })); + continue; + } + if (is("punc", ":")) { + next(); + a.push(new AST_ObjectKeyVal({ + start: start, + key: key, + value: maybe_assign(), + end: prev(), + })); + continue; + } + if (start.type == "name") switch (key) { + case "async": + var is_gen = is("operator", "*") && next(); + key = as_property_key(); + var func_start = S.token; + var func = function_(is_gen ? AST_AsyncGeneratorFunction : AST_AsyncFunction); + func.start = func_start; + func.end = prev(); + a.push(new AST_ObjectMethod({ + start: start, + key: key, + value: func, + end: prev(), + })); + continue; + case "get": + a.push(new AST_ObjectGetter({ + start: start, + key: as_property_key(), + value: create_accessor(), + end: prev(), + })); + continue; + case "set": + a.push(new AST_ObjectSetter({ + start: start, + key: as_property_key(), + value: create_accessor(), + end: prev(), + })); + continue; + } + unexpected(); + } + next(); + return new AST_Object({ properties: a }); + }); + + function as_property_key() { + var tmp = S.token; + switch (tmp.type) { + case "operator": + if (!KEYWORDS[tmp.value]) unexpected(); + case "num": + case "string": + case "name": + case "keyword": + case "atom": + next(); + return "" + tmp.value; + case "punc": + expect("["); + var key = maybe_assign(); + expect("]"); + return key; + default: + unexpected(); + } + } + + function as_name() { + var name = S.token.value; + expect_token("name"); + return name; + } + + function _make_symbol(type, token) { + var name = token.value; + switch (name) { + case "await": + if (S.in_async) unexpected(token); + break; + case "super": + type = AST_Super; + break; + case "this": + type = AST_This; + break; + case "yield": + if (S.in_generator) unexpected(token); + break; + } + return new type({ + name: "" + name, + start: token, + end: token, + }); + } + + function strict_verify_symbol(sym) { + if (sym.name == "arguments" || sym.name == "eval" || sym.name == "let") + token_error(sym.start, "Unexpected " + sym.name + " in strict mode"); + } + + function as_symbol(type, no_error) { + if (!is("name")) { + if (!no_error) croak("Name expected"); + return null; + } + var sym = _make_symbol(type, S.token); + if (S.input.has_directive("use strict") && sym instanceof AST_SymbolDeclaration) { + strict_verify_symbol(sym); + } + next(); + return sym; + } + + function maybe_destructured(type) { + var start = S.token; + if (is("punc", "[")) { + next(); + var elements = expr_list("]", !options.strict, true, function() { + return maybe_default(type); + }); + return new AST_DestructuredArray({ + start: start, + elements: elements, + rest: elements.rest || null, + end: prev(), + }); + } + if (is("punc", "{")) { + next(); + var first = true, a = [], rest = null; + while (!is("punc", "}")) { + if (first) first = false; else expect(","); + // allow trailing comma + if (!options.strict && is("punc", "}")) break; + var key_start = S.token; + if (is("punc", "[") || is_token(peek(), "punc", ":")) { + var key = as_property_key(); + expect(":"); + a.push(new AST_DestructuredKeyVal({ + start: key_start, + key: key, + value: maybe_default(type), + end: prev(), + })); + continue; + } + if (is("operator", "...")) { + next(); + rest = maybe_destructured(type); + break; + } + var name = as_symbol(type); + if (is("operator", "=")) { + next(); + name = new AST_DefaultValue({ + start: name.start, + name: name, + value: maybe_assign(), + end: prev(), + }); + } + a.push(new AST_DestructuredKeyVal({ + start: key_start, + key: key_start.value, + value: name, + end: prev(), + })); + } + expect("}"); + return new AST_DestructuredObject({ + start: start, + properties: a, + rest: rest, + end: prev(), + }); + } + return as_symbol(type); + } + + function maybe_default(type) { + var start = S.token; + var name = maybe_destructured(type); + if (!is("operator", "=")) return name; + next(); + return new AST_DefaultValue({ + start: start, + name: name, + value: maybe_assign(), + end: prev(), + }); + } + + function template(tag) { + var start = tag ? tag.start : S.token; + var read = S.input.context().read_template; + var strings = []; + var expressions = []; + while (read(strings)) { + next(); + expressions.push(expression()); + if (!is("punc", "}")) unexpected(); + } + next(); + return new AST_Template({ + start: start, + expressions: expressions, + strings: strings, + tag: tag, + end: prev(), + }); + } + + function subscripts(expr, allow_calls) { + var start = expr.start; + var optional = null; + while (true) { + if (is("operator", "?") && is_token(peek(), "punc", ".")) { + next(); + next(); + optional = expr; + } + if (is("punc", "[")) { + next(); + var prop = expression(); + expect("]"); + expr = new AST_Sub({ + start: start, + optional: optional === expr, + expression: expr, + property: prop, + end: prev(), + }); + } else if (allow_calls && is("punc", "(")) { + next(); + expr = new AST_Call({ + start: start, + optional: optional === expr, + expression: expr, + args: expr_list(")", !options.strict), + end: prev(), + }); + } else if (optional === expr || is("punc", ".")) { + if (optional !== expr) next(); + expr = new AST_Dot({ + start: start, + optional: optional === expr, + expression: expr, + property: as_name(), + end: prev(), + }); + } else if (is("punc", "`")) { + if (optional) croak("Invalid template on optional chain"); + expr = template(expr); + } else { + break; + } + } + if (optional) expr.terminal = true; + if (expr instanceof AST_Call && !expr.pure) { + var start = expr.start; + var comments = start.comments_before; + var i = HOP(start, "comments_before_length") ? start.comments_before_length : comments.length; + while (--i >= 0) { + if (/[@#]__PURE__/.test(comments[i].value)) { + expr.pure = true; + break; + } + } + } + return expr; + } + + function maybe_unary(no_in) { + var start = S.token; + if (S.in_async && is("name", "await")) { + if (S.in_funarg === S.in_function) croak("Invalid use of await in function argument"); + S.input.context().regex_allowed = true; + next(); + return new AST_Await({ + start: start, + expression: maybe_unary(no_in), + end: prev(), + }); + } + if (S.in_generator && is("name", "yield")) { + if (S.in_funarg === S.in_function) croak("Invalid use of yield in function argument"); + S.input.context().regex_allowed = true; + next(); + var exp = null; + var nested = false; + if (is("operator", "*")) { + next(); + exp = maybe_assign(no_in); + nested = true; + } else if (is("punc") ? !PUNC_AFTER_EXPRESSION[S.token.value] : !can_insert_semicolon()) { + exp = maybe_assign(no_in); + } + return new AST_Yield({ + start: start, + expression: exp, + nested: nested, + end: prev(), + }); + } + if (is("operator") && UNARY_PREFIX[start.value]) { + next(); + handle_regexp(); + var ex = make_unary(AST_UnaryPrefix, start, maybe_unary(no_in)); + ex.start = start; + ex.end = prev(); + return ex; + } + var val = expr_atom(true); + while (is("operator") && UNARY_POSTFIX[S.token.value] && !has_newline_before(S.token)) { + val = make_unary(AST_UnaryPostfix, S.token, val); + val.start = start; + val.end = S.token; + next(); + } + return val; + } + + function make_unary(ctor, token, expr) { + var op = token.value; + switch (op) { + case "++": + case "--": + if (!is_assignable(expr)) + token_error(token, "Invalid use of " + op + " operator"); + break; + case "delete": + if (expr instanceof AST_SymbolRef && S.input.has_directive("use strict")) + token_error(expr.start, "Calling delete on expression not allowed in strict mode"); + break; + } + return new ctor({ operator: op, expression: expr }); + } + + var expr_op = function(left, min_precision, no_in) { + var op = is("operator") ? S.token.value : null; + if (op == "in" && no_in) op = null; + var precision = op != null ? PRECEDENCE[op] : null; + if (precision != null && precision > min_precision) { + next(); + var right = expr_op(maybe_unary(no_in), op == "**" ? precision - 1 : precision, no_in); + return expr_op(new AST_Binary({ + start : left.start, + left : left, + operator : op, + right : right, + end : right.end, + }), min_precision, no_in); + } + return left; + }; + + function expr_ops(no_in) { + return expr_op(maybe_unary(no_in), 0, no_in); + } + + var maybe_conditional = function(no_in) { + var start = S.token; + var expr = expr_ops(no_in); + if (is("operator", "?")) { + next(); + var yes = maybe_assign(); + expect(":"); + return new AST_Conditional({ + start : start, + condition : expr, + consequent : yes, + alternative : maybe_assign(no_in), + end : prev() + }); + } + return expr; + }; + + function is_assignable(expr) { + return expr instanceof AST_PropAccess && !expr.optional || expr instanceof AST_SymbolRef; + } + + function to_destructured(node) { + if (node instanceof AST_Array) { + var rest = null; + if (node.elements[node.elements.length - 1] instanceof AST_Spread) { + rest = to_destructured(node.elements.pop().expression); + if (!(rest instanceof AST_Destructured || is_assignable(rest))) return node; + } + var elements = node.elements.map(to_destructured); + return all(elements, function(node) { + return node instanceof AST_DefaultValue + || node instanceof AST_Destructured + || node instanceof AST_Hole + || is_assignable(node); + }) ? new AST_DestructuredArray({ + start: node.start, + elements: elements, + rest: rest, + end: node.end, + }) : node; + } + if (node instanceof AST_Assign) { + var name = to_destructured(node.left); + return name instanceof AST_Destructured || is_assignable(name) ? new AST_DefaultValue({ + start: node.start, + name: name, + value: node.right, + end: node.end, + }) : node; + } + if (!(node instanceof AST_Object)) return node; + var rest = null; + if (node.properties[node.properties.length - 1] instanceof AST_Spread) { + rest = to_destructured(node.properties.pop().expression); + if (!(rest instanceof AST_Destructured || is_assignable(rest))) return node; + } + var props = []; + for (var i = 0; i < node.properties.length; i++) { + var prop = node.properties[i]; + if (!(prop instanceof AST_ObjectKeyVal)) return node; + var value = to_destructured(prop.value); + if (!(value instanceof AST_DefaultValue || value instanceof AST_Destructured || is_assignable(value))) { + return node; + } + props.push(new AST_DestructuredKeyVal({ + start: prop.start, + key: prop.key, + value: value, + end: prop.end, + })); + } + return new AST_DestructuredObject({ + start: node.start, + properties: props, + rest: rest, + end: node.end, + }); + } + + function maybe_assign(no_in) { + var start = S.token; + var left = maybe_conditional(no_in), val = S.token.value; + if (is("operator") && ASSIGNMENT[val]) { + if (is_assignable(left) || val == "=" && (left = to_destructured(left)) instanceof AST_Destructured) { + next(); + return new AST_Assign({ + start : start, + left : left, + operator : val, + right : maybe_assign(no_in), + end : prev() + }); + } + croak("Invalid assignment"); + } + return left; + } + + function expression(no_in, maybe_arrow) { + var start = S.token; + var exprs = []; + while (true) { + if (maybe_arrow && is("operator", "...")) { + next(); + exprs.rest = maybe_destructured(AST_SymbolFunarg); + break; + } + exprs.push(maybe_assign(no_in)); + if (!is("punc", ",")) break; + next(); + if (maybe_arrow && is("punc", ")") && is_token(peek(), "punc", "=>")) break; + } + return exprs.length == 1 && !exprs.rest ? exprs[0] : new AST_Sequence({ + start: start, + expressions: exprs, + end: prev(), + }); + } + + function in_loop(cont) { + ++S.in_loop; + var ret = cont(); + --S.in_loop; + return ret; + } + + if (options.expression) { + handle_regexp(); + var exp = expression(); + expect_token("eof"); + return exp; + } + + return function() { + var start = S.token; + var body = []; + if (options.module) { + S.in_async = true; + S.input.add_directive("use strict"); + } + S.input.push_directives_stack(); + while (!is("eof")) + body.push(statement(true)); + S.input.pop_directives_stack(); + var end = prev() || start; + var toplevel = options.toplevel; + if (toplevel) { + toplevel.body = toplevel.body.concat(body); + toplevel.end = end; + } else { + toplevel = new AST_Toplevel({ start: start, body: body, end: end }); + } + return toplevel; + }(); +} diff --git a/node_modules/uglify-js/lib/propmangle.js b/node_modules/uglify-js/lib/propmangle.js new file mode 100644 index 0000000..3e71b68 --- /dev/null +++ b/node_modules/uglify-js/lib/propmangle.js @@ -0,0 +1,328 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function get_builtins() { + var names = new Dictionary(); + // constants + [ + "NaN", + "null", + "true", + "false", + "Infinity", + "-Infinity", + "undefined", + ].forEach(add); + // global functions + [ + "encodeURI", + "encodeURIComponent", + "escape", + "eval", + "decodeURI", + "decodeURIComponent", + "isFinite", + "isNaN", + "parseFloat", + "parseInt", + "unescape", + ].forEach(add); + // global constructors & objects + var global = Function("return this")(); + [ + "Array", + "ArrayBuffer", + "Atomics", + "BigInt", + "Boolean", + "console", + "DataView", + "Date", + "Error", + "Function", + "Int8Array", + "Intl", + "JSON", + "Map", + "Math", + "Number", + "Object", + "Promise", + "Proxy", + "Reflect", + "RegExp", + "Set", + "String", + "Symbol", + "WebAssembly", + ].forEach(function(name) { + add(name); + var ctor = global[name]; + if (!ctor) return; + Object.getOwnPropertyNames(ctor).map(add); + if (typeof ctor != "function") return; + if (ctor.__proto__) Object.getOwnPropertyNames(ctor.__proto__).map(add); + if (ctor.prototype) Object.getOwnPropertyNames(ctor.prototype).map(add); + try { + Object.getOwnPropertyNames(new ctor()).map(add); + } catch (e) { + try { + Object.getOwnPropertyNames(ctor()).map(add); + } catch (e) {} + } + }); + return (get_builtins = function() { + return names.clone(); + })(); + + function add(name) { + names.set(name, true); + } +} + +function reserve_quoted_keys(ast, reserved) { + ast.walk(new TreeWalker(function(node) { + if (node instanceof AST_ClassProperty + || node instanceof AST_DestructuredKeyVal + || node instanceof AST_ObjectProperty) { + if (node.key instanceof AST_Node) { + addStrings(node.key, add); + } else if (node.start && node.start.quote) { + add(node.key); + } + } else if (node instanceof AST_Dot) { + if (node.quoted) add(node.property); + } else if (node instanceof AST_Sub) { + addStrings(node.property, add); + } + })); + + function add(name) { + push_uniq(reserved, name); + } +} + +function addStrings(node, add) { + if (node instanceof AST_Conditional) { + addStrings(node.consequent, add); + addStrings(node.alternative, add); + } else if (node instanceof AST_Sequence) { + addStrings(node.tail_node(), add); + } else if (node instanceof AST_String) { + add(node.value); + } +} + +function mangle_properties(ast, options) { + options = defaults(options, { + builtins: false, + cache: null, + debug: false, + domprops: false, + keep_quoted: false, + regex: null, + reserved: null, + }, true); + + var reserved = options.builtins ? new Dictionary() : get_builtins(); + if (!options.domprops && typeof domprops !== "undefined") domprops.forEach(function(name) { + reserved.set(name, true); + }); + if (Array.isArray(options.reserved)) options.reserved.forEach(function(name) { + reserved.set(name, true); + }); + + var cname = -1; + var cache; + if (options.cache) { + cache = options.cache.props; + cache.each(function(name) { + reserved.set(name, true); + }); + } else { + cache = new Dictionary(); + } + + var regex = options.regex; + + // note debug is either false (disabled), or a string of the debug suffix to use (enabled). + // note debug may be enabled as an empty string, which is falsy. Also treat passing 'true' + // the same as passing an empty string. + var debug = options.debug !== false; + var debug_suffix; + if (debug) debug_suffix = options.debug === true ? "" : options.debug; + + var names_to_mangle = new Dictionary(); + var unmangleable = reserved.clone(); + + // step 1: find candidates to mangle + ast.walk(new TreeWalker(function(node) { + if (node.TYPE == "Call") { + var exp = node.expression; + if (exp instanceof AST_Dot) switch (exp.property) { + case "defineProperty": + case "getOwnPropertyDescriptor": + if (node.args.length < 2) break; + exp = exp.expression; + if (!(exp instanceof AST_SymbolRef)) break; + if (exp.name != "Object") break; + if (!exp.definition().undeclared) break; + addStrings(node.args[1], add); + break; + case "hasOwnProperty": + if (node.args.length < 1) break; + addStrings(node.args[0], add); + break; + } + } else if (node instanceof AST_ClassProperty + || node instanceof AST_DestructuredKeyVal + || node instanceof AST_ObjectProperty) { + if (node.key instanceof AST_Node) { + addStrings(node.key, add); + } else { + add(node.key); + } + } else if (node instanceof AST_Dot) { + if (is_lhs(node, this.parent())) add(node.property); + } else if (node instanceof AST_Sub) { + if (is_lhs(node, this.parent())) addStrings(node.property, add); + } + })); + + // step 2: renaming properties + ast.walk(new TreeWalker(function(node) { + if (node instanceof AST_Binary) { + if (node.operator == "in") mangleStrings(node.left); + } else if (node.TYPE == "Call") { + var exp = node.expression; + if (exp instanceof AST_Dot) switch (exp.property) { + case "defineProperty": + case "getOwnPropertyDescriptor": + if (node.args.length < 2) break; + exp = exp.expression; + if (!(exp instanceof AST_SymbolRef)) break; + if (exp.name != "Object") break; + if (!exp.definition().undeclared) break; + mangleStrings(node.args[1]); + break; + case "hasOwnProperty": + if (node.args.length < 1) break; + mangleStrings(node.args[0]); + break; + } + } else if (node instanceof AST_ClassProperty + || node instanceof AST_DestructuredKeyVal + || node instanceof AST_ObjectProperty) { + if (node.key instanceof AST_Node) { + mangleStrings(node.key); + } else { + node.key = mangle(node.key); + } + } else if (node instanceof AST_Dot) { + node.property = mangle(node.property); + } else if (node instanceof AST_Sub) { + if (!options.keep_quoted) mangleStrings(node.property); + } + })); + + // only function declarations after this line + + function can_mangle(name) { + if (unmangleable.has(name)) return false; + if (/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name)) return false; + return true; + } + + function should_mangle(name) { + if (reserved.has(name)) { + AST_Node.info("Preserving reserved property {this}", name); + return false; + } + if (regex && !regex.test(name)) { + AST_Node.info("Preserving excluded property {this}", name); + return false; + } + return cache.has(name) || names_to_mangle.has(name); + } + + function add(name) { + if (can_mangle(name)) names_to_mangle.set(name, true); + if (!should_mangle(name)) unmangleable.set(name, true); + } + + function mangle(name) { + if (!should_mangle(name)) return name; + var mangled = cache.get(name); + if (!mangled) { + if (debug) { + // debug mode: use a prefix and suffix to preserve readability, e.g. o.foo ---> o._$foo$NNN_. + var debug_mangled = "_$" + name + "$" + debug_suffix + "_"; + if (can_mangle(debug_mangled)) mangled = debug_mangled; + } + // either debug mode is off, or it is on and we could not use the mangled name + if (!mangled) do { + mangled = base54(++cname); + } while (!can_mangle(mangled)); + if (/^#/.test(name)) mangled = "#" + mangled; + cache.set(name, mangled); + } + AST_Node.info("Mapping property {name} to {mangled}", { + mangled: mangled, + name: name, + }); + return mangled; + } + + function mangleStrings(node) { + if (node instanceof AST_Sequence) { + mangleStrings(node.tail_node()); + } else if (node instanceof AST_String) { + node.value = mangle(node.value); + } else if (node instanceof AST_Conditional) { + mangleStrings(node.consequent); + mangleStrings(node.alternative); + } + } +} diff --git a/node_modules/uglify-js/lib/scope.js b/node_modules/uglify-js/lib/scope.js new file mode 100644 index 0000000..c2108c5 --- /dev/null +++ b/node_modules/uglify-js/lib/scope.js @@ -0,0 +1,866 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function SymbolDef(id, scope, orig, init) { + this._bits = 0; + this.defun = undefined; + this.eliminated = 0; + this.id = id; + this.init = init; + this.mangled_name = null; + this.name = orig.name; + this.orig = [ orig ]; + this.references = []; + this.replaced = 0; + this.safe_ids = undefined; + this.scope = scope; +} + +SymbolDef.prototype = { + forEach: function(fn) { + this.orig.forEach(fn); + this.references.forEach(fn); + }, + mangle: function(options) { + if (this.mangled_name) return; + var cache = this.global && options.cache && options.cache.props; + if (cache && cache.has(this.name)) { + this.mangled_name = cache.get(this.name); + } else if (this.unmangleable(options)) { + names_in_use(this.scope, options).set(this.name, true); + } else { + var def = this.redefined(); + if (def) { + this.mangled_name = def.mangled_name || def.name; + } else { + this.mangled_name = next_mangled_name(this, options); + } + if (cache) cache.set(this.name, this.mangled_name); + } + }, + redefined: function() { + var self = this; + var scope = self.defun; + if (!scope) return; + var name = self.name; + var def = scope.variables.get(name) + || scope instanceof AST_Toplevel && scope.globals.get(name) + || self.orig[0] instanceof AST_SymbolConst && find_if(function(def) { + return def.name == name; + }, scope.enclosed); + if (def && def !== self) return def.redefined() || def; + }, + unmangleable: function(options) { + if (this.exported) return true; + if (this.undeclared) return true; + if (!options.eval && this.scope.pinned()) return true; + if (options.keep_fargs && is_funarg(this)) return true; + if (options.keep_fnames) { + var sym = this.orig[0]; + if (sym instanceof AST_SymbolClass) return true; + if (sym instanceof AST_SymbolDefClass) return true; + if (sym instanceof AST_SymbolDefun) return true; + if (sym instanceof AST_SymbolLambda) return true; + } + if (!options.toplevel && this.global) return true; + return false; + }, +}; + +DEF_BITPROPS(SymbolDef, [ + "const_redefs", + "cross_loop", + "direct_access", + "exported", + "global", + "undeclared", +]); + +function is_funarg(def) { + return def.orig[0] instanceof AST_SymbolFunarg || def.orig[1] instanceof AST_SymbolFunarg; +} + +var unary_side_effects = makePredicate("delete ++ --"); + +function is_lhs(node, parent) { + if (parent instanceof AST_Assign) return parent.left === node && node; + if (parent instanceof AST_DefaultValue) return parent.name === node && node; + if (parent instanceof AST_Destructured) return node; + if (parent instanceof AST_DestructuredKeyVal) return node; + if (parent instanceof AST_ForEnumeration) return parent.init === node && node; + if (parent instanceof AST_Unary) return unary_side_effects[parent.operator] && parent.expression; +} + +AST_Toplevel.DEFMETHOD("figure_out_scope", function(options) { + options = defaults(options, { + cache: null, + ie: false, + }); + + // pass 1: setup scope chaining and handle definitions + var self = this; + var defun = null; + var exported = false; + var next_def_id = 0; + var scope = self.parent_scope = null; + var tw = new TreeWalker(function(node, descend) { + if (node instanceof AST_DefClass) { + var save_exported = exported; + exported = tw.parent() instanceof AST_ExportDeclaration; + node.name.walk(tw); + exported = save_exported; + walk_scope(function() { + if (node.extends) node.extends.walk(tw); + node.properties.forEach(function(prop) { + prop.walk(tw); + }); + }); + return true; + } + if (node instanceof AST_Definitions) { + var save_exported = exported; + exported = tw.parent() instanceof AST_ExportDeclaration; + descend(); + exported = save_exported; + return true; + } + if (node instanceof AST_LambdaDefinition) { + var save_exported = exported; + exported = tw.parent() instanceof AST_ExportDeclaration; + node.name.walk(tw); + exported = save_exported; + walk_scope(function() { + node.argnames.forEach(function(argname) { + argname.walk(tw); + }); + if (node.rest) node.rest.walk(tw); + walk_body(node, tw); + }); + return true; + } + if (node instanceof AST_SwitchBranch) { + node.init_vars(scope); + descend(); + return true; + } + if (node instanceof AST_Try) { + walk_scope(function() { + walk_body(node, tw); + }); + if (node.bcatch) node.bcatch.walk(tw); + if (node.bfinally) node.bfinally.walk(tw); + return true; + } + if (node instanceof AST_With) { + var s = scope; + do { + s = s.resolve(); + if (s.uses_with) break; + s.uses_with = true; + } while (s = s.parent_scope); + walk_scope(descend); + return true; + } + if (node instanceof AST_BlockScope) { + walk_scope(descend); + return true; + } + if (node instanceof AST_Symbol) { + node.scope = scope; + } + if (node instanceof AST_Label) { + node.thedef = node; + node.references = []; + } + if (node instanceof AST_SymbolCatch) { + scope.def_variable(node).defun = defun; + } else if (node instanceof AST_SymbolConst) { + var def = scope.def_variable(node); + def.defun = defun; + if (exported) def.exported = true; + } else if (node instanceof AST_SymbolDefun) { + var def = defun.def_function(node, tw.parent()); + if (exported) def.exported = true; + } else if (node instanceof AST_SymbolFunarg) { + defun.def_variable(node); + } else if (node instanceof AST_SymbolLambda) { + var def = defun.def_function(node, node.name == "arguments" ? undefined : defun); + if (options.ie && node.name != "arguments") def.defun = defun.parent_scope.resolve(); + } else if (node instanceof AST_SymbolLet) { + var def = scope.def_variable(node); + if (exported) def.exported = true; + } else if (node instanceof AST_SymbolVar) { + var def = defun.def_variable(node, node instanceof AST_SymbolImport ? undefined : null); + if (exported) def.exported = true; + } + + function walk_scope(descend) { + node.init_vars(scope); + var save_defun = defun; + var save_scope = scope; + if (node instanceof AST_Scope) defun = node; + scope = node; + descend(); + scope = save_scope; + defun = save_defun; + } + }); + self.make_def = function(orig, init) { + return new SymbolDef(++next_def_id, this, orig, init); + }; + self.walk(tw); + + // pass 2: find back references and eval + self.globals = new Dictionary(); + var in_arg = []; + var tw = new TreeWalker(function(node) { + if (node instanceof AST_Catch) { + if (!(node.argname instanceof AST_Destructured)) return; + in_arg.push(node); + node.argname.walk(tw); + in_arg.pop(); + walk_body(node, tw); + return true; + } + if (node instanceof AST_Lambda) { + in_arg.push(node); + if (node.name) node.name.walk(tw); + node.argnames.forEach(function(argname) { + argname.walk(tw); + }); + if (node.rest) node.rest.walk(tw); + in_arg.pop(); + walk_lambda(node, tw); + return true; + } + if (node instanceof AST_LoopControl) { + if (node.label) node.label.thedef.references.push(node); + return true; + } + if (node instanceof AST_SymbolDeclaration) { + var def = node.definition(); + def.preinit = def.references.length; + if (node instanceof AST_SymbolCatch) { + // ensure mangling works if `catch` reuses a scope variable + var redef = def.redefined(); + if (redef) for (var s = node.scope; s; s = s.parent_scope) { + if (!push_uniq(s.enclosed, redef)) break; + if (s === redef.scope) break; + } + } else if (node instanceof AST_SymbolConst) { + // ensure compression works if `const` reuses a scope variable + var redef = def.redefined(); + if (redef) redef.const_redefs = true; + } else if (def.scope !== node.scope && (node instanceof AST_SymbolDefun + || node instanceof AST_SymbolFunarg + || node instanceof AST_SymbolVar)) { + node.mark_enclosed(options); + var redef = node.scope.find_variable(node.name); + if (node.thedef !== redef) { + node.thedef = redef; + redef.orig.push(node); + node.mark_enclosed(options); + } + } + if (node.name != "arguments") return true; + var parent = node instanceof AST_SymbolVar && tw.parent(); + if (parent instanceof AST_VarDef && !parent.value) return true; + var sym = node.scope.resolve().find_variable("arguments"); + if (sym && is_arguments(sym)) sym.scope.uses_arguments = 3; + return true; + } + if (node instanceof AST_SymbolRef) { + var name = node.name; + var sym = node.scope.find_variable(name); + for (var i = in_arg.length; i > 0 && sym;) { + i = in_arg.lastIndexOf(sym.scope, i - 1); + if (i < 0) break; + var decl = sym.orig[0]; + if (decl instanceof AST_SymbolCatch + || decl instanceof AST_SymbolFunarg + || decl instanceof AST_SymbolLambda) { + node.in_arg = true; + break; + } + sym = sym.scope.parent_scope.find_variable(name); + } + if (!sym) { + sym = self.def_global(node); + } else if (name == "arguments" && is_arguments(sym)) { + var parent = tw.parent(); + if (is_lhs(node, parent)) { + sym.scope.uses_arguments = 3; + } else if (sym.scope.uses_arguments < 2 + && !(parent instanceof AST_PropAccess && parent.expression === node)) { + sym.scope.uses_arguments = 2; + } else if (!sym.scope.uses_arguments) { + sym.scope.uses_arguments = true; + } + } + if (name == "eval") { + var parent = tw.parent(); + if (parent.TYPE == "Call" && parent.expression === node) { + var s = node.scope; + do { + s = s.resolve(); + if (s.uses_eval) break; + s.uses_eval = true; + } while (s = s.parent_scope); + } else if (sym.undeclared) { + self.uses_eval = true; + } + } + if (sym.init instanceof AST_LambdaDefinition && sym.scope !== sym.init.name.scope) { + var scope = node.scope; + do { + if (scope === sym.init.name.scope) break; + } while (scope = scope.parent_scope); + if (!scope) sym.init = undefined; + } + node.thedef = sym; + node.reference(options); + return true; + } + }); + self.walk(tw); + + // pass 3: fix up any scoping issue with IE8 + if (options.ie) self.walk(new TreeWalker(function(node) { + if (node instanceof AST_SymbolCatch) { + var def = node.thedef; + var scope = def.defun; + if (def.name != "arguments" && scope.name instanceof AST_SymbolLambda && scope.name.name == def.name) { + scope = scope.parent_scope.resolve(); + } + redefine(node, scope); + return true; + } + if (node instanceof AST_SymbolLambda) { + var def = node.thedef; + if (!redefine(node, node.scope.parent_scope.resolve())) { + def.defun = undefined; + } else if (typeof node.thedef.init !== "undefined") { + node.thedef.init = false; + } else if (def.init) { + node.thedef.init = def.init; + } + return true; + } + })); + + function is_arguments(sym) { + return sym.orig[0] instanceof AST_SymbolFunarg + && !(sym.orig[1] instanceof AST_SymbolFunarg || sym.orig[2] instanceof AST_SymbolFunarg) + && !is_arrow(sym.scope); + } + + function redefine(node, scope) { + var name = node.name; + var old_def = node.thedef; + if (!all(old_def.orig, function(sym) { + return !(sym instanceof AST_SymbolConst || sym instanceof AST_SymbolLet); + })) return false; + var new_def = scope.find_variable(name); + if (new_def) { + var redef = new_def.redefined(); + if (redef) new_def = redef; + } else { + new_def = self.globals.get(name); + } + if (new_def) { + new_def.orig.push(node); + } else { + new_def = scope.def_variable(node); + } + if (new_def.undeclared) self.variables.set(name, new_def); + if (name == "arguments" && is_arguments(old_def) && node instanceof AST_SymbolLambda) return true; + old_def.defun = new_def.scope; + old_def.forEach(function(node) { + node.redef = old_def; + node.thedef = new_def; + node.reference(options); + }); + return true; + } +}); + +AST_Toplevel.DEFMETHOD("def_global", function(node) { + var globals = this.globals, name = node.name; + if (globals.has(name)) { + return globals.get(name); + } else { + var g = this.make_def(node); + g.undeclared = true; + g.global = true; + globals.set(name, g); + return g; + } +}); + +function init_block_vars(scope, parent) { + scope.enclosed = []; // variables from this or outer scope(s) that are referenced from this or inner scopes + scope.parent_scope = parent; // the parent scope (null if this is the top level) + scope.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope) + scope.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions) + if (parent) scope.make_def = parent.make_def; // top-level tracking of SymbolDef instances +} + +function init_scope_vars(scope, parent) { + init_block_vars(scope, parent); + scope.uses_eval = false; // will be set to true if this or nested scope uses the global `eval` + scope.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement +} + +AST_BlockScope.DEFMETHOD("init_vars", function(parent_scope) { + init_block_vars(this, parent_scope); +}); +AST_Scope.DEFMETHOD("init_vars", function(parent_scope) { + init_scope_vars(this, parent_scope); +}); +AST_Arrow.DEFMETHOD("init_vars", function(parent_scope) { + init_scope_vars(this, parent_scope); + return this; +}); +AST_AsyncArrow.DEFMETHOD("init_vars", function(parent_scope) { + init_scope_vars(this, parent_scope); +}); +AST_Lambda.DEFMETHOD("init_vars", function(parent_scope) { + init_scope_vars(this, parent_scope); + this.uses_arguments = false; + this.def_variable(new AST_SymbolFunarg({ + name: "arguments", + scope: this, + start: this.start, + end: this.end, + })); + return this; +}); + +AST_Symbol.DEFMETHOD("mark_enclosed", function(options) { + var def = this.definition(); + for (var s = this.scope; s; s = s.parent_scope) { + if (!push_uniq(s.enclosed, def)) break; + if (!options) { + s._var_names = undefined; + } else { + if (options.keep_fargs && s instanceof AST_Lambda) s.each_argname(function(arg) { + push_uniq(def.scope.enclosed, arg.definition()); + }); + if (options.keep_fnames) s.functions.each(function(d) { + push_uniq(def.scope.enclosed, d); + }); + } + if (s === def.scope) break; + } +}); + +AST_Symbol.DEFMETHOD("reference", function(options) { + this.definition().references.push(this); + this.mark_enclosed(options); +}); + +AST_BlockScope.DEFMETHOD("find_variable", function(name) { + return this.variables.get(name) + || this.parent_scope && this.parent_scope.find_variable(name); +}); + +AST_BlockScope.DEFMETHOD("def_function", function(symbol, init) { + var def = this.def_variable(symbol, init); + if (!def.init || def.init instanceof AST_LambdaDefinition) def.init = init; + this.functions.set(symbol.name, def); + return def; +}); + +AST_BlockScope.DEFMETHOD("def_variable", function(symbol, init) { + var def = this.variables.get(symbol.name); + if (def) { + def.orig.push(symbol); + if (def.init instanceof AST_LambdaExpression) def.init = init; + } else { + def = this.make_def(symbol, init); + this.variables.set(symbol.name, def); + def.global = !this.parent_scope; + } + return symbol.thedef = def; +}); + +function names_in_use(scope, options) { + var names = scope.names_in_use; + if (!names) { + scope.cname = -1; + scope.cname_holes = []; + scope.names_in_use = names = new Dictionary(); + var cache = options.cache && options.cache.props; + scope.enclosed.forEach(function(def) { + if (def.unmangleable(options)) names.set(def.name, true); + if (def.global && cache && cache.has(def.name)) { + names.set(cache.get(def.name), true); + } + }); + } + return names; +} + +function next_mangled_name(def, options) { + var scope = def.scope; + var in_use = names_in_use(scope, options); + var holes = scope.cname_holes; + var names = new Dictionary(); + var scopes = [ scope ]; + def.forEach(function(sym) { + var scope = sym.scope; + do { + if (member(scope, scopes)) break; + names_in_use(scope, options).each(function(marker, name) { + names.set(name, marker); + }); + scopes.push(scope); + } while (scope = scope.parent_scope); + }); + var name; + for (var i = 0; i < holes.length; i++) { + name = base54(holes[i]); + if (names.has(name)) continue; + holes.splice(i, 1); + in_use.set(name, true); + return name; + } + while (true) { + name = base54(++scope.cname); + if (in_use.has(name) || RESERVED_WORDS[name] || options.reserved.has[name]) continue; + if (!names.has(name)) break; + holes.push(scope.cname); + } + in_use.set(name, true); + return name; +} + +AST_Symbol.DEFMETHOD("unmangleable", function(options) { + var def = this.definition(); + return !def || def.unmangleable(options); +}); + +// labels are always mangleable +AST_Label.DEFMETHOD("unmangleable", return_false); + +AST_Symbol.DEFMETHOD("definition", function() { + return this.thedef; +}); + +function _default_mangler_options(options) { + options = defaults(options, { + eval : false, + ie : false, + keep_fargs : false, + keep_fnames : false, + reserved : [], + toplevel : false, + v8 : false, + webkit : false, + }); + if (!Array.isArray(options.reserved)) options.reserved = []; + // Never mangle `arguments` + push_uniq(options.reserved, "arguments"); + options.reserved.has = makePredicate(options.reserved); + return options; +} + +// We only need to mangle declaration nodes. Special logic wired into the code +// generator will display the mangled name if it is present (and for +// `AST_SymbolRef`s it will use the mangled name of the `AST_SymbolDeclaration` +// that it points to). +AST_Toplevel.DEFMETHOD("mangle_names", function(options) { + options = _default_mangler_options(options); + if (options.cache && options.cache.props) { + var mangled_names = names_in_use(this, options); + options.cache.props.each(function(mangled_name) { + mangled_names.set(mangled_name, true); + }); + } + var cutoff = 36; + var lname = -1; + var redefined = []; + var tw = new TreeWalker(function(node, descend) { + var save_nesting; + if (node instanceof AST_BlockScope) { + // `lname` is incremented when we get to the `AST_Label` + if (node instanceof AST_LabeledStatement) save_nesting = lname; + if (options.webkit && node instanceof AST_IterationStatement && node.init instanceof AST_Let) { + node.init.definitions.forEach(function(defn) { + defn.name.match_symbol(function(sym) { + if (!(sym instanceof AST_SymbolLet)) return; + var def = sym.definition(); + var scope = sym.scope.parent_scope; + var redef = scope.def_variable(sym); + sym.thedef = def; + scope.to_mangle.push(redef); + def.redefined = function() { + return redef; + }; + }); + }, true); + } + var to_mangle = node.to_mangle = []; + node.variables.each(function(def) { + if (!defer_redef(def)) to_mangle.push(def); + }); + descend(); + if (options.cache && node instanceof AST_Toplevel) { + node.globals.each(mangle); + } + if (node instanceof AST_Defun && tw.has_directive("use asm")) { + var sym = new AST_SymbolRef(node.name); + sym.scope = node; + sym.reference(options); + } + if (to_mangle.length > cutoff) { + var indices = to_mangle.map(function(def, index) { + return index; + }).sort(function(i, j) { + return to_mangle[j].references.length - to_mangle[i].references.length || i - j; + }); + to_mangle = indices.slice(0, cutoff).sort(function(i, j) { + return i - j; + }).map(function(index) { + return to_mangle[index]; + }).concat(indices.slice(cutoff).sort(function(i, j) { + return i - j; + }).map(function(index) { + return to_mangle[index]; + })); + } + to_mangle.forEach(mangle); + if (node instanceof AST_LabeledStatement && !(options.v8 && in_label(tw))) lname = save_nesting; + return true; + } + if (node instanceof AST_Label) { + var name; + do { + name = base54(++lname); + } while (RESERVED_WORDS[name]); + node.mangled_name = name; + return true; + } + }); + this.walk(tw); + redefined.forEach(mangle); + + function mangle(def) { + if (options.reserved.has[def.name]) return; + def.mangle(options); + } + + function defer_redef(def) { + var sym = def.orig[0]; + var redef = def.redefined(); + if (!redef) { + if (!(sym instanceof AST_SymbolConst)) return false; + var scope = def.scope.resolve(); + if (def.scope === scope) return false; + if (def.scope.parent_scope.find_variable(sym.name)) return false; + redef = scope.def_variable(sym); + scope.to_mangle.push(redef); + } + redefined.push(def); + def.references.forEach(reference); + if (sym instanceof AST_SymbolCatch || sym instanceof AST_SymbolConst) { + reference(sym); + def.redefined = function() { + return redef; + }; + } + return true; + + function reference(sym) { + sym.thedef = redef; + sym.reference(options); + sym.thedef = def; + } + } + + function in_label(tw) { + var level = 0, parent; + while (parent = tw.parent(level++)) { + if (parent instanceof AST_Block) return parent instanceof AST_Toplevel && !options.toplevel; + if (parent instanceof AST_LabeledStatement) return true; + } + } +}); + +AST_Toplevel.DEFMETHOD("find_colliding_names", function(options) { + var cache = options.cache && options.cache.props; + var avoid = Object.create(RESERVED_WORDS); + options.reserved.forEach(to_avoid); + this.globals.each(add_def); + this.walk(new TreeWalker(function(node) { + if (node instanceof AST_BlockScope) node.variables.each(add_def); + })); + return avoid; + + function to_avoid(name) { + avoid[name] = true; + } + + function add_def(def) { + var name = def.name; + if (def.global && cache && cache.has(name)) name = cache.get(name); + else if (!def.unmangleable(options)) return; + to_avoid(name); + } +}); + +AST_Toplevel.DEFMETHOD("expand_names", function(options) { + base54.reset(); + base54.sort(); + options = _default_mangler_options(options); + var avoid = this.find_colliding_names(options); + var cname = 0; + this.globals.each(rename); + this.walk(new TreeWalker(function(node) { + if (node instanceof AST_BlockScope) node.variables.each(rename); + })); + + function next_name() { + var name; + do { + name = base54(cname++); + } while (avoid[name]); + return name; + } + + function rename(def) { + if (def.global && options.cache) return; + if (def.unmangleable(options)) return; + if (options.reserved.has[def.name]) return; + var redef = def.redefined(); + var name = redef ? redef.rename || redef.name : next_name(); + def.rename = name; + def.forEach(function(sym) { + if (sym.definition() === def) sym.name = name; + }); + } +}); + +AST_Node.DEFMETHOD("tail_node", return_this); +AST_Sequence.DEFMETHOD("tail_node", function() { + return this.expressions[this.expressions.length - 1]; +}); + +AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options) { + options = _default_mangler_options(options); + base54.reset(); + var fn = AST_Symbol.prototype.add_source_map; + try { + AST_Symbol.prototype.add_source_map = function() { + if (!this.unmangleable(options)) base54.consider(this.name, -1); + }; + if (options.properties) { + AST_Dot.prototype.add_source_map = function() { + base54.consider(this.property, -1); + }; + AST_Sub.prototype.add_source_map = function() { + skip_string(this.property); + }; + } + base54.consider(this.print_to_string(), 1); + } finally { + AST_Symbol.prototype.add_source_map = fn; + delete AST_Dot.prototype.add_source_map; + delete AST_Sub.prototype.add_source_map; + } + base54.sort(); + + function skip_string(node) { + if (node instanceof AST_String) { + base54.consider(node.value, -1); + } else if (node instanceof AST_Conditional) { + skip_string(node.consequent); + skip_string(node.alternative); + } else if (node instanceof AST_Sequence) { + skip_string(node.tail_node()); + } + } +}); + +var base54 = (function() { + var freq = Object.create(null); + function init(chars) { + var array = []; + for (var i = 0; i < chars.length; i++) { + var ch = chars[i]; + array.push(ch); + freq[ch] = -1e-2 * i; + } + return array; + } + var digits = init("0123456789"); + var leading = init("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_"); + var chars, frequency; + function reset() { + chars = null; + frequency = Object.create(freq); + } + base54.consider = function(str, delta) { + for (var i = str.length; --i >= 0;) { + frequency[str[i]] += delta; + } + }; + function compare(a, b) { + return frequency[b] - frequency[a]; + } + base54.sort = function() { + chars = leading.sort(compare).concat(digits).sort(compare); + }; + base54.reset = reset; + reset(); + function base54(num) { + var ret = leading[num % 54]; + for (num = Math.floor(num / 54); --num >= 0; num >>= 6) { + ret += chars[num & 0x3F]; + } + return ret; + } + return base54; +})(); diff --git a/node_modules/uglify-js/lib/sourcemap.js b/node_modules/uglify-js/lib/sourcemap.js new file mode 100644 index 0000000..a230a44 --- /dev/null +++ b/node_modules/uglify-js/lib/sourcemap.js @@ -0,0 +1,195 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +var vlq_char = characters("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"); +var vlq_bits = vlq_char.reduce(function(map, ch, bits) { + map[ch] = bits; + return map; +}, Object.create(null)); + +function vlq_decode(indices, str) { + var value = 0; + var shift = 0; + for (var i = 0, j = 0; i < str.length; i++) { + var bits = vlq_bits[str[i]]; + value += (bits & 31) << shift; + if (bits & 32) { + shift += 5; + } else { + indices[j++] += value & 1 ? 0x80000000 | -(value >> 1) : value >> 1; + value = shift = 0; + } + } + return j; +} + +function vlq_encode(num) { + var result = ""; + num = Math.abs(num) << 1 | num >>> 31; + do { + var bits = num & 31; + if (num >>>= 5) bits |= 32; + result += vlq_char[bits]; + } while (num); + return result; +} + +function create_array_map() { + var map = new Dictionary(); + var array = []; + array.index = function(name) { + var index = map.get(name); + if (!(index >= 0)) { + index = array.length; + array.push(name); + map.set(name, index); + } + return index; + }; + return array; +} + +function SourceMap(options) { + var sources = create_array_map(); + var sources_content = options.includeSources && new Dictionary(); + var names = create_array_map(); + var mappings = ""; + if (options.orig) Object.keys(options.orig).forEach(function(name) { + var map = options.orig[name]; + var indices = [ 0, 0, 1, 0, 0 ]; + options.orig[name] = { + names: map.names, + mappings: map.mappings.split(/;/).map(function(line) { + indices[0] = 0; + return line.split(/,/).map(function(segment) { + return indices.slice(0, vlq_decode(indices, segment)); + }); + }), + sources: map.sources, + }; + if (!sources_content || !map.sourcesContent) return; + for (var i = 0; i < map.sources.length; i++) { + var content = map.sourcesContent[i]; + if (content) sources_content.set(map.sources[i], content); + } + }); + var prev_source; + var generated_line = 1; + var generated_column = 0; + var source_index = 0; + var original_line = 1; + var original_column = 0; + var name_index = 0; + return { + add: options.orig ? function(source, gen_line, gen_col, orig_line, orig_col, name) { + var map = options.orig[source]; + if (map) { + var segments = map.mappings[orig_line - 1]; + if (!segments) return; + var indices; + for (var i = 0; i < segments.length; i++) { + var col = segments[i][0]; + if (orig_col >= col) indices = segments[i]; + if (orig_col <= col) break; + } + if (!indices || indices.length < 4) { + source = null; + } else { + source = map.sources[indices[1]]; + orig_line = indices[2]; + orig_col = indices[3]; + if (indices.length > 4) name = map.names[indices[4]]; + } + } + add(source, gen_line, gen_col, orig_line, orig_col, name); + } : add, + setSourceContent: sources_content ? function(source, content) { + if (!sources_content.has(source)) { + sources_content.set(source, content); + } + } : noop, + toString: function() { + return JSON.stringify({ + version: 3, + file: options.filename || undefined, + sourceRoot: options.root || undefined, + sources: sources, + sourcesContent: sources_content ? sources.map(function(source) { + return sources_content.get(source) || null; + }) : undefined, + names: names, + mappings: mappings, + }); + } + }; + + function add(source, gen_line, gen_col, orig_line, orig_col, name) { + if (prev_source == null && source == null) return; + prev_source = source; + if (generated_line < gen_line) { + generated_column = 0; + do { + mappings += ";"; + } while (++generated_line < gen_line); + } else if (mappings) { + mappings += ","; + } + mappings += vlq_encode(gen_col - generated_column); + generated_column = gen_col; + if (source == null) return; + var src_idx = sources.index(source); + mappings += vlq_encode(src_idx - source_index); + source_index = src_idx; + mappings += vlq_encode(orig_line - original_line); + original_line = orig_line; + mappings += vlq_encode(orig_col - original_column); + original_column = orig_col; + if (options.names && name != null) { + var name_idx = names.index(name); + mappings += vlq_encode(name_idx - name_index); + name_index = name_idx; + } + } +} diff --git a/node_modules/uglify-js/lib/transform.js b/node_modules/uglify-js/lib/transform.js new file mode 100644 index 0000000..dcf90df --- /dev/null +++ b/node_modules/uglify-js/lib/transform.js @@ -0,0 +1,250 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function TreeTransformer(before, after) { + TreeWalker.call(this); + this.before = before; + this.after = after; +} +TreeTransformer.prototype = new TreeWalker; + +(function(DEF) { + function do_list(list, tw) { + return List(list, function(node) { + return node.transform(tw, true); + }); + } + + DEF(AST_Node, noop); + DEF(AST_LabeledStatement, function(self, tw) { + self.label = self.label.transform(tw); + self.body = self.body.transform(tw); + }); + DEF(AST_SimpleStatement, function(self, tw) { + self.body = self.body.transform(tw); + }); + DEF(AST_Block, function(self, tw) { + self.body = do_list(self.body, tw); + }); + DEF(AST_Do, function(self, tw) { + self.body = self.body.transform(tw); + self.condition = self.condition.transform(tw); + }); + DEF(AST_While, function(self, tw) { + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); + }); + DEF(AST_For, function(self, tw) { + if (self.init) self.init = self.init.transform(tw); + if (self.condition) self.condition = self.condition.transform(tw); + if (self.step) self.step = self.step.transform(tw); + self.body = self.body.transform(tw); + }); + DEF(AST_ForEnumeration, function(self, tw) { + self.init = self.init.transform(tw); + self.object = self.object.transform(tw); + self.body = self.body.transform(tw); + }); + DEF(AST_With, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = self.body.transform(tw); + }); + DEF(AST_Exit, function(self, tw) { + if (self.value) self.value = self.value.transform(tw); + }); + DEF(AST_LoopControl, function(self, tw) { + if (self.label) self.label = self.label.transform(tw); + }); + DEF(AST_If, function(self, tw) { + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); + if (self.alternative) self.alternative = self.alternative.transform(tw); + }); + DEF(AST_Switch, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); + }); + DEF(AST_Case, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); + }); + DEF(AST_Try, function(self, tw) { + self.body = do_list(self.body, tw); + if (self.bcatch) self.bcatch = self.bcatch.transform(tw); + if (self.bfinally) self.bfinally = self.bfinally.transform(tw); + }); + DEF(AST_Catch, function(self, tw) { + if (self.argname) self.argname = self.argname.transform(tw); + self.body = do_list(self.body, tw); + }); + DEF(AST_Definitions, function(self, tw) { + self.definitions = do_list(self.definitions, tw); + }); + DEF(AST_VarDef, function(self, tw) { + self.name = self.name.transform(tw); + if (self.value) self.value = self.value.transform(tw); + }); + DEF(AST_DefaultValue, function(self, tw) { + self.name = self.name.transform(tw); + self.value = self.value.transform(tw); + }); + DEF(AST_Lambda, function(self, tw) { + if (self.name) self.name = self.name.transform(tw); + self.argnames = do_list(self.argnames, tw); + if (self.rest) self.rest = self.rest.transform(tw); + self.body = do_list(self.body, tw); + }); + function transform_arrow(self, tw) { + self.argnames = do_list(self.argnames, tw); + if (self.rest) self.rest = self.rest.transform(tw); + if (self.value) { + self.value = self.value.transform(tw); + } else { + self.body = do_list(self.body, tw); + } + } + DEF(AST_Arrow, transform_arrow); + DEF(AST_AsyncArrow, transform_arrow); + DEF(AST_Class, function(self, tw) { + if (self.name) self.name = self.name.transform(tw); + if (self.extends) self.extends = self.extends.transform(tw); + self.properties = do_list(self.properties, tw); + }); + DEF(AST_ClassProperty, function(self, tw) { + if (self.key instanceof AST_Node) self.key = self.key.transform(tw); + if (self.value) self.value = self.value.transform(tw); + }); + DEF(AST_Call, function(self, tw) { + self.expression = self.expression.transform(tw); + self.args = do_list(self.args, tw); + }); + DEF(AST_Sequence, function(self, tw) { + self.expressions = do_list(self.expressions, tw); + }); + DEF(AST_Await, function(self, tw) { + self.expression = self.expression.transform(tw); + }); + DEF(AST_Yield, function(self, tw) { + if (self.expression) self.expression = self.expression.transform(tw); + }); + DEF(AST_Dot, function(self, tw) { + self.expression = self.expression.transform(tw); + }); + DEF(AST_Sub, function(self, tw) { + self.expression = self.expression.transform(tw); + self.property = self.property.transform(tw); + }); + DEF(AST_Spread, function(self, tw) { + self.expression = self.expression.transform(tw); + }); + DEF(AST_Unary, function(self, tw) { + self.expression = self.expression.transform(tw); + }); + DEF(AST_Binary, function(self, tw) { + self.left = self.left.transform(tw); + self.right = self.right.transform(tw); + }); + DEF(AST_Conditional, function(self, tw) { + self.condition = self.condition.transform(tw); + self.consequent = self.consequent.transform(tw); + self.alternative = self.alternative.transform(tw); + }); + DEF(AST_Array, function(self, tw) { + self.elements = do_list(self.elements, tw); + }); + DEF(AST_DestructuredArray, function(self, tw) { + self.elements = do_list(self.elements, tw); + if (self.rest) self.rest = self.rest.transform(tw); + }); + DEF(AST_DestructuredKeyVal, function(self, tw) { + if (self.key instanceof AST_Node) self.key = self.key.transform(tw); + self.value = self.value.transform(tw); + }); + DEF(AST_DestructuredObject, function(self, tw) { + self.properties = do_list(self.properties, tw); + if (self.rest) self.rest = self.rest.transform(tw); + }); + DEF(AST_Object, function(self, tw) { + self.properties = do_list(self.properties, tw); + }); + DEF(AST_ObjectProperty, function(self, tw) { + if (self.key instanceof AST_Node) self.key = self.key.transform(tw); + self.value = self.value.transform(tw); + }); + DEF(AST_ExportDeclaration, function(self, tw) { + self.body = self.body.transform(tw); + }); + DEF(AST_ExportDefault, function(self, tw) { + self.body = self.body.transform(tw); + }); + DEF(AST_ExportReferences, function(self, tw) { + self.properties = do_list(self.properties, tw); + }); + DEF(AST_Import, function(self, tw) { + if (self.all) self.all = self.all.transform(tw); + if (self.default) self.default = self.default.transform(tw); + if (self.properties) self.properties = do_list(self.properties, tw); + }); + DEF(AST_Template, function(self, tw) { + if (self.tag) self.tag = self.tag.transform(tw); + self.expressions = do_list(self.expressions, tw); + }); +})(function(node, descend) { + node.DEFMETHOD("transform", function(tw, in_list) { + var x, y; + tw.push(this); + if (tw.before) x = tw.before(this, descend, in_list); + if (typeof x === "undefined") { + x = this; + descend(x, tw); + if (tw.after) { + y = tw.after(x, in_list); + if (typeof y !== "undefined") x = y; + } + } + tw.pop(); + return x; + }); +}); diff --git a/node_modules/uglify-js/lib/utils.js b/node_modules/uglify-js/lib/utils.js new file mode 100644 index 0000000..6faaa15 --- /dev/null +++ b/node_modules/uglify-js/lib/utils.js @@ -0,0 +1,287 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function characters(str) { + return str.split(""); +} + +function member(name, array) { + return array.indexOf(name) >= 0; +} + +function find_if(func, array) { + for (var i = array.length; --i >= 0;) if (func(array[i])) return array[i]; +} + +function configure_error_stack(fn) { + Object.defineProperty(fn.prototype, "stack", { + get: function() { + var err = new Error(this.message); + err.name = this.name; + try { + throw err; + } catch (e) { + return e.stack; + } + } + }); +} + +function DefaultsError(msg, defs) { + this.message = msg; + this.defs = defs; +} +DefaultsError.prototype = Object.create(Error.prototype); +DefaultsError.prototype.constructor = DefaultsError; +DefaultsError.prototype.name = "DefaultsError"; +configure_error_stack(DefaultsError); + +function defaults(args, defs, croak) { + if (croak) for (var i in args) { + if (HOP(args, i) && !HOP(defs, i)) throw new DefaultsError("`" + i + "` is not a supported option", defs); + } + for (var i in args) { + if (HOP(args, i)) defs[i] = args[i]; + } + return defs; +} + +function noop() {} +function return_false() { return false; } +function return_true() { return true; } +function return_this() { return this; } +function return_null() { return null; } + +var List = (function() { + function List(a, f) { + var ret = []; + for (var i = 0; i < a.length; i++) { + var val = f(a[i], i); + if (val === skip) continue; + if (val instanceof Splice) { + ret.push.apply(ret, val.v); + } else { + ret.push(val); + } + } + return ret; + } + List.is_op = function(val) { + return val === skip || val instanceof Splice; + }; + List.splice = function(val) { + return new Splice(val); + }; + var skip = List.skip = {}; + function Splice(val) { + this.v = val; + } + return List; +})(); + +function push_uniq(array, el) { + if (array.indexOf(el) < 0) return array.push(el); +} + +function string_template(text, props) { + return text.replace(/\{([^{}]+)\}/g, function(str, p) { + var value = p == "this" ? props : props[p]; + if (value instanceof AST_Node) return value.print_to_string(); + if (value instanceof AST_Token) return value.file + ":" + value.line + "," + value.col; + return value; + }); +} + +function remove(array, el) { + var index = array.indexOf(el); + if (index >= 0) array.splice(index, 1); +} + +function makePredicate(words) { + if (!Array.isArray(words)) words = words.split(" "); + var map = Object.create(null); + words.forEach(function(word) { + map[word] = true; + }); + return map; +} + +function all(array, predicate) { + for (var i = array.length; --i >= 0;) + if (!predicate(array[i], i)) + return false; + return true; +} + +function Dictionary() { + this.values = Object.create(null); +} +Dictionary.prototype = { + set: function(key, val) { + if (key == "__proto__") { + this.proto_value = val; + } else { + this.values[key] = val; + } + return this; + }, + add: function(key, val) { + var list = this.get(key); + if (list) { + list.push(val); + } else { + this.set(key, [ val ]); + } + return this; + }, + get: function(key) { + return key == "__proto__" ? this.proto_value : this.values[key]; + }, + del: function(key) { + if (key == "__proto__") { + delete this.proto_value; + } else { + delete this.values[key]; + } + return this; + }, + has: function(key) { + return key == "__proto__" ? "proto_value" in this : key in this.values; + }, + all: function(predicate) { + for (var i in this.values) + if (!predicate(this.values[i], i)) return false; + if ("proto_value" in this && !predicate(this.proto_value, "__proto__")) return false; + return true; + }, + each: function(f) { + for (var i in this.values) + f(this.values[i], i); + if ("proto_value" in this) f(this.proto_value, "__proto__"); + }, + size: function() { + return Object.keys(this.values).length + ("proto_value" in this); + }, + map: function(f) { + var ret = []; + for (var i in this.values) + ret.push(f(this.values[i], i)); + if ("proto_value" in this) ret.push(f(this.proto_value, "__proto__")); + return ret; + }, + clone: function() { + var ret = new Dictionary(); + this.each(function(value, i) { + ret.set(i, value); + }); + return ret; + }, + toObject: function() { + var obj = {}; + this.each(function(value, i) { + obj["$" + i] = value; + }); + return obj; + }, +}; +Dictionary.fromObject = function(obj) { + var dict = new Dictionary(); + for (var i in obj) + if (HOP(obj, i)) dict.set(i.slice(1), obj[i]); + return dict; +}; + +function HOP(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +// return true if the node at the top of the stack (that means the +// innermost node in the current output) is lexically the first in +// a statement. +function first_in_statement(stack, arrow, export_default) { + var node = stack.parent(-1); + for (var i = 0, p; p = stack.parent(i++); node = p) { + if (is_arrow(p)) { + return arrow && p.value === node; + } else if (p instanceof AST_Binary) { + if (p.left === node) continue; + } else if (p.TYPE == "Call") { + if (p.expression === node) continue; + } else if (p instanceof AST_Conditional) { + if (p.condition === node) continue; + } else if (p instanceof AST_ExportDefault) { + return export_default; + } else if (p instanceof AST_PropAccess) { + if (p.expression === node) continue; + } else if (p instanceof AST_Sequence) { + if (p.expressions[0] === node) continue; + } else if (p instanceof AST_SimpleStatement) { + return true; + } else if (p instanceof AST_Template) { + if (p.tag === node) continue; + } else if (p instanceof AST_UnaryPostfix) { + if (p.expression === node) continue; + } + return false; + } +} + +function DEF_BITPROPS(ctor, props) { + if (props.length > 31) throw new Error("Too many properties: " + props.length + "\n" + props.join(", ")); + props.forEach(function(name, pos) { + var mask = 1 << pos; + Object.defineProperty(ctor.prototype, name, { + get: function() { + return !!(this._bits & mask); + }, + set: function(val) { + if (val) + this._bits |= mask; + else + this._bits &= ~mask; + }, + }); + }); +} diff --git a/node_modules/uglify-js/package.json b/node_modules/uglify-js/package.json new file mode 100644 index 0000000..5776de1 --- /dev/null +++ b/node_modules/uglify-js/package.json @@ -0,0 +1,56 @@ +{ + "name": "uglify-js", + "description": "JavaScript parser, mangler/compressor and beautifier toolkit", + "author": "Mihai Bazon (http://lisperator.net/)", + "license": "BSD-2-Clause", + "version": "3.17.4", + "engines": { + "node": ">=0.8.0" + }, + "maintainers": [ + "Alex Lam ", + "Mihai Bazon (http://lisperator.net/)" + ], + "repository": "mishoo/UglifyJS", + "main": "tools/node.js", + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "files": [ + "bin", + "lib", + "tools", + "LICENSE" + ], + "devDependencies": { + "acorn": "~8.7.1", + "semver": "~6.3.0" + }, + "scripts": { + "test": "node test/compress.js && node test/mocha.js" + }, + "keywords": [ + "cli", + "compress", + "compressor", + "ecma", + "ecmascript", + "es", + "es5", + "javascript", + "js", + "jsmin", + "min", + "minification", + "minifier", + "minify", + "optimize", + "optimizer", + "pack", + "packer", + "parse", + "parser", + "uglifier", + "uglify" + ] +} diff --git a/node_modules/uglify-js/tools/domprops.html b/node_modules/uglify-js/tools/domprops.html new file mode 100644 index 0000000..e217b17 --- /dev/null +++ b/node_modules/uglify-js/tools/domprops.html @@ -0,0 +1,456 @@ + + + + + + diff --git a/node_modules/uglify-js/tools/domprops.json b/node_modules/uglify-js/tools/domprops.json new file mode 100644 index 0000000..1045429 --- /dev/null +++ b/node_modules/uglify-js/tools/domprops.json @@ -0,0 +1,8325 @@ +[ + "$&", + "$'", + "$*", + "$+", + "$1", + "$2", + "$3", + "$4", + "$5", + "$6", + "$7", + "$8", + "$9", + "$_", + "$`", + "$input", + "-moz-animation", + "-moz-animation-delay", + "-moz-animation-direction", + "-moz-animation-duration", + "-moz-animation-fill-mode", + "-moz-animation-iteration-count", + "-moz-animation-name", + "-moz-animation-play-state", + "-moz-animation-timing-function", + "-moz-appearance", + "-moz-backface-visibility", + "-moz-binding", + "-moz-border-end", + "-moz-border-end-color", + "-moz-border-end-style", + "-moz-border-end-width", + "-moz-border-image", + "-moz-border-start", + "-moz-border-start-color", + "-moz-border-start-style", + "-moz-border-start-width", + "-moz-box-align", + "-moz-box-direction", + "-moz-box-flex", + "-moz-box-ordinal-group", + "-moz-box-orient", + "-moz-box-pack", + "-moz-box-sizing", + "-moz-column-count", + "-moz-column-fill", + "-moz-column-gap", + "-moz-column-rule", + "-moz-column-rule-color", + "-moz-column-rule-style", + "-moz-column-rule-width", + "-moz-column-width", + "-moz-columns", + "-moz-float-edge", + "-moz-font-feature-settings", + "-moz-font-language-override", + "-moz-force-broken-image-icon", + "-moz-hyphens", + "-moz-image-region", + "-moz-margin-end", + "-moz-margin-start", + "-moz-orient", + "-moz-outline-radius", + "-moz-outline-radius-bottomleft", + "-moz-outline-radius-bottomright", + "-moz-outline-radius-topleft", + "-moz-outline-radius-topright", + "-moz-padding-end", + "-moz-padding-start", + "-moz-perspective", + "-moz-perspective-origin", + "-moz-stack-sizing", + "-moz-tab-size", + "-moz-text-size-adjust", + "-moz-transform", + "-moz-transform-origin", + "-moz-transform-style", + "-moz-transition", + "-moz-transition-delay", + "-moz-transition-duration", + "-moz-transition-property", + "-moz-transition-timing-function", + "-moz-user-focus", + "-moz-user-input", + "-moz-user-modify", + "-moz-user-select", + "-moz-window-dragging", + "-webkit-align-content", + "-webkit-align-items", + "-webkit-align-self", + "-webkit-animation", + "-webkit-animation-delay", + "-webkit-animation-direction", + "-webkit-animation-duration", + "-webkit-animation-fill-mode", + "-webkit-animation-iteration-count", + "-webkit-animation-name", + "-webkit-animation-play-state", + "-webkit-animation-timing-function", + "-webkit-appearance", + "-webkit-backface-visibility", + "-webkit-background-clip", + "-webkit-background-origin", + "-webkit-background-size", + "-webkit-border-bottom-left-radius", + "-webkit-border-bottom-right-radius", + "-webkit-border-image", + "-webkit-border-radius", + "-webkit-border-top-left-radius", + "-webkit-border-top-right-radius", + "-webkit-box-align", + "-webkit-box-direction", + "-webkit-box-flex", + "-webkit-box-ordinal-group", + "-webkit-box-orient", + "-webkit-box-pack", + "-webkit-box-shadow", + "-webkit-box-sizing", + "-webkit-filter", + "-webkit-flex", + "-webkit-flex-basis", + "-webkit-flex-direction", + "-webkit-flex-flow", + "-webkit-flex-grow", + "-webkit-flex-shrink", + "-webkit-flex-wrap", + "-webkit-justify-content", + "-webkit-line-clamp", + "-webkit-mask", + "-webkit-mask-clip", + "-webkit-mask-composite", + "-webkit-mask-image", + "-webkit-mask-origin", + "-webkit-mask-position", + "-webkit-mask-position-x", + "-webkit-mask-position-y", + "-webkit-mask-repeat", + "-webkit-mask-size", + "-webkit-order", + "-webkit-perspective", + "-webkit-perspective-origin", + "-webkit-text-fill-color", + "-webkit-text-size-adjust", + "-webkit-text-stroke", + "-webkit-text-stroke-color", + "-webkit-text-stroke-width", + "-webkit-transform", + "-webkit-transform-origin", + "-webkit-transform-style", + "-webkit-transition", + "-webkit-transition-delay", + "-webkit-transition-duration", + "-webkit-transition-property", + "-webkit-transition-timing-function", + "-webkit-user-select", + "0", + "1", + "10", + "11", + "12", + "13", + "14", + "15", + "16", + "17", + "18", + "19", + "2", + "20", + "21", + "22", + "23", + "24", + "25", + "26", + "27", + "28", + "29", + "3", + "30", + "31", + "32", + "33", + "34", + "35", + "36", + "37", + "38", + "39", + "4", + "40", + "41", + "42", + "43", + "44", + "45", + "46", + "47", + "48", + "49", + "5", + "50", + "51", + "6", + "7", + "8", + "9", + "@@iterator", + "ABORT_ERR", + "ACTIVE", + "ACTIVE_ATTRIBUTES", + "ACTIVE_TEXTURE", + "ACTIVE_UNIFORMS", + "ACTIVE_UNIFORM_BLOCKS", + "ADDITION", + "ALIASED_LINE_WIDTH_RANGE", + "ALIASED_POINT_SIZE_RANGE", + "ALLOW_KEYBOARD_INPUT", + "ALLPASS", + "ALPHA", + "ALPHA_BITS", + "ALREADY_SIGNALED", + "ALT_MASK", + "ALWAYS", + "ANDROID", + "ANGLE_instanced_arrays", + "ANY_SAMPLES_PASSED", + "ANY_SAMPLES_PASSED_CONSERVATIVE", + "ANY_TYPE", + "ANY_UNORDERED_NODE_TYPE", + "APP_UPDATE", + "ARM", + "ARRAY_BUFFER", + "ARRAY_BUFFER_BINDING", + "ATTACHED_SHADERS", + "ATTRIBUTE_NODE", + "AT_TARGET", + "AbortController", + "AbortSignal", + "AbsoluteOrientationSensor", + "AbstractRange", + "Accelerometer", + "ActiveXObject", + "AddSearchProvider", + "AesGcmEncryptResult", + "AggregateError", + "AnalyserNode", + "Animation", + "AnimationEffect", + "AnimationEvent", + "AnimationPlaybackEvent", + "AnimationTimeline", + "AnonXMLHttpRequest", + "AppBannerPromptResult", + "ApplicationCache", + "ApplicationCacheErrorEvent", + "Array", + "ArrayBuffer", + "Atomics", + "Attr", + "Audio", + "AudioBuffer", + "AudioBufferSourceNode", + "AudioContext", + "AudioDestinationNode", + "AudioListener", + "AudioNode", + "AudioParam", + "AudioParamMap", + "AudioProcessingEvent", + "AudioScheduledSourceNode", + "AudioStreamTrack", + "AudioTrack", + "AudioTrackList", + "AudioWorklet", + "AudioWorkletNode", + "AuthenticatorAssertionResponse", + "AuthenticatorAttestationResponse", + "AuthenticatorResponse", + "AutocompleteErrorEvent", + "BACK", + "BAD_BOUNDARYPOINTS_ERR", + "BAD_REQUEST", + "BANDPASS", + "BLEND", + "BLEND_COLOR", + "BLEND_DST_ALPHA", + "BLEND_DST_RGB", + "BLEND_EQUATION", + "BLEND_EQUATION_ALPHA", + "BLEND_EQUATION_RGB", + "BLEND_SRC_ALPHA", + "BLEND_SRC_RGB", + "BLUE_BITS", + "BLUR", + "BOOL", + "BOOLEAN_TYPE", + "BOOL_VEC2", + "BOOL_VEC3", + "BOOL_VEC4", + "BOTH", + "BROWSER_DEFAULT_WEBGL", + "BUBBLING_PHASE", + "BUFFER_SIZE", + "BUFFER_USAGE", + "BYTE", + "BYTES_PER_ELEMENT", + "BackgroundFetchManager", + "BackgroundFetchRecord", + "BackgroundFetchRegistration", + "BarProp", + "BarcodeDetector", + "BaseAudioContext", + "BaseHref", + "BatteryManager", + "BeforeInstallPromptEvent", + "BeforeLoadEvent", + "BeforeUnloadEvent", + "BigInt", + "BigInt64Array", + "BigUint64Array", + "BiquadFilterNode", + "Blob", + "BlobEvent", + "Bluetooth", + "BluetoothCharacteristicProperties", + "BluetoothDevice", + "BluetoothRemoteGATTCharacteristic", + "BluetoothRemoteGATTDescriptor", + "BluetoothRemoteGATTServer", + "BluetoothRemoteGATTService", + "BluetoothUUID", + "BookmarkCollection", + "Boolean", + "BroadcastChannel", + "ByteLengthQueuingStrategy", + "CANNOT_RUN", + "CAPTURING_PHASE", + "CCW", + "CDATASection", + "CDATA_SECTION_NODE", + "CHANGE", + "CHARSET_RULE", + "CHECKING", + "CHROME_UPDATE", + "CLAMP_TO_EDGE", + "CLICK", + "CLOSED", + "CLOSING", + "COLOR", + "COLOR_ATTACHMENT0", + "COLOR_ATTACHMENT1", + "COLOR_ATTACHMENT10", + "COLOR_ATTACHMENT11", + "COLOR_ATTACHMENT12", + "COLOR_ATTACHMENT13", + "COLOR_ATTACHMENT14", + "COLOR_ATTACHMENT15", + "COLOR_ATTACHMENT2", + "COLOR_ATTACHMENT3", + "COLOR_ATTACHMENT4", + "COLOR_ATTACHMENT5", + "COLOR_ATTACHMENT6", + "COLOR_ATTACHMENT7", + "COLOR_ATTACHMENT8", + "COLOR_ATTACHMENT9", + "COLOR_BUFFER_BIT", + "COLOR_CLEAR_VALUE", + "COLOR_WRITEMASK", + "COMMENT_NODE", + "COMPARE_REF_TO_TEXTURE", + "COMPILE_STATUS", + "COMPRESSED_RGBA_S3TC_DXT1_EXT", + "COMPRESSED_RGBA_S3TC_DXT3_EXT", + "COMPRESSED_RGBA_S3TC_DXT5_EXT", + "COMPRESSED_RGB_S3TC_DXT1_EXT", + "COMPRESSED_TEXTURE_FORMATS", + "CONDITION_SATISFIED", + "CONFIGURATION_UNSUPPORTED", + "CONNECTING", + "CONSTANT_ALPHA", + "CONSTANT_COLOR", + "CONSTRAINT_ERR", + "CONTENT", + "CONTEXT_LOST_WEBGL", + "CONTROL_MASK", + "COPY_READ_BUFFER", + "COPY_READ_BUFFER_BINDING", + "COPY_WRITE_BUFFER", + "COPY_WRITE_BUFFER_BINDING", + "COUNTER_STYLE_RULE", + "CROS", + "CSS", + "CSS2Properties", + "CSSAnimation", + "CSSCharsetRule", + "CSSConditionRule", + "CSSCounterStyleRule", + "CSSFontFaceRule", + "CSSFontFeatureValuesRule", + "CSSGroupingRule", + "CSSImageValue", + "CSSImportRule", + "CSSKeyframeRule", + "CSSKeyframesRule", + "CSSKeywordValue", + "CSSMathInvert", + "CSSMathMax", + "CSSMathMin", + "CSSMathNegate", + "CSSMathProduct", + "CSSMathSum", + "CSSMathValue", + "CSSMatrixComponent", + "CSSMediaRule", + "CSSMozDocumentRule", + "CSSNameSpaceRule", + "CSSNamespaceRule", + "CSSNumericArray", + "CSSNumericValue", + "CSSPageRule", + "CSSPerspective", + "CSSPositionValue", + "CSSPrimitiveValue", + "CSSRotate", + "CSSRule", + "CSSRuleList", + "CSSScale", + "CSSSkew", + "CSSSkewX", + "CSSSkewY", + "CSSStyleDeclaration", + "CSSStyleRule", + "CSSStyleSheet", + "CSSStyleValue", + "CSSSupportsRule", + "CSSTransformComponent", + "CSSTransformValue", + "CSSTransition", + "CSSTranslate", + "CSSUnitValue", + "CSSUnknownRule", + "CSSUnparsedValue", + "CSSValue", + "CSSValueList", + "CSSVariableReferenceValue", + "CSSVariablesDeclaration", + "CSSVariablesRule", + "CSSViewportRule", + "CSS_ATTR", + "CSS_CM", + "CSS_COUNTER", + "CSS_CUSTOM", + "CSS_DEG", + "CSS_DIMENSION", + "CSS_EMS", + "CSS_EXS", + "CSS_FILTER_BLUR", + "CSS_FILTER_BRIGHTNESS", + "CSS_FILTER_CONTRAST", + "CSS_FILTER_CUSTOM", + "CSS_FILTER_DROP_SHADOW", + "CSS_FILTER_GRAYSCALE", + "CSS_FILTER_HUE_ROTATE", + "CSS_FILTER_INVERT", + "CSS_FILTER_OPACITY", + "CSS_FILTER_REFERENCE", + "CSS_FILTER_SATURATE", + "CSS_FILTER_SEPIA", + "CSS_GRAD", + "CSS_HZ", + "CSS_IDENT", + "CSS_IN", + "CSS_INHERIT", + "CSS_KHZ", + "CSS_MATRIX", + "CSS_MATRIX3D", + "CSS_MM", + "CSS_MS", + "CSS_NUMBER", + "CSS_PC", + "CSS_PERCENTAGE", + "CSS_PERSPECTIVE", + "CSS_PRIMITIVE_VALUE", + "CSS_PT", + "CSS_PX", + "CSS_RAD", + "CSS_RECT", + "CSS_RGBCOLOR", + "CSS_ROTATE", + "CSS_ROTATE3D", + "CSS_ROTATEX", + "CSS_ROTATEY", + "CSS_ROTATEZ", + "CSS_S", + "CSS_SCALE", + "CSS_SCALE3D", + "CSS_SCALEX", + "CSS_SCALEY", + "CSS_SCALEZ", + "CSS_SKEW", + "CSS_SKEWX", + "CSS_SKEWY", + "CSS_STRING", + "CSS_TRANSLATE", + "CSS_TRANSLATE3D", + "CSS_TRANSLATEX", + "CSS_TRANSLATEY", + "CSS_TRANSLATEZ", + "CSS_UNKNOWN", + "CSS_URI", + "CSS_VALUE_LIST", + "CSS_VH", + "CSS_VMAX", + "CSS_VMIN", + "CSS_VW", + "CULL_FACE", + "CULL_FACE_MODE", + "CURRENT_PROGRAM", + "CURRENT_QUERY", + "CURRENT_VERTEX_ATTRIB", + "CUSTOM", + "CW", + "Cache", + "CacheStorage", + "CanvasCaptureMediaStream", + "CanvasCaptureMediaStreamTrack", + "CanvasGradient", + "CanvasPattern", + "CanvasPixelArray", + "CanvasRenderingContext2D", + "CaretPosition", + "ChannelMergerNode", + "ChannelSplitterNode", + "CharacterData", + "Chrome PDF Plugin", + "Chrome PDF Viewer", + "ClientRect", + "ClientRectList", + "Clipboard", + "ClipboardEvent", + "ClipboardItem", + "CloseEvent", + "Collator", + "CollectGarbage", + "CommandEvent", + "Comment", + "CompileError", + "CompositionEvent", + "CompressionStream", + "Console", + "ConstantSourceNode", + "ControlRangeCollection", + "Controllers", + "ConvolverNode", + "Coordinates", + "CountQueuingStrategy", + "Counter", + "Credential", + "CredentialsContainer", + "Crypto", + "CryptoKey", + "CryptoOperation", + "CustomElementRegistry", + "CustomEvent", + "DATABASE_ERR", + "DATA_CLONE_ERR", + "DATA_ERR", + "DBLCLICK", + "DECR", + "DECR_WRAP", + "DELETE_STATUS", + "DEPTH", + "DEPTH24_STENCIL8", + "DEPTH32F_STENCIL8", + "DEPTH_ATTACHMENT", + "DEPTH_BITS", + "DEPTH_BUFFER_BIT", + "DEPTH_CLEAR_VALUE", + "DEPTH_COMPONENT", + "DEPTH_COMPONENT16", + "DEPTH_COMPONENT24", + "DEPTH_COMPONENT32F", + "DEPTH_FUNC", + "DEPTH_RANGE", + "DEPTH_STENCIL", + "DEPTH_STENCIL_ATTACHMENT", + "DEPTH_TEST", + "DEPTH_WRITEMASK", + "DEVICE_INELIGIBLE", + "DIRECTION_DOWN", + "DIRECTION_LEFT", + "DIRECTION_RIGHT", + "DIRECTION_UP", + "DISABLED", + "DISPATCH_REQUEST_ERR", + "DITHER", + "DOCUMENT_FRAGMENT_NODE", + "DOCUMENT_NODE", + "DOCUMENT_POSITION_CONTAINED_BY", + "DOCUMENT_POSITION_CONTAINS", + "DOCUMENT_POSITION_DISCONNECTED", + "DOCUMENT_POSITION_FOLLOWING", + "DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC", + "DOCUMENT_POSITION_PRECEDING", + "DOCUMENT_TYPE_NODE", + "DOMCursor", + "DOMError", + "DOMException", + "DOMImplementation", + "DOMImplementationLS", + "DOMMatrix", + "DOMMatrixReadOnly", + "DOMParser", + "DOMPoint", + "DOMPointReadOnly", + "DOMQuad", + "DOMRect", + "DOMRectList", + "DOMRectReadOnly", + "DOMRequest", + "DOMSTRING_SIZE_ERR", + "DOMSettableTokenList", + "DOMStringList", + "DOMStringMap", + "DOMTokenList", + "DOMTransactionEvent", + "DOM_DELTA_LINE", + "DOM_DELTA_PAGE", + "DOM_DELTA_PIXEL", + "DOM_INPUT_METHOD_DROP", + "DOM_INPUT_METHOD_HANDWRITING", + "DOM_INPUT_METHOD_IME", + "DOM_INPUT_METHOD_KEYBOARD", + "DOM_INPUT_METHOD_MULTIMODAL", + "DOM_INPUT_METHOD_OPTION", + "DOM_INPUT_METHOD_PASTE", + "DOM_INPUT_METHOD_SCRIPT", + "DOM_INPUT_METHOD_UNKNOWN", + "DOM_INPUT_METHOD_VOICE", + "DOM_KEY_LOCATION_JOYSTICK", + "DOM_KEY_LOCATION_LEFT", + "DOM_KEY_LOCATION_MOBILE", + "DOM_KEY_LOCATION_NUMPAD", + "DOM_KEY_LOCATION_RIGHT", + "DOM_KEY_LOCATION_STANDARD", + "DOM_VK_0", + "DOM_VK_1", + "DOM_VK_2", + "DOM_VK_3", + "DOM_VK_4", + "DOM_VK_5", + "DOM_VK_6", + "DOM_VK_7", + "DOM_VK_8", + "DOM_VK_9", + "DOM_VK_A", + "DOM_VK_ACCEPT", + "DOM_VK_ADD", + "DOM_VK_ALT", + "DOM_VK_ALTGR", + "DOM_VK_AMPERSAND", + "DOM_VK_ASTERISK", + "DOM_VK_AT", + "DOM_VK_ATTN", + "DOM_VK_B", + "DOM_VK_BACKSPACE", + "DOM_VK_BACK_QUOTE", + "DOM_VK_BACK_SLASH", + "DOM_VK_BACK_SPACE", + "DOM_VK_C", + "DOM_VK_CANCEL", + "DOM_VK_CAPS_LOCK", + "DOM_VK_CIRCUMFLEX", + "DOM_VK_CLEAR", + "DOM_VK_CLOSE_BRACKET", + "DOM_VK_CLOSE_CURLY_BRACKET", + "DOM_VK_CLOSE_PAREN", + "DOM_VK_COLON", + "DOM_VK_COMMA", + "DOM_VK_CONTEXT_MENU", + "DOM_VK_CONTROL", + "DOM_VK_CONVERT", + "DOM_VK_CRSEL", + "DOM_VK_CTRL", + "DOM_VK_D", + "DOM_VK_DECIMAL", + "DOM_VK_DELETE", + "DOM_VK_DIVIDE", + "DOM_VK_DOLLAR", + "DOM_VK_DOUBLE_QUOTE", + "DOM_VK_DOWN", + "DOM_VK_E", + "DOM_VK_EISU", + "DOM_VK_END", + "DOM_VK_ENTER", + "DOM_VK_EQUALS", + "DOM_VK_EREOF", + "DOM_VK_ESCAPE", + "DOM_VK_EXCLAMATION", + "DOM_VK_EXECUTE", + "DOM_VK_EXSEL", + "DOM_VK_F", + "DOM_VK_F1", + "DOM_VK_F10", + "DOM_VK_F11", + "DOM_VK_F12", + "DOM_VK_F13", + "DOM_VK_F14", + "DOM_VK_F15", + "DOM_VK_F16", + "DOM_VK_F17", + "DOM_VK_F18", + "DOM_VK_F19", + "DOM_VK_F2", + "DOM_VK_F20", + "DOM_VK_F21", + "DOM_VK_F22", + "DOM_VK_F23", + "DOM_VK_F24", + "DOM_VK_F25", + "DOM_VK_F26", + "DOM_VK_F27", + "DOM_VK_F28", + "DOM_VK_F29", + "DOM_VK_F3", + "DOM_VK_F30", + "DOM_VK_F31", + "DOM_VK_F32", + "DOM_VK_F33", + "DOM_VK_F34", + "DOM_VK_F35", + "DOM_VK_F36", + "DOM_VK_F4", + "DOM_VK_F5", + "DOM_VK_F6", + "DOM_VK_F7", + "DOM_VK_F8", + "DOM_VK_F9", + "DOM_VK_FINAL", + "DOM_VK_FRONT", + "DOM_VK_G", + "DOM_VK_GREATER_THAN", + "DOM_VK_H", + "DOM_VK_HANGUL", + "DOM_VK_HANJA", + "DOM_VK_HASH", + "DOM_VK_HELP", + "DOM_VK_HK_TOGGLE", + "DOM_VK_HOME", + "DOM_VK_HYPHEN_MINUS", + "DOM_VK_I", + "DOM_VK_INSERT", + "DOM_VK_J", + "DOM_VK_JUNJA", + "DOM_VK_K", + "DOM_VK_KANA", + "DOM_VK_KANJI", + "DOM_VK_L", + "DOM_VK_LEFT", + "DOM_VK_LEFT_TAB", + "DOM_VK_LESS_THAN", + "DOM_VK_M", + "DOM_VK_META", + "DOM_VK_MODECHANGE", + "DOM_VK_MULTIPLY", + "DOM_VK_N", + "DOM_VK_NONCONVERT", + "DOM_VK_NUMPAD0", + "DOM_VK_NUMPAD1", + "DOM_VK_NUMPAD2", + "DOM_VK_NUMPAD3", + "DOM_VK_NUMPAD4", + "DOM_VK_NUMPAD5", + "DOM_VK_NUMPAD6", + "DOM_VK_NUMPAD7", + "DOM_VK_NUMPAD8", + "DOM_VK_NUMPAD9", + "DOM_VK_NUM_LOCK", + "DOM_VK_O", + "DOM_VK_OEM_1", + "DOM_VK_OEM_102", + "DOM_VK_OEM_2", + "DOM_VK_OEM_3", + "DOM_VK_OEM_4", + "DOM_VK_OEM_5", + "DOM_VK_OEM_6", + "DOM_VK_OEM_7", + "DOM_VK_OEM_8", + "DOM_VK_OEM_COMMA", + "DOM_VK_OEM_MINUS", + "DOM_VK_OEM_PERIOD", + "DOM_VK_OEM_PLUS", + "DOM_VK_OPEN_BRACKET", + "DOM_VK_OPEN_CURLY_BRACKET", + "DOM_VK_OPEN_PAREN", + "DOM_VK_P", + "DOM_VK_PA1", + "DOM_VK_PAGEDOWN", + "DOM_VK_PAGEUP", + "DOM_VK_PAGE_DOWN", + "DOM_VK_PAGE_UP", + "DOM_VK_PAUSE", + "DOM_VK_PERCENT", + "DOM_VK_PERIOD", + "DOM_VK_PIPE", + "DOM_VK_PLAY", + "DOM_VK_PLUS", + "DOM_VK_PRINT", + "DOM_VK_PRINTSCREEN", + "DOM_VK_PROCESSKEY", + "DOM_VK_PROPERITES", + "DOM_VK_Q", + "DOM_VK_QUESTION_MARK", + "DOM_VK_QUOTE", + "DOM_VK_R", + "DOM_VK_REDO", + "DOM_VK_RETURN", + "DOM_VK_RIGHT", + "DOM_VK_S", + "DOM_VK_SCROLL_LOCK", + "DOM_VK_SELECT", + "DOM_VK_SEMICOLON", + "DOM_VK_SEPARATOR", + "DOM_VK_SHIFT", + "DOM_VK_SLASH", + "DOM_VK_SLEEP", + "DOM_VK_SPACE", + "DOM_VK_SUBTRACT", + "DOM_VK_T", + "DOM_VK_TAB", + "DOM_VK_TILDE", + "DOM_VK_U", + "DOM_VK_UNDERSCORE", + "DOM_VK_UNDO", + "DOM_VK_UNICODE", + "DOM_VK_UP", + "DOM_VK_V", + "DOM_VK_VOLUME_DOWN", + "DOM_VK_VOLUME_MUTE", + "DOM_VK_VOLUME_UP", + "DOM_VK_W", + "DOM_VK_WIN", + "DOM_VK_WINDOW", + "DOM_VK_WIN_ICO_00", + "DOM_VK_WIN_ICO_CLEAR", + "DOM_VK_WIN_ICO_HELP", + "DOM_VK_WIN_OEM_ATTN", + "DOM_VK_WIN_OEM_AUTO", + "DOM_VK_WIN_OEM_BACKTAB", + "DOM_VK_WIN_OEM_CLEAR", + "DOM_VK_WIN_OEM_COPY", + "DOM_VK_WIN_OEM_CUSEL", + "DOM_VK_WIN_OEM_ENLW", + "DOM_VK_WIN_OEM_FINISH", + "DOM_VK_WIN_OEM_FJ_JISHO", + "DOM_VK_WIN_OEM_FJ_LOYA", + "DOM_VK_WIN_OEM_FJ_MASSHOU", + "DOM_VK_WIN_OEM_FJ_ROYA", + "DOM_VK_WIN_OEM_FJ_TOUROKU", + "DOM_VK_WIN_OEM_JUMP", + "DOM_VK_WIN_OEM_PA1", + "DOM_VK_WIN_OEM_PA2", + "DOM_VK_WIN_OEM_PA3", + "DOM_VK_WIN_OEM_RESET", + "DOM_VK_WIN_OEM_WSCTRL", + "DOM_VK_X", + "DOM_VK_XF86XK_ADD_FAVORITE", + "DOM_VK_XF86XK_APPLICATION_LEFT", + "DOM_VK_XF86XK_APPLICATION_RIGHT", + "DOM_VK_XF86XK_AUDIO_CYCLE_TRACK", + "DOM_VK_XF86XK_AUDIO_FORWARD", + "DOM_VK_XF86XK_AUDIO_LOWER_VOLUME", + "DOM_VK_XF86XK_AUDIO_MEDIA", + "DOM_VK_XF86XK_AUDIO_MUTE", + "DOM_VK_XF86XK_AUDIO_NEXT", + "DOM_VK_XF86XK_AUDIO_PAUSE", + "DOM_VK_XF86XK_AUDIO_PLAY", + "DOM_VK_XF86XK_AUDIO_PREV", + "DOM_VK_XF86XK_AUDIO_RAISE_VOLUME", + "DOM_VK_XF86XK_AUDIO_RANDOM_PLAY", + "DOM_VK_XF86XK_AUDIO_RECORD", + "DOM_VK_XF86XK_AUDIO_REPEAT", + "DOM_VK_XF86XK_AUDIO_REWIND", + "DOM_VK_XF86XK_AUDIO_STOP", + "DOM_VK_XF86XK_AWAY", + "DOM_VK_XF86XK_BACK", + "DOM_VK_XF86XK_BACK_FORWARD", + "DOM_VK_XF86XK_BATTERY", + "DOM_VK_XF86XK_BLUE", + "DOM_VK_XF86XK_BLUETOOTH", + "DOM_VK_XF86XK_BOOK", + "DOM_VK_XF86XK_BRIGHTNESS_ADJUST", + "DOM_VK_XF86XK_CALCULATOR", + "DOM_VK_XF86XK_CALENDAR", + "DOM_VK_XF86XK_CD", + "DOM_VK_XF86XK_CLOSE", + "DOM_VK_XF86XK_COMMUNITY", + "DOM_VK_XF86XK_CONTRAST_ADJUST", + "DOM_VK_XF86XK_COPY", + "DOM_VK_XF86XK_CUT", + "DOM_VK_XF86XK_CYCLE_ANGLE", + "DOM_VK_XF86XK_DISPLAY", + "DOM_VK_XF86XK_DOCUMENTS", + "DOM_VK_XF86XK_DOS", + "DOM_VK_XF86XK_EJECT", + "DOM_VK_XF86XK_EXCEL", + "DOM_VK_XF86XK_EXPLORER", + "DOM_VK_XF86XK_FAVORITES", + "DOM_VK_XF86XK_FINANCE", + "DOM_VK_XF86XK_FORWARD", + "DOM_VK_XF86XK_FRAME_BACK", + "DOM_VK_XF86XK_FRAME_FORWARD", + "DOM_VK_XF86XK_GAME", + "DOM_VK_XF86XK_GO", + "DOM_VK_XF86XK_GREEN", + "DOM_VK_XF86XK_HIBERNATE", + "DOM_VK_XF86XK_HISTORY", + "DOM_VK_XF86XK_HOME_PAGE", + "DOM_VK_XF86XK_HOT_LINKS", + "DOM_VK_XF86XK_I_TOUCH", + "DOM_VK_XF86XK_KBD_BRIGHTNESS_DOWN", + "DOM_VK_XF86XK_KBD_BRIGHTNESS_UP", + "DOM_VK_XF86XK_KBD_LIGHT_ON_OFF", + "DOM_VK_XF86XK_LAUNCH0", + "DOM_VK_XF86XK_LAUNCH1", + "DOM_VK_XF86XK_LAUNCH2", + "DOM_VK_XF86XK_LAUNCH3", + "DOM_VK_XF86XK_LAUNCH4", + "DOM_VK_XF86XK_LAUNCH5", + "DOM_VK_XF86XK_LAUNCH6", + "DOM_VK_XF86XK_LAUNCH7", + "DOM_VK_XF86XK_LAUNCH8", + "DOM_VK_XF86XK_LAUNCH9", + "DOM_VK_XF86XK_LAUNCH_A", + "DOM_VK_XF86XK_LAUNCH_B", + "DOM_VK_XF86XK_LAUNCH_C", + "DOM_VK_XF86XK_LAUNCH_D", + "DOM_VK_XF86XK_LAUNCH_E", + "DOM_VK_XF86XK_LAUNCH_F", + "DOM_VK_XF86XK_LIGHT_BULB", + "DOM_VK_XF86XK_LOG_OFF", + "DOM_VK_XF86XK_MAIL", + "DOM_VK_XF86XK_MAIL_FORWARD", + "DOM_VK_XF86XK_MARKET", + "DOM_VK_XF86XK_MEETING", + "DOM_VK_XF86XK_MEMO", + "DOM_VK_XF86XK_MENU_KB", + "DOM_VK_XF86XK_MENU_PB", + "DOM_VK_XF86XK_MESSENGER", + "DOM_VK_XF86XK_MON_BRIGHTNESS_DOWN", + "DOM_VK_XF86XK_MON_BRIGHTNESS_UP", + "DOM_VK_XF86XK_MUSIC", + "DOM_VK_XF86XK_MY_COMPUTER", + "DOM_VK_XF86XK_MY_SITES", + "DOM_VK_XF86XK_NEW", + "DOM_VK_XF86XK_NEWS", + "DOM_VK_XF86XK_OFFICE_HOME", + "DOM_VK_XF86XK_OPEN", + "DOM_VK_XF86XK_OPEN_URL", + "DOM_VK_XF86XK_OPTION", + "DOM_VK_XF86XK_PASTE", + "DOM_VK_XF86XK_PHONE", + "DOM_VK_XF86XK_PICTURES", + "DOM_VK_XF86XK_POWER_DOWN", + "DOM_VK_XF86XK_POWER_OFF", + "DOM_VK_XF86XK_RED", + "DOM_VK_XF86XK_REFRESH", + "DOM_VK_XF86XK_RELOAD", + "DOM_VK_XF86XK_REPLY", + "DOM_VK_XF86XK_ROCKER_DOWN", + "DOM_VK_XF86XK_ROCKER_ENTER", + "DOM_VK_XF86XK_ROCKER_UP", + "DOM_VK_XF86XK_ROTATE_WINDOWS", + "DOM_VK_XF86XK_ROTATION_KB", + "DOM_VK_XF86XK_ROTATION_PB", + "DOM_VK_XF86XK_SAVE", + "DOM_VK_XF86XK_SCREEN_SAVER", + "DOM_VK_XF86XK_SCROLL_CLICK", + "DOM_VK_XF86XK_SCROLL_DOWN", + "DOM_VK_XF86XK_SCROLL_UP", + "DOM_VK_XF86XK_SEARCH", + "DOM_VK_XF86XK_SEND", + "DOM_VK_XF86XK_SHOP", + "DOM_VK_XF86XK_SPELL", + "DOM_VK_XF86XK_SPLIT_SCREEN", + "DOM_VK_XF86XK_STANDBY", + "DOM_VK_XF86XK_START", + "DOM_VK_XF86XK_STOP", + "DOM_VK_XF86XK_SUBTITLE", + "DOM_VK_XF86XK_SUPPORT", + "DOM_VK_XF86XK_SUSPEND", + "DOM_VK_XF86XK_TASK_PANE", + "DOM_VK_XF86XK_TERMINAL", + "DOM_VK_XF86XK_TIME", + "DOM_VK_XF86XK_TOOLS", + "DOM_VK_XF86XK_TOP_MENU", + "DOM_VK_XF86XK_TO_DO_LIST", + "DOM_VK_XF86XK_TRAVEL", + "DOM_VK_XF86XK_USER1KB", + "DOM_VK_XF86XK_USER2KB", + "DOM_VK_XF86XK_USER_PB", + "DOM_VK_XF86XK_UWB", + "DOM_VK_XF86XK_VENDOR_HOME", + "DOM_VK_XF86XK_VIDEO", + "DOM_VK_XF86XK_VIEW", + "DOM_VK_XF86XK_WAKE_UP", + "DOM_VK_XF86XK_WEB_CAM", + "DOM_VK_XF86XK_WHEEL_BUTTON", + "DOM_VK_XF86XK_WLAN", + "DOM_VK_XF86XK_WORD", + "DOM_VK_XF86XK_WWW", + "DOM_VK_XF86XK_XFER", + "DOM_VK_XF86XK_YELLOW", + "DOM_VK_XF86XK_ZOOM_IN", + "DOM_VK_XF86XK_ZOOM_OUT", + "DOM_VK_Y", + "DOM_VK_Z", + "DOM_VK_ZOOM", + "DONE", + "DONT_CARE", + "DOWNLOADING", + "DRAGDROP", + "DRAW_BUFFER0", + "DRAW_BUFFER1", + "DRAW_BUFFER10", + "DRAW_BUFFER11", + "DRAW_BUFFER12", + "DRAW_BUFFER13", + "DRAW_BUFFER14", + "DRAW_BUFFER15", + "DRAW_BUFFER2", + "DRAW_BUFFER3", + "DRAW_BUFFER4", + "DRAW_BUFFER5", + "DRAW_BUFFER6", + "DRAW_BUFFER7", + "DRAW_BUFFER8", + "DRAW_BUFFER9", + "DRAW_FRAMEBUFFER", + "DRAW_FRAMEBUFFER_BINDING", + "DST_ALPHA", + "DST_COLOR", + "DYNAMIC_COPY", + "DYNAMIC_DRAW", + "DYNAMIC_READ", + "DataChannel", + "DataCue", + "DataTransfer", + "DataTransferItem", + "DataTransferItemList", + "DataView", + "Database", + "Date", + "DateTimeFormat", + "Debug", + "DecompressionStream", + "Default Browser Helper", + "DelayNode", + "DesktopNotification", + "DesktopNotificationCenter", + "DeviceAcceleration", + "DeviceLightEvent", + "DeviceMotionEvent", + "DeviceMotionEventAcceleration", + "DeviceMotionEventRotationRate", + "DeviceOrientationEvent", + "DeviceProximityEvent", + "DeviceRotationRate", + "DeviceStorage", + "DeviceStorageChangeEvent", + "Directory", + "DisplayNames", + "Document", + "DocumentFragment", + "DocumentTimeline", + "DocumentType", + "DragEvent", + "DynamicsCompressorNode", + "E", + "ELEMENT_ARRAY_BUFFER", + "ELEMENT_ARRAY_BUFFER_BINDING", + "ELEMENT_NODE", + "EMPTY", + "ENCODING_ERR", + "ENDED", + "END_TO_END", + "END_TO_START", + "ENTITY_NODE", + "ENTITY_REFERENCE_NODE", + "EPSILON", + "EQUAL", + "EQUALPOWER", + "ERROR", + "EXPONENTIAL_DISTANCE", + "EXT_texture_filter_anisotropic", + "Element", + "ElementInternals", + "ElementQuery", + "EnterPictureInPictureEvent", + "Entity", + "EntityReference", + "Enumerator", + "Error", + "ErrorEvent", + "EvalError", + "Event", + "EventException", + "EventSource", + "EventTarget", + "External", + "FASTEST", + "FIDOSDK", + "FILTER_ACCEPT", + "FILTER_INTERRUPT", + "FILTER_REJECT", + "FILTER_SKIP", + "FINISHED_STATE", + "FIRST_ORDERED_NODE_TYPE", + "FLOAT", + "FLOAT_32_UNSIGNED_INT_24_8_REV", + "FLOAT_MAT2", + "FLOAT_MAT2x3", + "FLOAT_MAT2x4", + "FLOAT_MAT3", + "FLOAT_MAT3x2", + "FLOAT_MAT3x4", + "FLOAT_MAT4", + "FLOAT_MAT4x2", + "FLOAT_MAT4x3", + "FLOAT_VEC2", + "FLOAT_VEC3", + "FLOAT_VEC4", + "FOCUS", + "FONT_FACE_RULE", + "FONT_FEATURE_VALUES_RULE", + "FRAGMENT_SHADER", + "FRAGMENT_SHADER_DERIVATIVE_HINT", + "FRAGMENT_SHADER_DERIVATIVE_HINT_OES", + "FRAMEBUFFER", + "FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE", + "FRAMEBUFFER_ATTACHMENT_BLUE_SIZE", + "FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING", + "FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE", + "FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE", + "FRAMEBUFFER_ATTACHMENT_GREEN_SIZE", + "FRAMEBUFFER_ATTACHMENT_OBJECT_NAME", + "FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE", + "FRAMEBUFFER_ATTACHMENT_RED_SIZE", + "FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL", + "FRAMEBUFFER_BINDING", + "FRAMEBUFFER_COMPLETE", + "FRAMEBUFFER_DEFAULT", + "FRAMEBUFFER_INCOMPLETE_ATTACHMENT", + "FRAMEBUFFER_INCOMPLETE_DIMENSIONS", + "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT", + "FRAMEBUFFER_INCOMPLETE_MULTISAMPLE", + "FRAMEBUFFER_UNSUPPORTED", + "FRONT", + "FRONT_AND_BACK", + "FRONT_FACE", + "FUNC_ADD", + "FUNC_REVERSE_SUBTRACT", + "FUNC_SUBTRACT", + "FeaturePolicy", + "FederatedCredential", + "Feed", + "FeedEntry", + "File", + "FileError", + "FileList", + "FileReader", + "FileSystem", + "FileSystemDirectoryEntry", + "FileSystemDirectoryReader", + "FileSystemEntry", + "FileSystemFileEntry", + "FinalizationRegistry", + "FindInPage", + "Float32Array", + "Float64Array", + "FocusEvent", + "FontFace", + "FontFaceSet", + "FontFaceSetLoadEvent", + "FormData", + "FormDataEvent", + "FragmentDirective", + "Function", + "GENERATE_MIPMAP_HINT", + "GEQUAL", + "GREATER", + "GREEN_BITS", + "GainNode", + "Gamepad", + "GamepadButton", + "GamepadEvent", + "GamepadHapticActuator", + "GamepadPose", + "Geolocation", + "GeolocationCoordinates", + "GeolocationPosition", + "GeolocationPositionError", + "GestureEvent", + "Global", + "Gyroscope", + "HALF_FLOAT", + "HAVE_CURRENT_DATA", + "HAVE_ENOUGH_DATA", + "HAVE_FUTURE_DATA", + "HAVE_METADATA", + "HAVE_NOTHING", + "HEADERS_RECEIVED", + "HIDDEN", + "HIERARCHY_REQUEST_ERR", + "HIGHPASS", + "HIGHSHELF", + "HIGH_FLOAT", + "HIGH_INT", + "HORIZONTAL", + "HORIZONTAL_AXIS", + "HRTF", + "HTMLAllCollection", + "HTMLAnchorElement", + "HTMLAppletElement", + "HTMLAreaElement", + "HTMLAreasCollection", + "HTMLAudioElement", + "HTMLBGSoundElement", + "HTMLBRElement", + "HTMLBaseElement", + "HTMLBaseFontElement", + "HTMLBlockElement", + "HTMLBlockquoteElement", + "HTMLBodyElement", + "HTMLButtonElement", + "HTMLCanvasElement", + "HTMLCollection", + "HTMLCommandElement", + "HTMLContentElement", + "HTMLDDElement", + "HTMLDListElement", + "HTMLDTElement", + "HTMLDataElement", + "HTMLDataListElement", + "HTMLDetailsElement", + "HTMLDialogElement", + "HTMLDirectoryElement", + "HTMLDivElement", + "HTMLDocument", + "HTMLElement", + "HTMLEmbedElement", + "HTMLFieldSetElement", + "HTMLFontElement", + "HTMLFormControlsCollection", + "HTMLFormElement", + "HTMLFrameElement", + "HTMLFrameSetElement", + "HTMLHRElement", + "HTMLHeadElement", + "HTMLHeadingElement", + "HTMLHtmlElement", + "HTMLIFrameElement", + "HTMLImageElement", + "HTMLInputElement", + "HTMLIsIndexElement", + "HTMLKeygenElement", + "HTMLLIElement", + "HTMLLabelElement", + "HTMLLegendElement", + "HTMLLinkElement", + "HTMLMapElement", + "HTMLMarqueeElement", + "HTMLMediaElement", + "HTMLMenuElement", + "HTMLMenuItemElement", + "HTMLMetaElement", + "HTMLMeterElement", + "HTMLModElement", + "HTMLNextIdElement", + "HTMLOListElement", + "HTMLObjectElement", + "HTMLOptGroupElement", + "HTMLOptionElement", + "HTMLOptionsCollection", + "HTMLOutputElement", + "HTMLParagraphElement", + "HTMLParamElement", + "HTMLPhraseElement", + "HTMLPictureElement", + "HTMLPreElement", + "HTMLProgressElement", + "HTMLPropertiesCollection", + "HTMLQuoteElement", + "HTMLScriptElement", + "HTMLSelectElement", + "HTMLShadowElement", + "HTMLSlotElement", + "HTMLSourceElement", + "HTMLSpanElement", + "HTMLStyleElement", + "HTMLTableCaptionElement", + "HTMLTableCellElement", + "HTMLTableColElement", + "HTMLTableDataCellElement", + "HTMLTableElement", + "HTMLTableHeaderCellElement", + "HTMLTableRowElement", + "HTMLTableSectionElement", + "HTMLTemplateElement", + "HTMLTextAreaElement", + "HTMLTimeElement", + "HTMLTitleElement", + "HTMLTrackElement", + "HTMLUListElement", + "HTMLUnknownElement", + "HTMLVideoElement", + "HashChangeEvent", + "Headers", + "History", + "Hz", + "ICE_CHECKING", + "ICE_CLOSED", + "ICE_COMPLETED", + "ICE_CONNECTED", + "ICE_FAILED", + "ICE_GATHERING", + "ICE_WAITING", + "IDBCursor", + "IDBCursorWithValue", + "IDBDatabase", + "IDBDatabaseException", + "IDBFactory", + "IDBFileHandle", + "IDBFileRequest", + "IDBIndex", + "IDBKeyRange", + "IDBMutableFile", + "IDBObjectStore", + "IDBOpenDBRequest", + "IDBRequest", + "IDBTransaction", + "IDBVersionChangeEvent", + "IDLE", + "IIRFilterNode", + "IMPLEMENTATION_COLOR_READ_FORMAT", + "IMPLEMENTATION_COLOR_READ_TYPE", + "IMPORT_RULE", + "INCR", + "INCR_WRAP", + "INDEX_SIZE_ERR", + "INSTALL", + "INSTALLED", + "INT", + "INTERLEAVED_ATTRIBS", + "INT_2_10_10_10_REV", + "INT_SAMPLER_2D", + "INT_SAMPLER_2D_ARRAY", + "INT_SAMPLER_3D", + "INT_SAMPLER_CUBE", + "INT_VEC2", + "INT_VEC3", + "INT_VEC4", + "INUSE_ATTRIBUTE_ERR", + "INVALID_ACCESS_ERR", + "INVALID_CHARACTER_ERR", + "INVALID_ENUM", + "INVALID_EXPRESSION_ERR", + "INVALID_FRAMEBUFFER_OPERATION", + "INVALID_INDEX", + "INVALID_MODIFICATION_ERR", + "INVALID_NODE_TYPE_ERR", + "INVALID_OPERATION", + "INVALID_STATE_ERR", + "INVALID_VALUE", + "INVERSE_DISTANCE", + "INVERT", + "IceCandidate", + "IdleDeadline", + "Image", + "ImageBitmap", + "ImageBitmapRenderingContext", + "ImageCapture", + "ImageData", + "Infinity", + "InputDeviceCapabilities", + "InputDeviceInfo", + "InputEvent", + "InputMethodContext", + "InstallState", + "InstallTrigger", + "Instance", + "Int16Array", + "Int32Array", + "Int8Array", + "Intent", + "InternalError", + "IntersectionObserver", + "IntersectionObserverEntry", + "Intl", + "IsSearchProviderInstalled", + "Iterator", + "JSON", + "Java Deployment Toolkit 7.0.250.17", + "Java(TM) Platform SE 7 U25", + "KEEP", + "KEYDOWN", + "KEYFRAMES_RULE", + "KEYFRAME_RULE", + "KEYPRESS", + "KEYUP", + "Key", + "KeyEvent", + "KeyOperation", + "KeyPair", + "Keyboard", + "KeyboardEvent", + "KeyboardLayoutMap", + "KeyframeEffect", + "LENGTHADJUST_SPACING", + "LENGTHADJUST_SPACINGANDGLYPHS", + "LENGTHADJUST_UNKNOWN", + "LEQUAL", + "LESS", + "LINEAR", + "LINEAR_DISTANCE", + "LINEAR_MIPMAP_LINEAR", + "LINEAR_MIPMAP_NEAREST", + "LINES", + "LINE_LOOP", + "LINE_STRIP", + "LINE_WIDTH", + "LINK_STATUS", + "LINUX", + "LIVE", + "LN10", + "LN2", + "LOADED", + "LOADING", + "LOCALE", + "LOG10E", + "LOG2E", + "LOWPASS", + "LOWSHELF", + "LOW_FLOAT", + "LOW_INT", + "LSException", + "LSParserFilter", + "LUMINANCE", + "LUMINANCE_ALPHA", + "LargestContentfulPaint", + "LayoutShift", + "LayoutShiftAttribution", + "LinearAccelerationSensor", + "LinkError", + "ListFormat", + "LocalMediaStream", + "Locale", + "Location", + "Lock", + "LockManager", + "MAC", + "MAX", + "MAX_3D_TEXTURE_SIZE", + "MAX_ARRAY_TEXTURE_LAYERS", + "MAX_CLIENT_WAIT_TIMEOUT_WEBGL", + "MAX_COLOR_ATTACHMENTS", + "MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS", + "MAX_COMBINED_TEXTURE_IMAGE_UNITS", + "MAX_COMBINED_UNIFORM_BLOCKS", + "MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS", + "MAX_CUBE_MAP_TEXTURE_SIZE", + "MAX_DRAW_BUFFERS", + "MAX_ELEMENTS_INDICES", + "MAX_ELEMENTS_VERTICES", + "MAX_ELEMENT_INDEX", + "MAX_FRAGMENT_INPUT_COMPONENTS", + "MAX_FRAGMENT_UNIFORM_BLOCKS", + "MAX_FRAGMENT_UNIFORM_COMPONENTS", + "MAX_FRAGMENT_UNIFORM_VECTORS", + "MAX_PROGRAM_TEXEL_OFFSET", + "MAX_RENDERBUFFER_SIZE", + "MAX_SAFE_INTEGER", + "MAX_SAMPLES", + "MAX_SERVER_WAIT_TIMEOUT", + "MAX_TEXTURE_IMAGE_UNITS", + "MAX_TEXTURE_LOD_BIAS", + "MAX_TEXTURE_MAX_ANISOTROPY_EXT", + "MAX_TEXTURE_SIZE", + "MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS", + "MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS", + "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS", + "MAX_UNIFORM_BLOCK_SIZE", + "MAX_UNIFORM_BUFFER_BINDINGS", + "MAX_VALUE", + "MAX_VARYING_COMPONENTS", + "MAX_VARYING_VECTORS", + "MAX_VERTEX_ATTRIBS", + "MAX_VERTEX_OUTPUT_COMPONENTS", + "MAX_VERTEX_TEXTURE_IMAGE_UNITS", + "MAX_VERTEX_UNIFORM_BLOCKS", + "MAX_VERTEX_UNIFORM_COMPONENTS", + "MAX_VERTEX_UNIFORM_VECTORS", + "MAX_VIEWPORT_DIMS", + "MEDIA_ERR_ABORTED", + "MEDIA_ERR_DECODE", + "MEDIA_ERR_ENCRYPTED", + "MEDIA_ERR_NETWORK", + "MEDIA_ERR_SRC_NOT_SUPPORTED", + "MEDIA_KEYERR_CLIENT", + "MEDIA_KEYERR_DOMAIN", + "MEDIA_KEYERR_HARDWARECHANGE", + "MEDIA_KEYERR_OUTPUT", + "MEDIA_KEYERR_SERVICE", + "MEDIA_KEYERR_UNKNOWN", + "MEDIA_RULE", + "MEDIUM_FLOAT", + "MEDIUM_INT", + "META_MASK", + "MIDIAccess", + "MIDIConnectionEvent", + "MIDIInput", + "MIDIInputMap", + "MIDIMessageEvent", + "MIDIOutput", + "MIDIOutputMap", + "MIDIPort", + "MIN", + "MIN_PROGRAM_TEXEL_OFFSET", + "MIN_SAFE_INTEGER", + "MIN_VALUE", + "MIRRORED_REPEAT", + "MODE_ASYNCHRONOUS", + "MODE_SYNCHRONOUS", + "MODIFICATION", + "MOUSEDOWN", + "MOUSEDRAG", + "MOUSEMOVE", + "MOUSEOUT", + "MOUSEOVER", + "MOUSEUP", + "MOZ_KEYFRAMES_RULE", + "MOZ_KEYFRAME_RULE", + "MOZ_SOURCE_CURSOR", + "MOZ_SOURCE_ERASER", + "MOZ_SOURCE_KEYBOARD", + "MOZ_SOURCE_MOUSE", + "MOZ_SOURCE_PEN", + "MOZ_SOURCE_TOUCH", + "MOZ_SOURCE_UNKNOWN", + "MSBehaviorUrnsCollection", + "MSBlobBuilder", + "MSCSSMatrix", + "MSCSSProperties", + "MSCSSRuleList", + "MSCompatibleInfo", + "MSCompatibleInfoCollection", + "MSCurrentStyleCSSProperties", + "MSEventObj", + "MSGESTURE_FLAG_BEGIN", + "MSGESTURE_FLAG_CANCEL", + "MSGESTURE_FLAG_END", + "MSGESTURE_FLAG_INERTIA", + "MSGESTURE_FLAG_NONE", + "MSGesture", + "MSGestureEvent", + "MSGraphicsTrust", + "MSInputMethodContext", + "MSManipulationEvent", + "MSMediaKeyError", + "MSMediaKeyMessageEvent", + "MSMediaKeyNeededEvent", + "MSMediaKeySession", + "MSMediaKeys", + "MSMimeTypesCollection", + "MSPOINTER_TYPE_MOUSE", + "MSPOINTER_TYPE_PEN", + "MSPOINTER_TYPE_TOUCH", + "MSPluginsCollection", + "MSPointerEvent", + "MSRangeCollection", + "MSSiteModeEvent", + "MSStream", + "MSStreamReader", + "MSStyleCSSProperties", + "MS_ASYNC_CALLBACK_STATUS_ASSIGN_DELEGATE", + "MS_ASYNC_CALLBACK_STATUS_CANCEL", + "MS_ASYNC_CALLBACK_STATUS_CHOOSEANY", + "MS_ASYNC_CALLBACK_STATUS_ERROR", + "MS_ASYNC_CALLBACK_STATUS_JOIN", + "MS_ASYNC_OP_STATUS_CANCELED", + "MS_ASYNC_OP_STATUS_ERROR", + "MS_ASYNC_OP_STATUS_SUCCESS", + "MS_MANIPULATION_STATE_ACTIVE", + "MS_MANIPULATION_STATE_CANCELLED", + "MS_MANIPULATION_STATE_COMMITTED", + "MS_MANIPULATION_STATE_DRAGGING", + "MS_MANIPULATION_STATE_INERTIA", + "MS_MANIPULATION_STATE_PRESELECT", + "MS_MANIPULATION_STATE_SELECTING", + "MS_MANIPULATION_STATE_STOPPED", + "MS_MEDIA_ERR_ENCRYPTED", + "MS_MEDIA_KEYERR_CLIENT", + "MS_MEDIA_KEYERR_DOMAIN", + "MS_MEDIA_KEYERR_HARDWARECHANGE", + "MS_MEDIA_KEYERR_OUTPUT", + "MS_MEDIA_KEYERR_SERVICE", + "MS_MEDIA_KEYERR_UNKNOWN", + "Map", + "Math", + "MathMLElement", + "MediaCapabilities", + "MediaCapabilitiesInfo", + "MediaController", + "MediaDeviceInfo", + "MediaDevices", + "MediaElementAudioSourceNode", + "MediaEncryptedEvent", + "MediaError", + "MediaKeyError", + "MediaKeyEvent", + "MediaKeyMessageEvent", + "MediaKeyNeededEvent", + "MediaKeySession", + "MediaKeyStatusMap", + "MediaKeySystemAccess", + "MediaKeys", + "MediaList", + "MediaMetadata", + "MediaQueryList", + "MediaQueryListEvent", + "MediaRecorder", + "MediaRecorderErrorEvent", + "MediaSession", + "MediaSettingsRange", + "MediaSource", + "MediaStream", + "MediaStreamAudioDestinationNode", + "MediaStreamAudioSourceNode", + "MediaStreamEvent", + "MediaStreamTrack", + "MediaStreamTrackAudioSourceNode", + "MediaStreamTrackEvent", + "Memory", + "MessageChannel", + "MessageEvent", + "MessagePort", + "Methods", + "Microsoft® DRM", + "MimeType", + "MimeTypeArray", + "Module", + "MouseEvent", + "MouseScrollEvent", + "MouseWheelEvent", + "MozAnimation", + "MozAnimationDelay", + "MozAnimationDirection", + "MozAnimationDuration", + "MozAnimationFillMode", + "MozAnimationIterationCount", + "MozAnimationName", + "MozAnimationPlayState", + "MozAnimationTimingFunction", + "MozAppearance", + "MozBackfaceVisibility", + "MozBinding", + "MozBorderBottomColors", + "MozBorderEnd", + "MozBorderEndColor", + "MozBorderEndStyle", + "MozBorderEndWidth", + "MozBorderImage", + "MozBorderLeftColors", + "MozBorderRightColors", + "MozBorderStart", + "MozBorderStartColor", + "MozBorderStartStyle", + "MozBorderStartWidth", + "MozBorderTopColors", + "MozBoxAlign", + "MozBoxDirection", + "MozBoxFlex", + "MozBoxOrdinalGroup", + "MozBoxOrient", + "MozBoxPack", + "MozBoxSizing", + "MozCSSKeyframeRule", + "MozCSSKeyframesRule", + "MozColumnCount", + "MozColumnFill", + "MozColumnGap", + "MozColumnRule", + "MozColumnRuleColor", + "MozColumnRuleStyle", + "MozColumnRuleWidth", + "MozColumnWidth", + "MozColumns", + "MozContactChangeEvent", + "MozFloatEdge", + "MozFontFeatureSettings", + "MozFontLanguageOverride", + "MozForceBrokenImageIcon", + "MozHyphens", + "MozImageRegion", + "MozMarginEnd", + "MozMarginStart", + "MozMmsEvent", + "MozMmsMessage", + "MozMobileMessageThread", + "MozOSXFontSmoothing", + "MozOrient", + "MozOutlineRadius", + "MozOutlineRadiusBottomleft", + "MozOutlineRadiusBottomright", + "MozOutlineRadiusTopleft", + "MozOutlineRadiusTopright", + "MozPaddingEnd", + "MozPaddingStart", + "MozPerspective", + "MozPerspectiveOrigin", + "MozPowerManager", + "MozSettingsEvent", + "MozSmsEvent", + "MozSmsMessage", + "MozStackSizing", + "MozTabSize", + "MozTextAlignLast", + "MozTextDecorationColor", + "MozTextDecorationLine", + "MozTextDecorationStyle", + "MozTextSizeAdjust", + "MozTransform", + "MozTransformOrigin", + "MozTransformStyle", + "MozTransition", + "MozTransitionDelay", + "MozTransitionDuration", + "MozTransitionProperty", + "MozTransitionTimingFunction", + "MozUserFocus", + "MozUserInput", + "MozUserModify", + "MozUserSelect", + "MozWindowDragging", + "MozWindowShadow", + "MutationEvent", + "MutationObserver", + "MutationRecord", + "NAMESPACE_ERR", + "NAMESPACE_RULE", + "NEAREST", + "NEAREST_MIPMAP_LINEAR", + "NEAREST_MIPMAP_NEAREST", + "NEGATIVE_INFINITY", + "NETWORK_EMPTY", + "NETWORK_ERR", + "NETWORK_IDLE", + "NETWORK_LOADED", + "NETWORK_LOADING", + "NETWORK_NO_SOURCE", + "NEVER", + "NEW", + "NEXT", + "NEXT_NO_DUPLICATE", + "NICEST", + "NODE_AFTER", + "NODE_BEFORE", + "NODE_BEFORE_AND_AFTER", + "NODE_INSIDE", + "NONE", + "NON_TRANSIENT_ERR", + "NOTATION_NODE", + "NOTCH", + "NOTEQUAL", + "NOT_ALLOWED_ERR", + "NOT_FOUND_ERR", + "NOT_INSTALLED", + "NOT_READABLE_ERR", + "NOT_SUPPORTED_ERR", + "NO_DATA_ALLOWED_ERR", + "NO_ERR", + "NO_ERROR", + "NO_MODIFICATION_ALLOWED_ERR", + "NO_UPDATE", + "NUMBER_TYPE", + "NUM_COMPRESSED_TEXTURE_FORMATS", + "NaN", + "NamedNodeMap", + "Native Client", + "NavigationPreloadManager", + "Navigator", + "NearbyLinks", + "NetworkInformation", + "Node", + "NodeFilter", + "NodeIterator", + "NodeList", + "Notation", + "Notification", + "NotifyPaintEvent", + "Number", + "NumberFormat", + "OBJECT_TYPE", + "OBSOLETE", + "OES_element_index_uint", + "OES_standard_derivatives", + "OES_texture_float", + "OES_texture_float_linear", + "OK", + "ONE", + "ONE_MINUS_CONSTANT_ALPHA", + "ONE_MINUS_CONSTANT_COLOR", + "ONE_MINUS_DST_ALPHA", + "ONE_MINUS_DST_COLOR", + "ONE_MINUS_SRC_ALPHA", + "ONE_MINUS_SRC_COLOR", + "OPEN", + "OPENBSD", + "OPENED", + "OPENING", + "ORDERED_NODE_ITERATOR_TYPE", + "ORDERED_NODE_SNAPSHOT_TYPE", + "OS_UPDATE", + "OTHER_ERROR", + "OUT_OF_MEMORY", + "Object", + "OfflineAudioCompletionEvent", + "OfflineAudioContext", + "OfflineResourceList", + "OffscreenCanvas", + "OffscreenCanvasRenderingContext2D", + "OnInstalledReason", + "OnRestartRequiredReason", + "Option", + "OrientationSensor", + "OscillatorNode", + "OverconstrainedError", + "OverconstrainedErrorEvent", + "OverflowEvent", + "PACKAGE", + "PACK_ALIGNMENT", + "PACK_ROW_LENGTH", + "PACK_SKIP_PIXELS", + "PACK_SKIP_ROWS", + "PAGE_RULE", + "PARSE_ERR", + "PATHSEG_ARC_ABS", + "PATHSEG_ARC_REL", + "PATHSEG_CLOSEPATH", + "PATHSEG_CURVETO_CUBIC_ABS", + "PATHSEG_CURVETO_CUBIC_REL", + "PATHSEG_CURVETO_CUBIC_SMOOTH_ABS", + "PATHSEG_CURVETO_CUBIC_SMOOTH_REL", + "PATHSEG_CURVETO_QUADRATIC_ABS", + "PATHSEG_CURVETO_QUADRATIC_REL", + "PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS", + "PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL", + "PATHSEG_LINETO_ABS", + "PATHSEG_LINETO_HORIZONTAL_ABS", + "PATHSEG_LINETO_HORIZONTAL_REL", + "PATHSEG_LINETO_REL", + "PATHSEG_LINETO_VERTICAL_ABS", + "PATHSEG_LINETO_VERTICAL_REL", + "PATHSEG_MOVETO_ABS", + "PATHSEG_MOVETO_REL", + "PATHSEG_UNKNOWN", + "PATH_EXISTS_ERR", + "PEAKING", + "PERIODIC", + "PERMISSION_DENIED", + "PERSISTENT", + "PI", + "PIXEL_PACK_BUFFER", + "PIXEL_PACK_BUFFER_BINDING", + "PIXEL_UNPACK_BUFFER", + "PIXEL_UNPACK_BUFFER_BINDING", + "PLAYING_STATE", + "POINTS", + "POLYGON_OFFSET_FACTOR", + "POLYGON_OFFSET_FILL", + "POLYGON_OFFSET_UNITS", + "POSITION_UNAVAILABLE", + "POSITIVE_INFINITY", + "PREV", + "PREV_NO_DUPLICATE", + "PROCESSING_INSTRUCTION_NODE", + "PageChangeEvent", + "PageTransitionEvent", + "PaintRequest", + "PaintRequestList", + "PannerNode", + "PasswordCredential", + "Path2D", + "PaymentAddress", + "PaymentInstruments", + "PaymentManager", + "PaymentMethodChangeEvent", + "PaymentRequest", + "PaymentRequestUpdateEvent", + "PaymentResponse", + "Performance", + "PerformanceElementTiming", + "PerformanceEntry", + "PerformanceEventTiming", + "PerformanceLongTaskTiming", + "PerformanceMark", + "PerformanceMeasure", + "PerformanceNavigation", + "PerformanceNavigationTiming", + "PerformanceObserver", + "PerformanceObserverEntryList", + "PerformancePaintTiming", + "PerformanceResourceTiming", + "PerformanceServerTiming", + "PerformanceTiming", + "PeriodicSyncManager", + "PeriodicWave", + "PermissionStatus", + "Permissions", + "PhotoCapabilities", + "PictureInPictureWindow", + "PlatformArch", + "PlatformNaclArch", + "PlatformOs", + "Plugin", + "PluginArray", + "PluralRules", + "PointerEvent", + "PopStateEvent", + "PopupBlockedEvent", + "Position", + "PositionError", + "Presentation", + "PresentationAvailability", + "PresentationConnection", + "PresentationConnectionAvailableEvent", + "PresentationConnectionCloseEvent", + "PresentationConnectionList", + "PresentationReceiver", + "PresentationRequest", + "ProcessingInstruction", + "ProgressEvent", + "Promise", + "PromiseRejectionEvent", + "PropertyNodeList", + "Proxy", + "PublicKeyCredential", + "PushManager", + "PushSubscription", + "PushSubscriptionOptions", + "Q", + "QUERY_RESULT", + "QUERY_RESULT_AVAILABLE", + "QUOTA_ERR", + "QUOTA_EXCEEDED_ERR", + "QueryInterface", + "R11F_G11F_B10F", + "R16F", + "R16I", + "R16UI", + "R32F", + "R32I", + "R32UI", + "R8", + "R8I", + "R8UI", + "R8_SNORM", + "RASTERIZER_DISCARD", + "READY_TO_RUN", + "READ_BUFFER", + "READ_FRAMEBUFFER", + "READ_FRAMEBUFFER_BINDING", + "READ_ONLY", + "READ_ONLY_ERR", + "READ_WRITE", + "RED", + "RED_BITS", + "RED_INTEGER", + "REMOVAL", + "RENDERBUFFER", + "RENDERBUFFER_ALPHA_SIZE", + "RENDERBUFFER_BINDING", + "RENDERBUFFER_BLUE_SIZE", + "RENDERBUFFER_DEPTH_SIZE", + "RENDERBUFFER_GREEN_SIZE", + "RENDERBUFFER_HEIGHT", + "RENDERBUFFER_INTERNAL_FORMAT", + "RENDERBUFFER_RED_SIZE", + "RENDERBUFFER_SAMPLES", + "RENDERBUFFER_STENCIL_SIZE", + "RENDERBUFFER_WIDTH", + "RENDERER", + "RENDERING_INTENT_ABSOLUTE_COLORIMETRIC", + "RENDERING_INTENT_AUTO", + "RENDERING_INTENT_PERCEPTUAL", + "RENDERING_INTENT_RELATIVE_COLORIMETRIC", + "RENDERING_INTENT_SATURATION", + "RENDERING_INTENT_UNKNOWN", + "REPEAT", + "REPLACE", + "RG", + "RG16F", + "RG16I", + "RG16UI", + "RG32F", + "RG32I", + "RG32UI", + "RG8", + "RG8I", + "RG8UI", + "RG8_SNORM", + "RGB", + "RGB10_A2", + "RGB10_A2UI", + "RGB16F", + "RGB16I", + "RGB16UI", + "RGB32F", + "RGB32I", + "RGB32UI", + "RGB565", + "RGB5_A1", + "RGB8", + "RGB8I", + "RGB8UI", + "RGB8_SNORM", + "RGB9_E5", + "RGBA", + "RGBA16F", + "RGBA16I", + "RGBA16UI", + "RGBA32F", + "RGBA32I", + "RGBA32UI", + "RGBA4", + "RGBA8", + "RGBA8I", + "RGBA8UI", + "RGBA8_SNORM", + "RGBA_INTEGER", + "RGBColor", + "RGB_INTEGER", + "RG_INTEGER", + "ROTATION_CLOCKWISE", + "ROTATION_COUNTERCLOCKWISE", + "RTCCertificate", + "RTCDTMFSender", + "RTCDTMFToneChangeEvent", + "RTCDataChannel", + "RTCDataChannelEvent", + "RTCDtlsTransport", + "RTCError", + "RTCErrorEvent", + "RTCIceCandidate", + "RTCIceTransport", + "RTCPeerConnection", + "RTCPeerConnectionIceErrorEvent", + "RTCPeerConnectionIceEvent", + "RTCRtpReceiver", + "RTCRtpSender", + "RTCRtpTransceiver", + "RTCSctpTransport", + "RTCSessionDescription", + "RTCStatsReport", + "RTCTrackEvent", + "RUNNING", + "RadioNodeList", + "Range", + "RangeError", + "RangeException", + "ReadableByteStream", + "ReadableStream", + "ReadableStreamDefaultReader", + "RecordErrorEvent", + "Rect", + "ReferenceError", + "Reflect", + "RegExp", + "RelativeOrientationSensor", + "RelativeTimeFormat", + "RemotePlayback", + "ReportingObserver", + "Request", + "RequestUpdateCheckStatus", + "ResizeObserver", + "ResizeObserverEntry", + "ResizeObserverSize", + "Response", + "RunningState", + "RuntimeError", + "SAMPLER_2D", + "SAMPLER_2D_ARRAY", + "SAMPLER_2D_ARRAY_SHADOW", + "SAMPLER_2D_SHADOW", + "SAMPLER_3D", + "SAMPLER_BINDING", + "SAMPLER_CUBE", + "SAMPLER_CUBE_SHADOW", + "SAMPLES", + "SAMPLE_ALPHA_TO_COVERAGE", + "SAMPLE_BUFFERS", + "SAMPLE_COVERAGE", + "SAMPLE_COVERAGE_INVERT", + "SAMPLE_COVERAGE_VALUE", + "SAWTOOTH", + "SCHEDULED_STATE", + "SCISSOR_BOX", + "SCISSOR_TEST", + "SCROLL_PAGE_DOWN", + "SCROLL_PAGE_UP", + "SDP_ANSWER", + "SDP_OFFER", + "SDP_PRANSWER", + "SECURITY_ERR", + "SELECT", + "SEPARATE_ATTRIBS", + "SERIALIZE_ERR", + "SEVERITY_ERROR", + "SEVERITY_FATAL_ERROR", + "SEVERITY_WARNING", + "SHADER_COMPILER", + "SHADER_TYPE", + "SHADING_LANGUAGE_VERSION", + "SHARED_MODULE_UPDATE", + "SHIFT_MASK", + "SHORT", + "SHOWING", + "SHOW_ALL", + "SHOW_ATTRIBUTE", + "SHOW_CDATA_SECTION", + "SHOW_COMMENT", + "SHOW_DOCUMENT", + "SHOW_DOCUMENT_FRAGMENT", + "SHOW_DOCUMENT_TYPE", + "SHOW_ELEMENT", + "SHOW_ENTITY", + "SHOW_ENTITY_REFERENCE", + "SHOW_NOTATION", + "SHOW_PROCESSING_INSTRUCTION", + "SHOW_TEXT", + "SIGNALED", + "SIGNED_NORMALIZED", + "SINE", + "SKIN", + "SOUNDFIELD", + "SQLError", + "SQLException", + "SQLResultSet", + "SQLResultSetRowList", + "SQLTransaction", + "SQRT1_2", + "SQRT2", + "SQUARE", + "SRC_ALPHA", + "SRC_ALPHA_SATURATE", + "SRC_COLOR", + "SRGB", + "SRGB8", + "SRGB8_ALPHA8", + "START_TO_END", + "START_TO_START", + "STATIC_COPY", + "STATIC_DRAW", + "STATIC_READ", + "STENCIL", + "STENCIL_ATTACHMENT", + "STENCIL_BACK_FAIL", + "STENCIL_BACK_FUNC", + "STENCIL_BACK_PASS_DEPTH_FAIL", + "STENCIL_BACK_PASS_DEPTH_PASS", + "STENCIL_BACK_REF", + "STENCIL_BACK_VALUE_MASK", + "STENCIL_BACK_WRITEMASK", + "STENCIL_BITS", + "STENCIL_BUFFER_BIT", + "STENCIL_CLEAR_VALUE", + "STENCIL_FAIL", + "STENCIL_FUNC", + "STENCIL_INDEX", + "STENCIL_INDEX8", + "STENCIL_PASS_DEPTH_FAIL", + "STENCIL_PASS_DEPTH_PASS", + "STENCIL_REF", + "STENCIL_TEST", + "STENCIL_VALUE_MASK", + "STENCIL_WRITEMASK", + "STREAM_COPY", + "STREAM_DRAW", + "STREAM_READ", + "STRING_TYPE", + "STYLE_RULE", + "SUBPIXEL_BITS", + "SUPPORTS_RULE", + "SVGAElement", + "SVGAltGlyphDefElement", + "SVGAltGlyphElement", + "SVGAltGlyphItemElement", + "SVGAngle", + "SVGAnimateColorElement", + "SVGAnimateElement", + "SVGAnimateMotionElement", + "SVGAnimateTransformElement", + "SVGAnimatedAngle", + "SVGAnimatedBoolean", + "SVGAnimatedEnumeration", + "SVGAnimatedInteger", + "SVGAnimatedLength", + "SVGAnimatedLengthList", + "SVGAnimatedNumber", + "SVGAnimatedNumberList", + "SVGAnimatedPreserveAspectRatio", + "SVGAnimatedRect", + "SVGAnimatedString", + "SVGAnimatedTransformList", + "SVGAnimationElement", + "SVGCircleElement", + "SVGClipPathElement", + "SVGColor", + "SVGComponentTransferFunctionElement", + "SVGCursorElement", + "SVGDefsElement", + "SVGDescElement", + "SVGDiscardElement", + "SVGDocument", + "SVGElement", + "SVGElementInstance", + "SVGElementInstanceList", + "SVGEllipseElement", + "SVGException", + "SVGFEBlendElement", + "SVGFEColorMatrixElement", + "SVGFEComponentTransferElement", + "SVGFECompositeElement", + "SVGFEConvolveMatrixElement", + "SVGFEDiffuseLightingElement", + "SVGFEDisplacementMapElement", + "SVGFEDistantLightElement", + "SVGFEDropShadowElement", + "SVGFEFloodElement", + "SVGFEFuncAElement", + "SVGFEFuncBElement", + "SVGFEFuncGElement", + "SVGFEFuncRElement", + "SVGFEGaussianBlurElement", + "SVGFEImageElement", + "SVGFEMergeElement", + "SVGFEMergeNodeElement", + "SVGFEMorphologyElement", + "SVGFEOffsetElement", + "SVGFEPointLightElement", + "SVGFESpecularLightingElement", + "SVGFESpotLightElement", + "SVGFETileElement", + "SVGFETurbulenceElement", + "SVGFilterElement", + "SVGFontElement", + "SVGFontFaceElement", + "SVGFontFaceFormatElement", + "SVGFontFaceNameElement", + "SVGFontFaceSrcElement", + "SVGFontFaceUriElement", + "SVGForeignObjectElement", + "SVGGElement", + "SVGGeometryElement", + "SVGGlyphElement", + "SVGGlyphRefElement", + "SVGGradientElement", + "SVGGraphicsElement", + "SVGHKernElement", + "SVGImageElement", + "SVGLength", + "SVGLengthList", + "SVGLineElement", + "SVGLinearGradientElement", + "SVGMPathElement", + "SVGMarkerElement", + "SVGMaskElement", + "SVGMatrix", + "SVGMetadataElement", + "SVGMissingGlyphElement", + "SVGNumber", + "SVGNumberList", + "SVGPaint", + "SVGPathElement", + "SVGPathSeg", + "SVGPathSegArcAbs", + "SVGPathSegArcRel", + "SVGPathSegClosePath", + "SVGPathSegCurvetoCubicAbs", + "SVGPathSegCurvetoCubicRel", + "SVGPathSegCurvetoCubicSmoothAbs", + "SVGPathSegCurvetoCubicSmoothRel", + "SVGPathSegCurvetoQuadraticAbs", + "SVGPathSegCurvetoQuadraticRel", + "SVGPathSegCurvetoQuadraticSmoothAbs", + "SVGPathSegCurvetoQuadraticSmoothRel", + "SVGPathSegLinetoAbs", + "SVGPathSegLinetoHorizontalAbs", + "SVGPathSegLinetoHorizontalRel", + "SVGPathSegLinetoRel", + "SVGPathSegLinetoVerticalAbs", + "SVGPathSegLinetoVerticalRel", + "SVGPathSegList", + "SVGPathSegMovetoAbs", + "SVGPathSegMovetoRel", + "SVGPatternElement", + "SVGPoint", + "SVGPointList", + "SVGPolygonElement", + "SVGPolylineElement", + "SVGPreserveAspectRatio", + "SVGRadialGradientElement", + "SVGRect", + "SVGRectElement", + "SVGRenderingIntent", + "SVGSVGElement", + "SVGScriptElement", + "SVGSetElement", + "SVGStopElement", + "SVGStringList", + "SVGStyleElement", + "SVGSwitchElement", + "SVGSymbolElement", + "SVGTRefElement", + "SVGTSpanElement", + "SVGTextContentElement", + "SVGTextElement", + "SVGTextPathElement", + "SVGTextPositioningElement", + "SVGTitleElement", + "SVGTransform", + "SVGTransformList", + "SVGUnitTypes", + "SVGUseElement", + "SVGVKernElement", + "SVGViewElement", + "SVGViewSpec", + "SVGZoomAndPan", + "SVGZoomEvent", + "SVG_ANGLETYPE_DEG", + "SVG_ANGLETYPE_GRAD", + "SVG_ANGLETYPE_RAD", + "SVG_ANGLETYPE_UNKNOWN", + "SVG_ANGLETYPE_UNSPECIFIED", + "SVG_CHANNEL_A", + "SVG_CHANNEL_B", + "SVG_CHANNEL_G", + "SVG_CHANNEL_R", + "SVG_CHANNEL_UNKNOWN", + "SVG_COLORTYPE_CURRENTCOLOR", + "SVG_COLORTYPE_RGBCOLOR", + "SVG_COLORTYPE_RGBCOLOR_ICCCOLOR", + "SVG_COLORTYPE_UNKNOWN", + "SVG_EDGEMODE_DUPLICATE", + "SVG_EDGEMODE_NONE", + "SVG_EDGEMODE_UNKNOWN", + "SVG_EDGEMODE_WRAP", + "SVG_FEBLEND_MODE_COLOR", + "SVG_FEBLEND_MODE_COLOR_BURN", + "SVG_FEBLEND_MODE_COLOR_DODGE", + "SVG_FEBLEND_MODE_DARKEN", + "SVG_FEBLEND_MODE_DIFFERENCE", + "SVG_FEBLEND_MODE_EXCLUSION", + "SVG_FEBLEND_MODE_HARD_LIGHT", + "SVG_FEBLEND_MODE_HUE", + "SVG_FEBLEND_MODE_LIGHTEN", + "SVG_FEBLEND_MODE_LUMINOSITY", + "SVG_FEBLEND_MODE_MULTIPLY", + "SVG_FEBLEND_MODE_NORMAL", + "SVG_FEBLEND_MODE_OVERLAY", + "SVG_FEBLEND_MODE_SATURATION", + "SVG_FEBLEND_MODE_SCREEN", + "SVG_FEBLEND_MODE_SOFT_LIGHT", + "SVG_FEBLEND_MODE_UNKNOWN", + "SVG_FECOLORMATRIX_TYPE_HUEROTATE", + "SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA", + "SVG_FECOLORMATRIX_TYPE_MATRIX", + "SVG_FECOLORMATRIX_TYPE_SATURATE", + "SVG_FECOLORMATRIX_TYPE_UNKNOWN", + "SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE", + "SVG_FECOMPONENTTRANSFER_TYPE_GAMMA", + "SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY", + "SVG_FECOMPONENTTRANSFER_TYPE_LINEAR", + "SVG_FECOMPONENTTRANSFER_TYPE_TABLE", + "SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN", + "SVG_FECOMPOSITE_OPERATOR_ARITHMETIC", + "SVG_FECOMPOSITE_OPERATOR_ATOP", + "SVG_FECOMPOSITE_OPERATOR_IN", + "SVG_FECOMPOSITE_OPERATOR_OUT", + "SVG_FECOMPOSITE_OPERATOR_OVER", + "SVG_FECOMPOSITE_OPERATOR_UNKNOWN", + "SVG_FECOMPOSITE_OPERATOR_XOR", + "SVG_INVALID_VALUE_ERR", + "SVG_LENGTHTYPE_CM", + "SVG_LENGTHTYPE_EMS", + "SVG_LENGTHTYPE_EXS", + "SVG_LENGTHTYPE_IN", + "SVG_LENGTHTYPE_MM", + "SVG_LENGTHTYPE_NUMBER", + "SVG_LENGTHTYPE_PC", + "SVG_LENGTHTYPE_PERCENTAGE", + "SVG_LENGTHTYPE_PT", + "SVG_LENGTHTYPE_PX", + "SVG_LENGTHTYPE_UNKNOWN", + "SVG_MARKERUNITS_STROKEWIDTH", + "SVG_MARKERUNITS_UNKNOWN", + "SVG_MARKERUNITS_USERSPACEONUSE", + "SVG_MARKER_ORIENT_ANGLE", + "SVG_MARKER_ORIENT_AUTO", + "SVG_MARKER_ORIENT_UNKNOWN", + "SVG_MASKTYPE_ALPHA", + "SVG_MASKTYPE_LUMINANCE", + "SVG_MATRIX_NOT_INVERTABLE", + "SVG_MEETORSLICE_MEET", + "SVG_MEETORSLICE_SLICE", + "SVG_MEETORSLICE_UNKNOWN", + "SVG_MORPHOLOGY_OPERATOR_DILATE", + "SVG_MORPHOLOGY_OPERATOR_ERODE", + "SVG_MORPHOLOGY_OPERATOR_UNKNOWN", + "SVG_PAINTTYPE_CURRENTCOLOR", + "SVG_PAINTTYPE_NONE", + "SVG_PAINTTYPE_RGBCOLOR", + "SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR", + "SVG_PAINTTYPE_UNKNOWN", + "SVG_PAINTTYPE_URI", + "SVG_PAINTTYPE_URI_CURRENTCOLOR", + "SVG_PAINTTYPE_URI_NONE", + "SVG_PAINTTYPE_URI_RGBCOLOR", + "SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR", + "SVG_PRESERVEASPECTRATIO_NONE", + "SVG_PRESERVEASPECTRATIO_UNKNOWN", + "SVG_PRESERVEASPECTRATIO_XMAXYMAX", + "SVG_PRESERVEASPECTRATIO_XMAXYMID", + "SVG_PRESERVEASPECTRATIO_XMAXYMIN", + "SVG_PRESERVEASPECTRATIO_XMIDYMAX", + "SVG_PRESERVEASPECTRATIO_XMIDYMID", + "SVG_PRESERVEASPECTRATIO_XMIDYMIN", + "SVG_PRESERVEASPECTRATIO_XMINYMAX", + "SVG_PRESERVEASPECTRATIO_XMINYMID", + "SVG_PRESERVEASPECTRATIO_XMINYMIN", + "SVG_SPREADMETHOD_PAD", + "SVG_SPREADMETHOD_REFLECT", + "SVG_SPREADMETHOD_REPEAT", + "SVG_SPREADMETHOD_UNKNOWN", + "SVG_STITCHTYPE_NOSTITCH", + "SVG_STITCHTYPE_STITCH", + "SVG_STITCHTYPE_UNKNOWN", + "SVG_TRANSFORM_MATRIX", + "SVG_TRANSFORM_ROTATE", + "SVG_TRANSFORM_SCALE", + "SVG_TRANSFORM_SKEWX", + "SVG_TRANSFORM_SKEWY", + "SVG_TRANSFORM_TRANSLATE", + "SVG_TRANSFORM_UNKNOWN", + "SVG_TURBULENCE_TYPE_FRACTALNOISE", + "SVG_TURBULENCE_TYPE_TURBULENCE", + "SVG_TURBULENCE_TYPE_UNKNOWN", + "SVG_UNIT_TYPE_OBJECTBOUNDINGBOX", + "SVG_UNIT_TYPE_UNKNOWN", + "SVG_UNIT_TYPE_USERSPACEONUSE", + "SVG_WRONG_TYPE_ERR", + "SVG_ZOOMANDPAN_DISABLE", + "SVG_ZOOMANDPAN_MAGNIFY", + "SVG_ZOOMANDPAN_UNKNOWN", + "SYNC_CONDITION", + "SYNC_FENCE", + "SYNC_FLAGS", + "SYNC_FLUSH_COMMANDS_BIT", + "SYNC_GPU_COMMANDS_COMPLETE", + "SYNC_STATUS", + "SYNTAX_ERR", + "SavedPages", + "Screen", + "ScreenOrientation", + "Script", + "ScriptEngine", + "ScriptEngineBuildVersion", + "ScriptEngineMajorVersion", + "ScriptEngineMinorVersion", + "ScriptProcessorNode", + "ScrollAreaEvent", + "SecurityPolicyViolationEvent", + "Selection", + "Sensor", + "SensorErrorEvent", + "ServiceWorker", + "ServiceWorkerContainer", + "ServiceWorkerMessageEvent", + "ServiceWorkerRegistration", + "SessionDescription", + "Set", + "ShadowRoot", + "SharedArrayBuffer", + "SharedWorker", + "SimpleGestureEvent", + "SourceBuffer", + "SourceBufferList", + "SpeechSynthesis", + "SpeechSynthesisErrorEvent", + "SpeechSynthesisEvent", + "SpeechSynthesisUtterance", + "SpeechSynthesisVoice", + "StaticRange", + "StereoPannerNode", + "StopIteration", + "Storage", + "StorageEvent", + "StorageManager", + "String", + "StyleMedia", + "StylePropertyMap", + "StylePropertyMapReadOnly", + "StyleSheet", + "StyleSheetList", + "StyleSheetPageList", + "SubmitEvent", + "SubtleCrypto", + "Symbol", + "SyncManager", + "SyntaxError", + "TEMPORARY", + "TEXTPATH_METHODTYPE_ALIGN", + "TEXTPATH_METHODTYPE_STRETCH", + "TEXTPATH_METHODTYPE_UNKNOWN", + "TEXTPATH_SPACINGTYPE_AUTO", + "TEXTPATH_SPACINGTYPE_EXACT", + "TEXTPATH_SPACINGTYPE_UNKNOWN", + "TEXTURE", + "TEXTURE0", + "TEXTURE1", + "TEXTURE10", + "TEXTURE11", + "TEXTURE12", + "TEXTURE13", + "TEXTURE14", + "TEXTURE15", + "TEXTURE16", + "TEXTURE17", + "TEXTURE18", + "TEXTURE19", + "TEXTURE2", + "TEXTURE20", + "TEXTURE21", + "TEXTURE22", + "TEXTURE23", + "TEXTURE24", + "TEXTURE25", + "TEXTURE26", + "TEXTURE27", + "TEXTURE28", + "TEXTURE29", + "TEXTURE3", + "TEXTURE30", + "TEXTURE31", + "TEXTURE4", + "TEXTURE5", + "TEXTURE6", + "TEXTURE7", + "TEXTURE8", + "TEXTURE9", + "TEXTURE_2D", + "TEXTURE_2D_ARRAY", + "TEXTURE_3D", + "TEXTURE_BASE_LEVEL", + "TEXTURE_BINDING_2D", + "TEXTURE_BINDING_2D_ARRAY", + "TEXTURE_BINDING_3D", + "TEXTURE_BINDING_CUBE_MAP", + "TEXTURE_COMPARE_FUNC", + "TEXTURE_COMPARE_MODE", + "TEXTURE_CUBE_MAP", + "TEXTURE_CUBE_MAP_NEGATIVE_X", + "TEXTURE_CUBE_MAP_NEGATIVE_Y", + "TEXTURE_CUBE_MAP_NEGATIVE_Z", + "TEXTURE_CUBE_MAP_POSITIVE_X", + "TEXTURE_CUBE_MAP_POSITIVE_Y", + "TEXTURE_CUBE_MAP_POSITIVE_Z", + "TEXTURE_IMMUTABLE_FORMAT", + "TEXTURE_IMMUTABLE_LEVELS", + "TEXTURE_MAG_FILTER", + "TEXTURE_MAX_ANISOTROPY_EXT", + "TEXTURE_MAX_LEVEL", + "TEXTURE_MAX_LOD", + "TEXTURE_MIN_FILTER", + "TEXTURE_MIN_LOD", + "TEXTURE_WRAP_R", + "TEXTURE_WRAP_S", + "TEXTURE_WRAP_T", + "TEXT_NODE", + "THROTTLED", + "TIMEOUT", + "TIMEOUT_ERR", + "TIMEOUT_EXPIRED", + "TIMEOUT_IGNORED", + "TOO_LARGE_ERR", + "TRANSACTION_INACTIVE_ERR", + "TRANSFORM_FEEDBACK", + "TRANSFORM_FEEDBACK_ACTIVE", + "TRANSFORM_FEEDBACK_BINDING", + "TRANSFORM_FEEDBACK_BUFFER", + "TRANSFORM_FEEDBACK_BUFFER_BINDING", + "TRANSFORM_FEEDBACK_BUFFER_MODE", + "TRANSFORM_FEEDBACK_BUFFER_SIZE", + "TRANSFORM_FEEDBACK_BUFFER_START", + "TRANSFORM_FEEDBACK_PAUSED", + "TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN", + "TRANSFORM_FEEDBACK_VARYINGS", + "TRIANGLE", + "TRIANGLES", + "TRIANGLE_FAN", + "TRIANGLE_STRIP", + "TYPE_BACK_FORWARD", + "TYPE_ERR", + "TYPE_MISMATCH_ERR", + "TYPE_NAVIGATE", + "TYPE_RELOAD", + "TYPE_RESERVED", + "Table", + "TaskAttributionTiming", + "Text", + "TextDecoder", + "TextDecoderStream", + "TextEncoder", + "TextEncoderStream", + "TextEvent", + "TextMetrics", + "TextRange", + "TextRangeCollection", + "TextTrack", + "TextTrackCue", + "TextTrackCueList", + "TextTrackList", + "TimeEvent", + "TimeRanges", + "Touch", + "TouchEvent", + "TouchList", + "TrackEvent", + "TransformStream", + "TransitionEvent", + "TreeWalker", + "TrustedHTML", + "TrustedScript", + "TrustedScriptURL", + "TrustedTypePolicy", + "TrustedTypePolicyFactory", + "TypeError", + "U2F", + "UIEvent", + "UNCACHED", + "UNIFORM_ARRAY_STRIDE", + "UNIFORM_BLOCK_ACTIVE_UNIFORMS", + "UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES", + "UNIFORM_BLOCK_BINDING", + "UNIFORM_BLOCK_DATA_SIZE", + "UNIFORM_BLOCK_INDEX", + "UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER", + "UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER", + "UNIFORM_BUFFER", + "UNIFORM_BUFFER_BINDING", + "UNIFORM_BUFFER_OFFSET_ALIGNMENT", + "UNIFORM_BUFFER_SIZE", + "UNIFORM_BUFFER_START", + "UNIFORM_IS_ROW_MAJOR", + "UNIFORM_MATRIX_STRIDE", + "UNIFORM_OFFSET", + "UNIFORM_SIZE", + "UNIFORM_TYPE", + "UNKNOWN_ERR", + "UNKNOWN_RULE", + "UNMASKED_RENDERER_WEBGL", + "UNMASKED_VENDOR_WEBGL", + "UNORDERED_NODE_ITERATOR_TYPE", + "UNORDERED_NODE_SNAPSHOT_TYPE", + "UNPACK_ALIGNMENT", + "UNPACK_COLORSPACE_CONVERSION_WEBGL", + "UNPACK_FLIP_Y_WEBGL", + "UNPACK_IMAGE_HEIGHT", + "UNPACK_PREMULTIPLY_ALPHA_WEBGL", + "UNPACK_ROW_LENGTH", + "UNPACK_SKIP_IMAGES", + "UNPACK_SKIP_PIXELS", + "UNPACK_SKIP_ROWS", + "UNSCHEDULED_STATE", + "UNSENT", + "UNSIGNALED", + "UNSIGNED_BYTE", + "UNSIGNED_INT", + "UNSIGNED_INT_10F_11F_11F_REV", + "UNSIGNED_INT_24_8", + "UNSIGNED_INT_2_10_10_10_REV", + "UNSIGNED_INT_5_9_9_9_REV", + "UNSIGNED_INT_SAMPLER_2D", + "UNSIGNED_INT_SAMPLER_2D_ARRAY", + "UNSIGNED_INT_SAMPLER_3D", + "UNSIGNED_INT_SAMPLER_CUBE", + "UNSIGNED_INT_VEC2", + "UNSIGNED_INT_VEC3", + "UNSIGNED_INT_VEC4", + "UNSIGNED_NORMALIZED", + "UNSIGNED_SHORT", + "UNSIGNED_SHORT_4_4_4_4", + "UNSIGNED_SHORT_5_5_5_1", + "UNSIGNED_SHORT_5_6_5", + "UNSPECIFIED_EVENT_TYPE_ERR", + "UPDATE", + "UPDATEREADY", + "UPDATE_AVAILABLE", + "URIError", + "URL", + "URLSearchParams", + "URLUnencoded", + "URL_MISMATCH_ERR", + "USB", + "USBAlternateInterface", + "USBConfiguration", + "USBConnectionEvent", + "USBDevice", + "USBEndpoint", + "USBInTransferResult", + "USBInterface", + "USBIsochronousInTransferPacket", + "USBIsochronousInTransferResult", + "USBIsochronousOutTransferPacket", + "USBIsochronousOutTransferResult", + "USBOutTransferResult", + "UTC", + "Uint16Array", + "Uint32Array", + "Uint8Array", + "Uint8ClampedArray", + "UserActivation", + "UserMessageHandler", + "UserMessageHandlersNamespace", + "UserProximityEvent", + "VALIDATE_STATUS", + "VALIDATION_ERR", + "VARIABLES_RULE", + "VBArray", + "VENDOR", + "VERSION", + "VERSION_CHANGE", + "VERSION_ERR", + "VERTEX_ARRAY_BINDING", + "VERTEX_ATTRIB_ARRAY_BUFFER_BINDING", + "VERTEX_ATTRIB_ARRAY_DIVISOR", + "VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE", + "VERTEX_ATTRIB_ARRAY_ENABLED", + "VERTEX_ATTRIB_ARRAY_INTEGER", + "VERTEX_ATTRIB_ARRAY_NORMALIZED", + "VERTEX_ATTRIB_ARRAY_POINTER", + "VERTEX_ATTRIB_ARRAY_SIZE", + "VERTEX_ATTRIB_ARRAY_STRIDE", + "VERTEX_ATTRIB_ARRAY_TYPE", + "VERTEX_SHADER", + "VERTICAL", + "VERTICAL_AXIS", + "VER_ERR", + "VIEWPORT", + "VIEWPORT_RULE", + "VRDisplay", + "VRDisplayCapabilities", + "VRDisplayEvent", + "VREyeParameters", + "VRFieldOfView", + "VRFrameData", + "VRPose", + "VRStageParameters", + "VTTCue", + "VTTRegion", + "ValidityState", + "VideoPlaybackQuality", + "VideoStreamTrack", + "VideoTrack", + "VideoTrackList", + "VisualViewport", + "WAIT_FAILED", + "WEBGL_compressed_texture_s3tc", + "WEBGL_debug_renderer_info", + "WEBKIT_FILTER_RULE", + "WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN", + "WEBKIT_FORCE_AT_MOUSE_DOWN", + "WEBKIT_KEYFRAMES_RULE", + "WEBKIT_KEYFRAME_RULE", + "WEBKIT_REGION_RULE", + "WIN", + "WRONG_DOCUMENT_ERR", + "WakeLock", + "WakeLockSentinel", + "WaveShaperNode", + "WeakMap", + "WeakRef", + "WeakSet", + "WebAssembly", + "WebGL2RenderingContext", + "WebGLActiveInfo", + "WebGLBuffer", + "WebGLContextEvent", + "WebGLFramebuffer", + "WebGLObject", + "WebGLProgram", + "WebGLQuery", + "WebGLRenderbuffer", + "WebGLRenderingContext", + "WebGLSampler", + "WebGLShader", + "WebGLShaderPrecisionFormat", + "WebGLSync", + "WebGLTexture", + "WebGLTransformFeedback", + "WebGLUniformLocation", + "WebGLVertexArray", + "WebGLVertexArrayObject", + "WebKit built-in PDF", + "WebKitAnimationEvent", + "WebKitBlobBuilder", + "WebKitCSSFilterRule", + "WebKitCSSFilterValue", + "WebKitCSSKeyframeRule", + "WebKitCSSKeyframesRule", + "WebKitCSSMatrix", + "WebKitCSSRegionRule", + "WebKitCSSTransformValue", + "WebKitDataCue", + "WebKitGamepad", + "WebKitMediaKeyError", + "WebKitMediaKeyMessageEvent", + "WebKitMediaKeyNeededEvent", + "WebKitMediaKeySession", + "WebKitMediaKeys", + "WebKitMediaSource", + "WebKitMutationObserver", + "WebKitNamespace", + "WebKitPlaybackTargetAvailabilityEvent", + "WebKitPoint", + "WebKitShadowRoot", + "WebKitSourceBuffer", + "WebKitSourceBufferList", + "WebKitTransitionEvent", + "WebSocket", + "WebkitAlignContent", + "WebkitAlignItems", + "WebkitAlignSelf", + "WebkitAnimation", + "WebkitAnimationDelay", + "WebkitAnimationDirection", + "WebkitAnimationDuration", + "WebkitAnimationFillMode", + "WebkitAnimationIterationCount", + "WebkitAnimationName", + "WebkitAnimationPlayState", + "WebkitAnimationTimingFunction", + "WebkitAppearance", + "WebkitBackfaceVisibility", + "WebkitBackgroundClip", + "WebkitBackgroundOrigin", + "WebkitBackgroundSize", + "WebkitBorderBottomLeftRadius", + "WebkitBorderBottomRightRadius", + "WebkitBorderImage", + "WebkitBorderRadius", + "WebkitBorderTopLeftRadius", + "WebkitBorderTopRightRadius", + "WebkitBoxAlign", + "WebkitBoxDirection", + "WebkitBoxFlex", + "WebkitBoxOrdinalGroup", + "WebkitBoxOrient", + "WebkitBoxPack", + "WebkitBoxShadow", + "WebkitBoxSizing", + "WebkitFilter", + "WebkitFlex", + "WebkitFlexBasis", + "WebkitFlexDirection", + "WebkitFlexFlow", + "WebkitFlexGrow", + "WebkitFlexShrink", + "WebkitFlexWrap", + "WebkitJustifyContent", + "WebkitLineClamp", + "WebkitMask", + "WebkitMaskClip", + "WebkitMaskComposite", + "WebkitMaskImage", + "WebkitMaskOrigin", + "WebkitMaskPosition", + "WebkitMaskPositionX", + "WebkitMaskPositionY", + "WebkitMaskRepeat", + "WebkitMaskSize", + "WebkitOrder", + "WebkitPerspective", + "WebkitPerspectiveOrigin", + "WebkitTextFillColor", + "WebkitTextSizeAdjust", + "WebkitTextStroke", + "WebkitTextStrokeColor", + "WebkitTextStrokeWidth", + "WebkitTransform", + "WebkitTransformOrigin", + "WebkitTransformStyle", + "WebkitTransition", + "WebkitTransitionDelay", + "WebkitTransitionDuration", + "WebkitTransitionProperty", + "WebkitTransitionTimingFunction", + "WebkitUserSelect", + "WheelEvent", + "Window", + "Windows Media Player Plug-in Dynamic Link Library", + "Windows Presentation Foundation", + "Worker", + "Worklet", + "WritableStream", + "WritableStreamDefaultWriter", + "X86_32", + "X86_64", + "XMLDocument", + "XMLHttpRequest", + "XMLHttpRequestEventTarget", + "XMLHttpRequestException", + "XMLHttpRequestProgressEvent", + "XMLHttpRequestUpload", + "XMLSerializer", + "XMLStylesheetProcessingInstruction", + "XPathEvaluator", + "XPathException", + "XPathExpression", + "XPathNSResolver", + "XPathResult", + "XR", + "XRBoundedReferenceSpace", + "XRDOMOverlayState", + "XRFrame", + "XRHitTestResult", + "XRHitTestSource", + "XRInputSource", + "XRInputSourceArray", + "XRInputSourceEvent", + "XRInputSourcesChangeEvent", + "XRLayer", + "XRPose", + "XRRay", + "XRReferenceSpace", + "XRReferenceSpaceEvent", + "XRRenderState", + "XRRigidTransform", + "XRSession", + "XRSessionEvent", + "XRSpace", + "XRSystem", + "XRTransientInputHitTestResult", + "XRTransientInputHitTestSource", + "XRView", + "XRViewerPose", + "XRViewport", + "XRWebGLLayer", + "XSLTProcessor", + "ZERO", + "_XD0M_", + "_YD0M_", + "__defineGetter__", + "__defineSetter__", + "__lookupGetter__", + "__lookupSetter__", + "__opera", + "__proto__", + "__relevantExtensionKeys", + "_browserjsran", + "a", + "aLink", + "abbr", + "abort", + "aborted", + "abs", + "absolute", + "acceleration", + "accelerationIncludingGravity", + "accelerator", + "accept", + "acceptCharset", + "acceptNode", + "accessKey", + "accessKeyLabel", + "accuracy", + "acos", + "acosh", + "action", + "actionURL", + "actions", + "activated", + "active", + "activeCues", + "activeElement", + "activeSourceBuffers", + "activeSourceCount", + "activeTexture", + "activeVRDisplays", + "actualBoundingBoxAscent", + "actualBoundingBoxDescent", + "actualBoundingBoxLeft", + "actualBoundingBoxRight", + "add", + "addAll", + "addBehavior", + "addCandidate", + "addColorStop", + "addCue", + "addElement", + "addEventListener", + "addFilter", + "addFromString", + "addFromUri", + "addIceCandidate", + "addImport", + "addListener", + "addModule", + "addNamed", + "addPageRule", + "addPath", + "addPointer", + "addRange", + "addRegion", + "addRule", + "addRules", + "addSearchEngine", + "addSourceBuffer", + "addStream", + "addTextTrack", + "addTrack", + "addTransceiver", + "addWakeLockListener", + "added", + "addedNodes", + "additionalName", + "additiveSymbols", + "addons", + "address", + "addressLine", + "adoptNode", + "adoptText", + "adoptedCallback", + "adoptedStyleSheets", + "adr", + "advance", + "after", + "album", + "alert", + "algorithm", + "align", + "align-content", + "align-items", + "align-self", + "alignContent", + "alignItems", + "alignSelf", + "alignmentBaseline", + "alinkColor", + "all", + "allSettled", + "allow", + "allowFullscreen", + "allowPaymentRequest", + "allowTransparency", + "allowedDirections", + "allowedFeatures", + "allowsFeature", + "alpha", + "alphabeticBaseline", + "alt", + "altGraphKey", + "altHtml", + "altKey", + "altLeft", + "alternate", + "alternateSetting", + "alternates", + "altitude", + "altitudeAccuracy", + "amplitude", + "ancestorOrigins", + "anchor", + "anchorNode", + "anchorOffset", + "anchors", + "and", + "angle", + "angularAcceleration", + "angularVelocity", + "animVal", + "animate", + "animatedInstanceRoot", + "animatedNormalizedPathSegList", + "animatedPathSegList", + "animatedPoints", + "animation", + "animation-delay", + "animation-direction", + "animation-duration", + "animation-fill-mode", + "animation-iteration-count", + "animation-name", + "animation-play-state", + "animation-timing-function", + "animationDelay", + "animationDirection", + "animationDuration", + "animationFillMode", + "animationIterationCount", + "animationName", + "animationPlayState", + "animationStartTime", + "animationTimingFunction", + "animationsPaused", + "anniversary", + "antialias", + "any", + "app", + "appCodeName", + "appMinorVersion", + "appName", + "appNotifications", + "appVersion", + "appearance", + "append", + "appendBuffer", + "appendChild", + "appendData", + "appendItem", + "appendMedium", + "appendNamed", + "appendRule", + "appendStream", + "appendWindowEnd", + "appendWindowStart", + "appleTrailingWord", + "applets", + "application/apple-default-browser", + "application/asx", + "application/java-deployment-toolkit", + "application/pdf", + "application/postscript", + "application/x-drm", + "application/x-drm-v2", + "application/x-google-chrome-pdf", + "application/x-java-applet", + "application/x-java-applet;deploy=10.25.2", + "application/x-java-applet;javafx=2.2.25", + "application/x-java-applet;jpi-version=1.7.0_25", + "application/x-java-applet;version=1.1", + "application/x-java-applet;version=1.1.1", + "application/x-java-applet;version=1.1.2", + "application/x-java-applet;version=1.1.3", + "application/x-java-applet;version=1.2", + "application/x-java-applet;version=1.2.1", + "application/x-java-applet;version=1.2.2", + "application/x-java-applet;version=1.3", + "application/x-java-applet;version=1.3.1", + "application/x-java-applet;version=1.4", + "application/x-java-applet;version=1.4.1", + "application/x-java-applet;version=1.4.2", + "application/x-java-applet;version=1.5", + "application/x-java-applet;version=1.6", + "application/x-java-applet;version=1.7", + "application/x-java-bean", + "application/x-java-bean;jpi-version=1.7.0_25", + "application/x-java-bean;version=1.1", + "application/x-java-bean;version=1.1.1", + "application/x-java-bean;version=1.1.2", + "application/x-java-bean;version=1.1.3", + "application/x-java-bean;version=1.2", + "application/x-java-bean;version=1.2.1", + "application/x-java-bean;version=1.2.2", + "application/x-java-bean;version=1.3", + "application/x-java-bean;version=1.3.1", + "application/x-java-bean;version=1.4", + "application/x-java-bean;version=1.4.1", + "application/x-java-bean;version=1.4.2", + "application/x-java-bean;version=1.5", + "application/x-java-bean;version=1.6", + "application/x-java-bean;version=1.7", + "application/x-java-vm", + "application/x-java-vm-npruntime", + "application/x-mplayer2", + "application/x-ms-xbap", + "application/x-nacl", + "application/x-pnacl", + "application/xaml+xml", + "applicationCache", + "applicationServerKey", + "apply", + "applyConstraints", + "applyElement", + "arc", + "arcTo", + "archive", + "areas", + "arguments", + "aria-activedescendant", + "aria-busy", + "aria-checked", + "aria-controls", + "aria-describedby", + "aria-disabled", + "aria-expanded", + "aria-flowto", + "aria-haspopup", + "aria-hidden", + "aria-invalid", + "aria-labelledby", + "aria-level", + "aria-live", + "aria-multiselectable", + "aria-owns", + "aria-posinset", + "aria-pressed", + "aria-readonly", + "aria-relevant", + "aria-required", + "aria-secret", + "aria-selected", + "aria-setsize", + "aria-valuemax", + "aria-valuemin", + "aria-valuenow", + "ariaAtomic", + "ariaAutoComplete", + "ariaBusy", + "ariaChecked", + "ariaColCount", + "ariaColIndex", + "ariaColSpan", + "ariaCurrent", + "ariaDescription", + "ariaDisabled", + "ariaExpanded", + "ariaHasPopup", + "ariaHidden", + "ariaKeyShortcuts", + "ariaLabel", + "ariaLevel", + "ariaLive", + "ariaModal", + "ariaMultiLine", + "ariaMultiSelectable", + "ariaOrientation", + "ariaPlaceholder", + "ariaPosInSet", + "ariaPressed", + "ariaReadOnly", + "ariaRelevant", + "ariaRequired", + "ariaRoleDescription", + "ariaRowCount", + "ariaRowIndex", + "ariaRowSpan", + "ariaSelected", + "ariaSetSize", + "ariaSort", + "ariaValueMax", + "ariaValueMin", + "ariaValueNow", + "ariaValueText", + "arrayBuffer", + "artist", + "artwork", + "as", + "asIntN", + "asUintN", + "asin", + "asinh", + "assert", + "assign", + "assignedElements", + "assignedNodes", + "assignedSlot", + "async", + "asyncIterator", + "atEnd", + "atan", + "atan2", + "atanh", + "atob", + "atomic", + "attachEvent", + "attachInternals", + "attachShader", + "attachShadow", + "attachments", + "attack", + "attestationObject", + "attrChange", + "attrName", + "attributeChangedCallback", + "attributeFilter", + "attributeName", + "attributeNamespace", + "attributeOldValue", + "attributeStyleMap", + "attributes", + "attribution", + "audio/x-ms-wax", + "audio/x-ms-wma", + "audioBitsPerSecond", + "audioTracks", + "audioWorklet", + "authenticatedSignedWrites", + "authenticatorData", + "autoIncrement", + "autobuffer", + "autocapitalize", + "autocomplete", + "autocorrect", + "autofocus", + "automationRate", + "autoplay", + "availHeight", + "availLeft", + "availTop", + "availWidth", + "availability", + "available", + "aversion", + "ax", + "axes", + "axis", + "ay", + "azimuth", + "b", + "back", + "backdropFilter", + "backface-visibility", + "backfaceVisibility", + "background", + "background-attachment", + "background-blend-mode", + "background-clip", + "background-color", + "background-image", + "background-origin", + "background-position", + "background-position-x", + "background-position-y", + "background-repeat", + "background-size", + "backgroundAttachment", + "backgroundBlendMode", + "backgroundClip", + "backgroundColor", + "backgroundFetch", + "backgroundImage", + "backgroundOrigin", + "backgroundPosition", + "backgroundPositionX", + "backgroundPositionY", + "backgroundRepeat", + "backgroundRepeatX", + "backgroundRepeatY", + "backgroundSize", + "badInput", + "badge", + "balance", + "baseFrequencyX", + "baseFrequencyY", + "baseLatency", + "baseLayer", + "baseName", + "baseNode", + "baseOffset", + "baseURI", + "baseVal", + "baselineShift", + "battery", + "bday", + "before", + "beginElement", + "beginElementAt", + "beginPath", + "beginQuery", + "beginTransformFeedback", + "behavior", + "behaviorCookie", + "behaviorPart", + "behaviorUrns", + "beta", + "bezierCurveTo", + "bgColor", + "bgProperties", + "bias", + "big", + "binaryType", + "bind", + "bindAttribLocation", + "bindBuffer", + "bindBufferBase", + "bindBufferRange", + "bindFramebuffer", + "bindRenderbuffer", + "bindSampler", + "bindTexture", + "bindTransformFeedback", + "bindVertexArray", + "blendColor", + "blendEquation", + "blendEquationSeparate", + "blendFunc", + "blendFuncSeparate", + "blink", + "blitFramebuffer", + "blob", + "block-size", + "blockDirection", + "blockSize", + "blockedURI", + "blue", + "bluetooth", + "blur", + "body", + "bodyUsed", + "bold", + "bookmarks", + "booleanValue", + "border", + "border-block", + "border-block-color", + "border-block-end", + "border-block-end-color", + "border-block-end-style", + "border-block-end-width", + "border-block-start", + "border-block-start-color", + "border-block-start-style", + "border-block-start-width", + "border-block-style", + "border-block-width", + "border-bottom", + "border-bottom-color", + "border-bottom-left-radius", + "border-bottom-right-radius", + "border-bottom-style", + "border-bottom-width", + "border-collapse", + "border-color", + "border-end-end-radius", + "border-end-start-radius", + "border-image", + "border-image-outset", + "border-image-repeat", + "border-image-slice", + "border-image-source", + "border-image-width", + "border-inline", + "border-inline-color", + "border-inline-end", + "border-inline-end-color", + "border-inline-end-style", + "border-inline-end-width", + "border-inline-start", + "border-inline-start-color", + "border-inline-start-style", + "border-inline-start-width", + "border-inline-style", + "border-inline-width", + "border-left", + "border-left-color", + "border-left-style", + "border-left-width", + "border-radius", + "border-right", + "border-right-color", + "border-right-style", + "border-right-width", + "border-spacing", + "border-start-end-radius", + "border-start-start-radius", + "border-style", + "border-top", + "border-top-color", + "border-top-left-radius", + "border-top-right-radius", + "border-top-style", + "border-top-width", + "border-width", + "borderBlock", + "borderBlockColor", + "borderBlockEnd", + "borderBlockEndColor", + "borderBlockEndStyle", + "borderBlockEndWidth", + "borderBlockStart", + "borderBlockStartColor", + "borderBlockStartStyle", + "borderBlockStartWidth", + "borderBlockStyle", + "borderBlockWidth", + "borderBottom", + "borderBottomColor", + "borderBottomLeftRadius", + "borderBottomRightRadius", + "borderBottomStyle", + "borderBottomWidth", + "borderBoxSize", + "borderCollapse", + "borderColor", + "borderColorDark", + "borderColorLight", + "borderEndEndRadius", + "borderEndStartRadius", + "borderImage", + "borderImageOutset", + "borderImageRepeat", + "borderImageSlice", + "borderImageSource", + "borderImageWidth", + "borderInline", + "borderInlineColor", + "borderInlineEnd", + "borderInlineEndColor", + "borderInlineEndStyle", + "borderInlineEndWidth", + "borderInlineStart", + "borderInlineStartColor", + "borderInlineStartStyle", + "borderInlineStartWidth", + "borderInlineStyle", + "borderInlineWidth", + "borderLeft", + "borderLeftColor", + "borderLeftStyle", + "borderLeftWidth", + "borderRadius", + "borderRight", + "borderRightColor", + "borderRightStyle", + "borderRightWidth", + "borderSpacing", + "borderStartEndRadius", + "borderStartStartRadius", + "borderStyle", + "borderTop", + "borderTopColor", + "borderTopLeftRadius", + "borderTopRightRadius", + "borderTopStyle", + "borderTopWidth", + "borderWidth", + "bottom", + "bottomMargin", + "bound", + "boundElements", + "boundingClientRect", + "boundingHeight", + "boundingLeft", + "boundingTop", + "boundingWidth", + "bounds", + "boundsGeometry", + "box-decoration-break", + "box-shadow", + "box-sizing", + "boxDecorationBreak", + "boxShadow", + "boxSizing", + "break-after", + "break-before", + "break-inside", + "breakAfter", + "breakBefore", + "breakInside", + "breakType", + "broadcast", + "browserLanguage", + "btoa", + "bubbles", + "buffer", + "bufferData", + "bufferDepth", + "bufferSize", + "bufferSubData", + "buffered", + "bufferedAmount", + "bufferedAmountLowThreshold", + "bufferedRendering", + "buildID", + "buildNumber", + "button", + "buttonID", + "buttons", + "byteLength", + "byteOffset", + "bytesWritten", + "c", + "cache", + "caches", + "calendar", + "call", + "caller", + "canBeFormatted", + "canBeMounted", + "canBeShared", + "canHaveChildren", + "canHaveHTML", + "canInsertDTMF", + "canMakePayment", + "canPlayType", + "canPresent", + "canTrickleIceCandidates", + "cancel", + "cancelAndHoldAtTime", + "cancelAnimationFrame", + "cancelBubble", + "cancelIdleCallback", + "cancelScheduledValues", + "cancelVideoFrameCallback", + "cancelWatchAvailability", + "cancelable", + "candidate", + "canonicalUUID", + "canvas", + "capabilities", + "caption", + "caption-side", + "captionSide", + "capture", + "captureEvents", + "captureStackTrace", + "captureStream", + "caret-color", + "caretBidiLevel", + "caretColor", + "caretPositionFromPoint", + "caretRangeFromPoint", + "caseFirst", + "cast", + "catch", + "category", + "cbrt", + "cd", + "ceil", + "cellIndex", + "cellPadding", + "cellSpacing", + "cells", + "ch", + "chOff", + "chain", + "challenge", + "changeType", + "changeVersion", + "changedTouches", + "channel", + "channelCount", + "channelCountMode", + "channelInterpretation", + "char", + "charAt", + "charCode", + "charCodeAt", + "charIndex", + "charLength", + "characterData", + "characterDataOldValue", + "characterSet", + "characteristic", + "charging", + "chargingTime", + "charset", + "check", + "checkEnclosure", + "checkFramebufferStatus", + "checkInstalled", + "checkIntersection", + "checkValidity", + "checked", + "childElementCount", + "childList", + "childNodes", + "children", + "chrome", + "ciphertext", + "cite", + "city", + "claimInterface", + "claimed", + "classList", + "className", + "classid", + "clear", + "clearAppBadge", + "clearAttributes", + "clearBufferfi", + "clearBufferfv", + "clearBufferiv", + "clearBufferuiv", + "clearColor", + "clearData", + "clearDepth", + "clearHalt", + "clearImmediate", + "clearInterval", + "clearLiveSeekableRange", + "clearMarks", + "clearMeasures", + "clearParameters", + "clearRect", + "clearResourceTimings", + "clearShadow", + "clearStencil", + "clearTimeout", + "clearWatch", + "click", + "clickCount", + "clientDataJSON", + "clientHeight", + "clientInformation", + "clientLeft", + "clientRect", + "clientRects", + "clientTop", + "clientWaitSync", + "clientWidth", + "clientX", + "clientY", + "clip", + "clip-path", + "clip-rule", + "clipBottom", + "clipLeft", + "clipPath", + "clipPathUnits", + "clipRight", + "clipRule", + "clipTop", + "clipboard", + "clipboardData", + "clone", + "cloneContents", + "cloneNode", + "cloneRange", + "close", + "closePath", + "closed", + "closest", + "clz", + "clz32", + "cm", + "cmp", + "code", + "codeBase", + "codePointAt", + "codeType", + "colSpan", + "collapse", + "collapseToEnd", + "collapseToStart", + "collapsed", + "collation", + "collect", + "colno", + "color", + "color-adjust", + "color-interpolation", + "color-interpolation-filters", + "colorAdjust", + "colorDepth", + "colorInterpolation", + "colorInterpolationFilters", + "colorMask", + "colorProfile", + "colorRendering", + "colorScheme", + "colorType", + "cols", + "column", + "column-count", + "column-fill", + "column-gap", + "column-rule", + "column-rule-color", + "column-rule-style", + "column-rule-width", + "column-span", + "column-width", + "columnCount", + "columnFill", + "columnGap", + "columnNumber", + "columnRule", + "columnRuleColor", + "columnRuleStyle", + "columnRuleWidth", + "columnSpan", + "columnWidth", + "columns", + "command", + "commit", + "commitLoadTime", + "commitPreferences", + "commitStyles", + "commonAncestorContainer", + "compact", + "compare", + "compareBoundaryPoints", + "compareDocumentPosition", + "compareEndPoints", + "compareExchange", + "compareNode", + "comparePoint", + "compatMode", + "compatible", + "compile", + "compileShader", + "compileStreaming", + "complete", + "component", + "componentFromPoint", + "composed", + "composedPath", + "composite", + "compositionEndOffset", + "compositionStartOffset", + "compressedTexImage2D", + "compressedTexImage3D", + "compressedTexSubImage2D", + "compressedTexSubImage3D", + "computedStyleMap", + "concat", + "conditionText", + "coneInnerAngle", + "coneOuterAngle", + "coneOuterGain", + "configuration", + "configurationName", + "configurationValue", + "configurations", + "confirm", + "confirmComposition", + "confirmSiteSpecificTrackingException", + "confirmWebWideTrackingException", + "connect", + "connectEnd", + "connectStart", + "connected", + "connectedCallback", + "connection", + "connectionInfo", + "connectionList", + "connectionSpeed", + "connectionState", + "connections", + "console", + "consoleHistory", + "consolidate", + "constraint", + "constrictionActive", + "construct", + "constructor", + "contactID", + "contain", + "containIntrinsicSize", + "containerId", + "containerName", + "containerSrc", + "containerType", + "contains", + "containsNode", + "content", + "contentBoxSize", + "contentDocument", + "contentEditable", + "contentHint", + "contentOverflow", + "contentRect", + "contentScriptType", + "contentStyleType", + "contentType", + "contentWindow", + "context", + "contextMenu", + "contextmenu", + "continue", + "continuePrimaryKey", + "continuous", + "control", + "controlTransferIn", + "controlTransferOut", + "controller", + "controls", + "controlsList", + "convertToBlob", + "convertToSpecifiedUnits", + "cookie", + "cookieEnabled", + "coords", + "copyBufferSubData", + "copyFromChannel", + "copyTexImage2D", + "copyTexSubImage2D", + "copyTexSubImage3D", + "copyToChannel", + "copyWithin", + "correspondingElement", + "correspondingUseElement", + "corruptedVideoFrames", + "cos", + "cosh", + "count", + "countReset", + "counter-increment", + "counter-reset", + "counter-set", + "counterIncrement", + "counterReset", + "counterSet", + "country", + "cpuClass", + "cpuSleepAllowed", + "create", + "createAnalyser", + "createAnswer", + "createAttribute", + "createAttributeNS", + "createBiquadFilter", + "createBuffer", + "createBufferSource", + "createCDATASection", + "createCSSStyleSheet", + "createCaption", + "createChannelMerger", + "createChannelSplitter", + "createComment", + "createConstantSource", + "createContextualFragment", + "createControlRange", + "createConvolver", + "createDTMFSender", + "createDataChannel", + "createDelay", + "createDelayNode", + "createDocument", + "createDocumentFragment", + "createDocumentType", + "createDynamicsCompressor", + "createElement", + "createElementNS", + "createEntityReference", + "createEvent", + "createEventObject", + "createExpression", + "createFramebuffer", + "createFunction", + "createGain", + "createGainNode", + "createHTML", + "createHTMLDocument", + "createIIRFilter", + "createImageBitmap", + "createImageData", + "createIndex", + "createJavaScriptNode", + "createLinearGradient", + "createMediaElementSource", + "createMediaKeys", + "createMediaStreamDestination", + "createMediaStreamSource", + "createMediaStreamTrackSource", + "createMutableFile", + "createNSResolver", + "createNodeIterator", + "createNotification", + "createObjectStore", + "createObjectURL", + "createOffer", + "createOscillator", + "createPanner", + "createPattern", + "createPeriodicWave", + "createPolicy", + "createPopup", + "createProcessingInstruction", + "createProgram", + "createQuery", + "createRadialGradient", + "createRange", + "createRangeCollection", + "createReader", + "createRenderbuffer", + "createSVGAngle", + "createSVGLength", + "createSVGMatrix", + "createSVGNumber", + "createSVGPathSegArcAbs", + "createSVGPathSegArcRel", + "createSVGPathSegClosePath", + "createSVGPathSegCurvetoCubicAbs", + "createSVGPathSegCurvetoCubicRel", + "createSVGPathSegCurvetoCubicSmoothAbs", + "createSVGPathSegCurvetoCubicSmoothRel", + "createSVGPathSegCurvetoQuadraticAbs", + "createSVGPathSegCurvetoQuadraticRel", + "createSVGPathSegCurvetoQuadraticSmoothAbs", + "createSVGPathSegCurvetoQuadraticSmoothRel", + "createSVGPathSegLinetoAbs", + "createSVGPathSegLinetoHorizontalAbs", + "createSVGPathSegLinetoHorizontalRel", + "createSVGPathSegLinetoRel", + "createSVGPathSegLinetoVerticalAbs", + "createSVGPathSegLinetoVerticalRel", + "createSVGPathSegMovetoAbs", + "createSVGPathSegMovetoRel", + "createSVGPoint", + "createSVGRect", + "createSVGTransform", + "createSVGTransformFromMatrix", + "createSampler", + "createScript", + "createScriptProcessor", + "createScriptURL", + "createSession", + "createShader", + "createShadowRoot", + "createStereoPanner", + "createStyleSheet", + "createTBody", + "createTFoot", + "createTHead", + "createTextNode", + "createTextRange", + "createTexture", + "createTouch", + "createTouchList", + "createTransformFeedback", + "createTreeWalker", + "createVertexArray", + "createWaveShaper", + "creationTime", + "credentials", + "crossOrigin", + "crossOriginIsolated", + "crypto", + "csi", + "csp", + "cssFloat", + "cssRules", + "cssText", + "cssValueType", + "ctrlKey", + "ctrlLeft", + "cues", + "cullFace", + "currency", + "currencyDisplay", + "current", + "currentDirection", + "currentLocalDescription", + "currentNode", + "currentPage", + "currentRect", + "currentRemoteDescription", + "currentScale", + "currentScript", + "currentSrc", + "currentState", + "currentStyle", + "currentTarget", + "currentTime", + "currentTranslate", + "currentView", + "cursor", + "curve", + "customElements", + "customError", + "customSections", + "cx", + "cy", + "d", + "data", + "dataFld", + "dataFormatAs", + "dataLoss", + "dataLossMessage", + "dataPageSize", + "dataSrc", + "dataTransfer", + "database", + "databases", + "dataset", + "dateTime", + "day", + "db", + "debug", + "debuggerEnabled", + "declare", + "decode", + "decodeAudioData", + "decodeURI", + "decodeURIComponent", + "decodedBodySize", + "decoding", + "decodingInfo", + "decrypt", + "default", + "defaultCharset", + "defaultChecked", + "defaultMuted", + "defaultPlaybackRate", + "defaultPolicy", + "defaultPrevented", + "defaultRequest", + "defaultSelected", + "defaultStatus", + "defaultURL", + "defaultValue", + "defaultView", + "defaultstatus", + "defer", + "define", + "defineMagicFunction", + "defineMagicVariable", + "defineProperties", + "defineProperty", + "deg", + "delay", + "delayTime", + "delegatesFocus", + "delete", + "deleteBuffer", + "deleteCaption", + "deleteCell", + "deleteContents", + "deleteData", + "deleteDatabase", + "deleteFramebuffer", + "deleteFromDocument", + "deleteIndex", + "deleteMedium", + "deleteObjectStore", + "deleteProgram", + "deleteProperty", + "deleteQuery", + "deleteRenderbuffer", + "deleteRow", + "deleteRule", + "deleteSampler", + "deleteShader", + "deleteSync", + "deleteTFoot", + "deleteTHead", + "deleteTexture", + "deleteTransformFeedback", + "deleteVertexArray", + "deliverChangeRecords", + "delivery", + "deliveryInfo", + "deliveryStatus", + "deliveryTimestamp", + "delta", + "deltaMode", + "deltaX", + "deltaY", + "deltaZ", + "dependentLocality", + "depthFar", + "depthFunc", + "depthMask", + "depthNear", + "depthRange", + "deref", + "deriveBits", + "deriveKey", + "description", + "deselectAll", + "designMode", + "desiredSize", + "destination", + "destinationURL", + "detach", + "detachEvent", + "detachShader", + "detail", + "details", + "detect", + "detune", + "device", + "deviceClass", + "deviceId", + "deviceMemory", + "devicePixelContentBoxSize", + "devicePixelRatio", + "deviceProtocol", + "deviceSessionId", + "deviceSubclass", + "deviceVersionMajor", + "deviceVersionMinor", + "deviceVersionSubminor", + "deviceXDPI", + "deviceYDPI", + "didTimeout", + "diffuseConstant", + "digest", + "dimensions", + "dir", + "dirName", + "dirXml", + "direction", + "dirxml", + "disable", + "disablePictureInPicture", + "disableRemotePlayback", + "disableVertexAttribArray", + "disabled", + "dischargingTime", + "disconnect", + "disconnectedCallback", + "dispatch", + "dispatchEvent", + "dispatchToListener", + "display", + "displayId", + "displayName", + "disposition", + "distanceModel", + "div", + "divisor", + "djsapi", + "djsproxy", + "doImport", + "doNotTrack", + "doScroll", + "doctype", + "document", + "documentElement", + "documentMode", + "documentURI", + "dolphin", + "dolphinGameCenter", + "dolphininfo", + "dolphinmeta", + "domComplete", + "domContentLoadedEventEnd", + "domContentLoadedEventStart", + "domInteractive", + "domLoading", + "domOverlayState", + "domain", + "domainLookupEnd", + "domainLookupStart", + "dominant-baseline", + "dominantBaseline", + "done", + "dopplerFactor", + "dotAll", + "downDegrees", + "downlink", + "download", + "downloadTotal", + "downloaded", + "dpcm", + "dpi", + "dppx", + "dragDrop", + "draggable", + "drawArrays", + "drawArraysInstanced", + "drawArraysInstancedANGLE", + "drawBuffers", + "drawCustomFocusRing", + "drawElements", + "drawElementsInstanced", + "drawElementsInstancedANGLE", + "drawFocusIfNeeded", + "drawImage", + "drawImageFromRect", + "drawRangeElements", + "drawSystemFocusRing", + "drawingBufferHeight", + "drawingBufferWidth", + "dropEffect", + "droppedVideoFrames", + "dropzone", + "dtmf", + "dump", + "duplicate", + "durability", + "duration", + "dvname", + "dvnum", + "dx", + "dy", + "dynsrc", + "e", + "edgeMode", + "effect", + "effectAllowed", + "effectiveDirective", + "effectiveType", + "elapsedTime", + "element", + "elementFromPoint", + "elementTiming", + "elements", + "elementsFromPoint", + "elevation", + "ellipse", + "em", + "emHeightAscent", + "emHeightDescent", + "email", + "embeds", + "emma", + "empty", + "empty-cells", + "emptyCells", + "emptyHTML", + "emptyScript", + "emulatedPosition", + "enable", + "enableBackground", + "enableDelegations", + "enableStyleSheetsForSet", + "enableVertexAttribArray", + "enabled", + "enabledPlugin", + "encode", + "encodeInto", + "encodeURI", + "encodeURIComponent", + "encodedBodySize", + "encoding", + "encodingInfo", + "encrypt", + "enctype", + "end", + "endContainer", + "endElement", + "endElementAt", + "endOfStream", + "endOffset", + "endQuery", + "endTime", + "endTransformFeedback", + "ended", + "endpoint", + "endpointNumber", + "endpoints", + "endsWith", + "enterKeyHint", + "entities", + "entries", + "entryType", + "enumerate", + "enumerateDevices", + "enumerateEditable", + "environmentBlendMode", + "epubCaptionSide", + "epubTextCombine", + "epubTextEmphasis", + "epubTextEmphasisColor", + "epubTextEmphasisStyle", + "epubTextOrientation", + "epubTextTransform", + "epubWordBreak", + "epubWritingMode", + "equals", + "era", + "error", + "errorCode", + "errorDetail", + "errorText", + "escape", + "estimate", + "eval", + "evaluate", + "event", + "eventPhase", + "every", + "ex", + "exception", + "exchange", + "exec", + "execCommand", + "execCommandShowHelp", + "execScript", + "executeSql", + "exitFullscreen", + "exitPictureInPicture", + "exitPointerLock", + "exitPresent", + "exp", + "expand", + "expandEntityReferences", + "expando", + "expansion", + "expiration", + "expirationTime", + "expires", + "expiryDate", + "explicitOriginalTarget", + "expm1", + "exponent", + "exponentialRampToValueAtTime", + "exportKey", + "exports", + "extend", + "extensions", + "extentNode", + "extentOffset", + "external", + "externalResourcesRequired", + "extractContents", + "extractable", + "eye", + "f", + "face", + "factoryReset", + "failureReason", + "fallback", + "family", + "familyName", + "farthestViewportElement", + "fastSeek", + "fatal", + "featurePolicy", + "featureSettings", + "features", + "fenceSync", + "fetch", + "fetchStart", + "fftSize", + "fgColor", + "fieldOfView", + "file", + "fileCreatedDate", + "fileHandle", + "fileModifiedDate", + "fileName", + "fileSize", + "fileUpdatedDate", + "filename", + "files", + "filesystem", + "fill", + "fill-opacity", + "fill-rule", + "fillLightMode", + "fillOpacity", + "fillRect", + "fillRule", + "fillStyle", + "fillText", + "filter", + "filterResX", + "filterResY", + "filterUnits", + "filters", + "finally", + "find", + "findIndex", + "findRule", + "findText", + "finish", + "finishDocumentLoadTime", + "finishLoadTime", + "finished", + "fireEvent", + "firesTouchEvents", + "first", + "firstChild", + "firstElementChild", + "firstPage", + "firstPaintAfterLoadTime", + "firstPaintTime", + "fixed", + "flags", + "flat", + "flatMap", + "flex", + "flex-basis", + "flex-direction", + "flex-flow", + "flex-grow", + "flex-shrink", + "flex-wrap", + "flexBasis", + "flexDirection", + "flexFlow", + "flexGrow", + "flexShrink", + "flexWrap", + "flipX", + "flipY", + "float", + "flood-color", + "flood-opacity", + "floodColor", + "floodOpacity", + "floor", + "flush", + "focus", + "focusNode", + "focusOffset", + "font", + "font-family", + "font-feature-settings", + "font-kerning", + "font-language-override", + "font-size", + "font-size-adjust", + "font-stretch", + "font-style", + "font-synthesis", + "font-variant", + "font-variant-alternates", + "font-variant-caps", + "font-variant-east-asian", + "font-variant-ligatures", + "font-variant-numeric", + "font-variant-position", + "font-weight", + "fontBoundingBoxAscent", + "fontBoundingBoxDescent", + "fontDisplay", + "fontFamily", + "fontFeatureSettings", + "fontKerning", + "fontLanguageOverride", + "fontOpticalSizing", + "fontSize", + "fontSizeAdjust", + "fontSmoothingEnabled", + "fontStretch", + "fontStyle", + "fontSynthesis", + "fontVariant", + "fontVariantAlternates", + "fontVariantCaps", + "fontVariantEastAsian", + "fontVariantLigatures", + "fontVariantNumeric", + "fontVariantPosition", + "fontVariationSettings", + "fontWeight", + "fontcolor", + "fontfaces", + "fonts", + "fontsize", + "for", + "forEach", + "force", + "forceRedraw", + "form", + "formAction", + "formData", + "formEnctype", + "formMethod", + "formNoValidate", + "formTarget", + "format", + "formatRange", + "formatRangeToParts", + "formatToParts", + "forms", + "forward", + "forwardX", + "forwardY", + "forwardZ", + "foundation", + "fr", + "fragmentDirective", + "frame", + "frameBorder", + "frameElement", + "frameSpacing", + "framebuffer", + "framebufferHeight", + "framebufferRenderbuffer", + "framebufferTexture2D", + "framebufferTextureLayer", + "framebufferWidth", + "frames", + "freeSpace", + "freeze", + "frequency", + "frequencyBinCount", + "from", + "fromCharCode", + "fromCodePoint", + "fromElement", + "fromEntries", + "fromFloat32Array", + "fromFloat64Array", + "fromMatrix", + "fromPoint", + "fromQuad", + "fromRect", + "frontFace", + "fround", + "fullPath", + "fullScreen", + "fullscreen", + "fullscreenElement", + "fullscreenEnabled", + "fx", + "fy", + "gain", + "gamepad", + "gamma", + "gap", + "gatheringState", + "gatt", + "genderIdentity", + "generateCertificate", + "generateKey", + "generateMipmap", + "generateRequest", + "geolocation", + "gestureObject", + "get", + "getActiveAttrib", + "getActiveUniform", + "getActiveUniformBlockName", + "getActiveUniformBlockParameter", + "getActiveUniforms", + "getAdditionalLanguages", + "getAdjacentText", + "getAll", + "getAllKeys", + "getAllResponseHeaders", + "getAllowlistForFeature", + "getAnimations", + "getAsFile", + "getAsString", + "getAttachedShaders", + "getAttribLocation", + "getAttribute", + "getAttributeNS", + "getAttributeNames", + "getAttributeNode", + "getAttributeNodeNS", + "getAttributeType", + "getAudioTracks", + "getAvailability", + "getBBox", + "getBattery", + "getBigInt64", + "getBigUint64", + "getBlob", + "getBookmark", + "getBoundingClientRect", + "getBounds", + "getBufferParameter", + "getBufferSubData", + "getByteFrequencyData", + "getByteTimeDomainData", + "getCSSCanvasContext", + "getCTM", + "getCandidateWindowClientRect", + "getCanonicalLocales", + "getCapabilities", + "getChannelData", + "getCharNumAtPosition", + "getCharacteristic", + "getCharacteristics", + "getClientExtensionResults", + "getClientRect", + "getClientRects", + "getCoalescedEvents", + "getCompositionAlternatives", + "getComputedStyle", + "getComputedTextLength", + "getComputedTiming", + "getConfiguration", + "getConstraints", + "getContext", + "getContextAttributes", + "getContributingSources", + "getCount", + "getCounterValue", + "getCueAsHTML", + "getCueById", + "getCurrentPosition", + "getCurrentTime", + "getData", + "getDatabaseNames", + "getDate", + "getDay", + "getDefaultComputedStyle", + "getDescriptor", + "getDescriptors", + "getDestinationInsertionPoints", + "getDetails", + "getDevices", + "getDirectory", + "getDisplayMedia", + "getDistributedNodes", + "getEditable", + "getElementById", + "getElementsByClassName", + "getElementsByName", + "getElementsByTagName", + "getElementsByTagNameNS", + "getEnclosureList", + "getEndPositionOfChar", + "getEntries", + "getEntriesByName", + "getEntriesByType", + "getError", + "getExtension", + "getExtentOfChar", + "getEyeParameters", + "getFeature", + "getFile", + "getFiles", + "getFilesAndDirectories", + "getFingerprints", + "getFloat32", + "getFloat64", + "getFloatFrequencyData", + "getFloatTimeDomainData", + "getFloatValue", + "getFragDataLocation", + "getFrameData", + "getFramebufferAttachmentParameter", + "getFrequencyResponse", + "getFullYear", + "getGamepads", + "getHitTestResults", + "getHitTestResultsForTransientInput", + "getHours", + "getIdentityAssertion", + "getIds", + "getImageData", + "getIndexedParameter", + "getInstalled", + "getInstalledRelatedApps", + "getInt16", + "getInt32", + "getInt8", + "getInternalformatParameter", + "getIntersectionList", + "getIsInstalled", + "getItem", + "getItems", + "getKey", + "getKeyframes", + "getLayers", + "getLayoutMap", + "getLineDash", + "getLocalCandidates", + "getLocalParameters", + "getLocalStreams", + "getLocalizationResource", + "getMarks", + "getMatchedCSSRules", + "getMeasures", + "getMetadata", + "getMilliseconds", + "getMinutes", + "getModifierState", + "getMonth", + "getNamedItem", + "getNamedItemNS", + "getNativeFramebufferScaleFactor", + "getNotifications", + "getNotifier", + "getNumberOfChars", + "getOffsetReferenceSpace", + "getOutputTimestamp", + "getOverrideHistoryNavigationMode", + "getOverrideStyle", + "getOwnPropertyDescriptor", + "getOwnPropertyDescriptors", + "getOwnPropertyNames", + "getOwnPropertySymbols", + "getParameter", + "getParameters", + "getParent", + "getPathSegAtLength", + "getPhotoCapabilities", + "getPhotoSettings", + "getPointAtLength", + "getPose", + "getPredictedEvents", + "getPreference", + "getPreferenceDefault", + "getPresentationAttribute", + "getPreventDefault", + "getPrimaryService", + "getPrimaryServices", + "getProgramInfoLog", + "getProgramParameter", + "getPropertyCSSValue", + "getPropertyPriority", + "getPropertyShorthand", + "getPropertyType", + "getPropertyValue", + "getPrototypeOf", + "getQuery", + "getQueryParameter", + "getRGBColorValue", + "getRandomValues", + "getRangeAt", + "getReader", + "getReceivers", + "getRectValue", + "getRegistration", + "getRegistrations", + "getRemoteCandidates", + "getRemoteCertificates", + "getRemoteParameters", + "getRemoteStreams", + "getRenderbufferParameter", + "getResponseHeader", + "getRevision", + "getRoot", + "getRootNode", + "getRotationOfChar", + "getRules", + "getSVGDocument", + "getSamplerParameter", + "getScreenCTM", + "getSeconds", + "getSelectedCandidatePair", + "getSelection", + "getSelf", + "getSenders", + "getService", + "getSettings", + "getShaderInfoLog", + "getShaderParameter", + "getShaderPrecisionFormat", + "getShaderSource", + "getSimpleDuration", + "getSiteIcons", + "getSources", + "getSpeculativeParserUrls", + "getStartDate", + "getStartPositionOfChar", + "getStartTime", + "getState", + "getStats", + "getStatusForPolicy", + "getStorageUpdates", + "getStreamById", + "getStringValue", + "getSubStringLength", + "getSubscription", + "getSupportedConstraints", + "getSupportedExtensions", + "getSupportedFormats", + "getSyncParameter", + "getSynchronizationSources", + "getTags", + "getTargetRanges", + "getTexParameter", + "getTime", + "getTimezoneOffset", + "getTiming", + "getTotalLength", + "getTrackById", + "getTracks", + "getTransceivers", + "getTransform", + "getTransformFeedbackVarying", + "getTransformToElement", + "getTransports", + "getType", + "getTypeMapping", + "getUTCDate", + "getUTCDay", + "getUTCFullYear", + "getUTCHours", + "getUTCMilliseconds", + "getUTCMinutes", + "getUTCMonth", + "getUTCSeconds", + "getUint16", + "getUint32", + "getUint8", + "getUniform", + "getUniformBlockIndex", + "getUniformIndices", + "getUniformLocation", + "getUserMedia", + "getVRDisplays", + "getValues", + "getVarDate", + "getVariableValue", + "getVertexAttrib", + "getVertexAttribOffset", + "getVideoPlaybackQuality", + "getVideoTracks", + "getViewerPose", + "getViewport", + "getVoices", + "getWakeLockState", + "getWriter", + "getYear", + "givenName", + "global", + "globalAlpha", + "globalCompositeOperation", + "globalThis", + "glyphOrientationHorizontal", + "glyphOrientationVertical", + "glyphRef", + "go", + "grabFrame", + "grad", + "gradientTransform", + "gradientUnits", + "grammars", + "green", + "grid", + "grid-area", + "grid-auto-columns", + "grid-auto-flow", + "grid-auto-rows", + "grid-column", + "grid-column-end", + "grid-column-gap", + "grid-column-start", + "grid-gap", + "grid-row", + "grid-row-end", + "grid-row-gap", + "grid-row-start", + "grid-template", + "grid-template-areas", + "grid-template-columns", + "grid-template-rows", + "gridArea", + "gridAutoColumns", + "gridAutoFlow", + "gridAutoRows", + "gridColumn", + "gridColumnEnd", + "gridColumnGap", + "gridColumnStart", + "gridGap", + "gridRow", + "gridRowEnd", + "gridRowGap", + "gridRowStart", + "gridTemplate", + "gridTemplateAreas", + "gridTemplateColumns", + "gridTemplateRows", + "gripSpace", + "group", + "groupCollapsed", + "groupEnd", + "groupId", + "grow", + "hadRecentInput", + "hand", + "handedness", + "hangingBaseline", + "hangingPunctuation", + "hapticActuators", + "hardwareConcurrency", + "has", + "hasAttribute", + "hasAttributeNS", + "hasAttributes", + "hasBeenActive", + "hasChildNodes", + "hasComposition", + "hasEnrolledInstrument", + "hasExtension", + "hasExternalDisplay", + "hasFeature", + "hasFocus", + "hasInstance", + "hasLayout", + "hasListener", + "hasListeners", + "hasOrientation", + "hasOwnProperty", + "hasPointerCapture", + "hasPosition", + "hasReading", + "hasStorageAccess", + "hash", + "head", + "headers", + "heading", + "height", + "hidden", + "hide", + "hideFocus", + "high", + "highWaterMark", + "hint", + "history", + "honorificPrefix", + "honorificSuffix", + "horizontalOverflow", + "host", + "hostCandidate", + "hostname", + "hour", + "hour12", + "hourCycle", + "href", + "hrefTranslate", + "hreflang", + "hspace", + "html5TagCheckInerface", + "htmlFor", + "htmlText", + "httpEquiv", + "httpRequestStatusCode", + "hwTimestamp", + "hyphens", + "hypot", + "iccId", + "iceConnectionState", + "iceGatheringState", + "iceTransport", + "icon", + "iconURL", + "id", + "identifier", + "identity", + "ideographicBaseline", + "idpLoginUrl", + "ignoreBOM", + "ignoreCase", + "ignoreDepthValues", + "ignoreMutedMedia", + "ignorePunctuation", + "image-orientation", + "image-rendering", + "imageHeight", + "imageOrientation", + "imageRendering", + "imageSizes", + "imageSmoothingEnabled", + "imageSmoothingQuality", + "imageSrcset", + "imageWidth", + "images", + "ime-mode", + "imeMode", + "implementation", + "import", + "importKey", + "importNode", + "importStylesheet", + "imports", + "impp", + "imul", + "in", + "in1", + "in2", + "inBandMetadataTrackDispatchType", + "inRange", + "includes", + "incremental", + "indeterminate", + "index", + "indexNames", + "indexOf", + "indexedDB", + "indicate", + "inertiaDestinationX", + "inertiaDestinationY", + "info", + "init", + "initAnimationEvent", + "initBeforeLoadEvent", + "initClipboardEvent", + "initCloseEvent", + "initCommandEvent", + "initCompositionEvent", + "initCustomEvent", + "initData", + "initDataType", + "initDeviceMotionEvent", + "initDeviceOrientationEvent", + "initDragEvent", + "initErrorEvent", + "initEvent", + "initFocusEvent", + "initGestureEvent", + "initHashChangeEvent", + "initKeyEvent", + "initKeyboardEvent", + "initMSManipulationEvent", + "initMessageEvent", + "initMouseEvent", + "initMouseScrollEvent", + "initMouseWheelEvent", + "initMutationEvent", + "initNSMouseEvent", + "initOverflowEvent", + "initPageEvent", + "initPageTransitionEvent", + "initPointerEvent", + "initPopStateEvent", + "initProgressEvent", + "initScrollAreaEvent", + "initSimpleGestureEvent", + "initStorageEvent", + "initTextEvent", + "initTimeEvent", + "initTouchEvent", + "initTransitionEvent", + "initUIEvent", + "initWebKitAnimationEvent", + "initWebKitTransitionEvent", + "initWebKitWheelEvent", + "initWheelEvent", + "initialTime", + "initialize", + "initiatorType", + "inline-size", + "inlineSize", + "inlineVerticalFieldOfView", + "inner", + "innerHTML", + "innerHeight", + "innerText", + "innerWidth", + "input", + "inputBuffer", + "inputEncoding", + "inputMethod", + "inputMode", + "inputSource", + "inputSources", + "inputType", + "inputs", + "insertAdjacentElement", + "insertAdjacentHTML", + "insertAdjacentText", + "insertBefore", + "insertCell", + "insertDTMF", + "insertData", + "insertId", + "insertItemBefore", + "insertNode", + "insertRow", + "insertRule", + "inset", + "inset-block", + "inset-block-end", + "inset-block-start", + "inset-inline", + "inset-inline-end", + "inset-inline-start", + "insetBlock", + "insetBlockEnd", + "insetBlockStart", + "insetInline", + "insetInlineEnd", + "insetInlineStart", + "install", + "installChrome", + "installPackage", + "installState", + "installing", + "instanceRoot", + "instantiate", + "instantiateStreaming", + "instruments", + "integrity", + "interactionMode", + "intercept", + "interfaceClass", + "interfaceName", + "interfaceNumber", + "interfaceProtocol", + "interfaceSubclass", + "interfaces", + "interimResults", + "internalSubset", + "interpretation", + "intersectionRatio", + "intersectionRect", + "intersectsNode", + "interval", + "invalidIteratorState", + "invalidateFramebuffer", + "invalidateSubFramebuffer", + "inverse", + "invertSelf", + "is", + "is2D", + "isActive", + "isAlternate", + "isArray", + "isBingCurrentSearchDefault", + "isBuffer", + "isCandidateWindowVisible", + "isChar", + "isCollapsed", + "isComposing", + "isConcatSpreadable", + "isConnected", + "isContentEditable", + "isContentHandlerRegistered", + "isContextLost", + "isDefaultNamespace", + "isDirectory", + "isDisabled", + "isEnabled", + "isEqual", + "isEqualNode", + "isExtensible", + "isExternalCTAP2SecurityKeySupported", + "isFile", + "isFinite", + "isFramebuffer", + "isFrozen", + "isGenerator", + "isHTML", + "isHistoryNavigation", + "isId", + "isIdentity", + "isInjected", + "isInstalled", + "isInteger", + "isIntersecting", + "isLockFree", + "isMap", + "isMultiLine", + "isNaN", + "isOpen", + "isPointInFill", + "isPointInPath", + "isPointInRange", + "isPointInStroke", + "isPrefAlternate", + "isPresenting", + "isPrimary", + "isProgram", + "isPropertyImplicit", + "isProtocolHandlerRegistered", + "isPrototypeOf", + "isQuery", + "isRenderbuffer", + "isSafeInteger", + "isSameNode", + "isSampler", + "isScript", + "isScriptURL", + "isSealed", + "isSecureContext", + "isSessionSupported", + "isShader", + "isSupported", + "isSync", + "isTextEdit", + "isTexture", + "isTransformFeedback", + "isTrusted", + "isTypeSupported", + "isTypeSupportedWithFeatures", + "isUserVerifyingPlatformAuthenticatorAvailable", + "isVertexArray", + "isView", + "isVisible", + "isochronousTransferIn", + "isochronousTransferOut", + "isolation", + "italics", + "item", + "itemId", + "itemProp", + "itemRef", + "itemScope", + "itemType", + "itemValue", + "items", + "iterateNext", + "iterator", + "javaEnabled", + "jobTitle", + "join", + "jsHeapSizeLimit", + "json", + "justify-content", + "justify-items", + "justify-self", + "justifyContent", + "justifyItems", + "justifySelf", + "k1", + "k2", + "k3", + "k4", + "kHz", + "keepalive", + "kernelMatrix", + "kernelUnitLengthX", + "kernelUnitLengthY", + "kerning", + "key", + "keyCode", + "keyFor", + "keyIdentifier", + "keyLightEnabled", + "keyLocation", + "keyPath", + "keyStatuses", + "keySystem", + "keyText", + "keyUsage", + "keyboard", + "keys", + "keytype", + "kind", + "knee", + "label", + "labels", + "lang", + "language", + "languages", + "largeArcFlag", + "lastActivePanel", + "lastChild", + "lastElementChild", + "lastEventId", + "lastIndex", + "lastIndexOf", + "lastInputTime", + "lastMatch", + "lastMessageSubject", + "lastMessageType", + "lastModified", + "lastModifiedDate", + "lastPage", + "lastParen", + "lastState", + "lastStyleSheetSet", + "latitude", + "layerX", + "layerY", + "layoutFlow", + "layoutGrid", + "layoutGridChar", + "layoutGridLine", + "layoutGridMode", + "layoutGridType", + "lbound", + "left", + "leftContext", + "leftDegrees", + "leftMargin", + "leftProjectionMatrix", + "leftViewMatrix", + "length", + "lengthAdjust", + "lengthComputable", + "letter-spacing", + "letterSpacing", + "level", + "lighting-color", + "lightingColor", + "limitingConeAngle", + "line", + "line-break", + "line-height", + "lineAlign", + "lineBreak", + "lineCap", + "lineDashOffset", + "lineHeight", + "lineJoin", + "lineNumber", + "lineTo", + "lineWidth", + "linearAcceleration", + "linearRampToValueAtTime", + "linearVelocity", + "lineno", + "lines", + "link", + "linkColor", + "linkProgram", + "links", + "list", + "list-style", + "list-style-image", + "list-style-position", + "list-style-type", + "listStyle", + "listStyleImage", + "listStylePosition", + "listStyleType", + "listener", + "load", + "loadEventEnd", + "loadEventStart", + "loadTime", + "loadTimes", + "loaded", + "loading", + "localDescription", + "localName", + "localService", + "localStorage", + "locale", + "localeCompare", + "location", + "locationbar", + "lock", + "locked", + "lockedFile", + "locks", + "log", + "log10", + "log1p", + "log2", + "logicalXDPI", + "logicalYDPI", + "longDesc", + "longitude", + "lookupNamespaceURI", + "lookupPrefix", + "loop", + "loopEnd", + "loopStart", + "looping", + "low", + "lower", + "lowerBound", + "lowerOpen", + "lowsrc", + "m11", + "m12", + "m13", + "m14", + "m21", + "m22", + "m23", + "m24", + "m31", + "m32", + "m33", + "m34", + "m41", + "m42", + "m43", + "m44", + "makeXRCompatible", + "manifest", + "manufacturer", + "manufacturerName", + "map", + "mapping", + "margin", + "margin-block", + "margin-block-end", + "margin-block-start", + "margin-bottom", + "margin-inline", + "margin-inline-end", + "margin-inline-start", + "margin-left", + "margin-right", + "margin-top", + "marginBlock", + "marginBlockEnd", + "marginBlockStart", + "marginBottom", + "marginHeight", + "marginInline", + "marginInlineEnd", + "marginInlineStart", + "marginLeft", + "marginRight", + "marginTop", + "marginWidth", + "mark", + "markTimeline", + "marker", + "marker-end", + "marker-mid", + "marker-offset", + "marker-start", + "markerEnd", + "markerHeight", + "markerMid", + "markerOffset", + "markerStart", + "markerUnits", + "markerWidth", + "marks", + "mask", + "mask-clip", + "mask-composite", + "mask-image", + "mask-mode", + "mask-origin", + "mask-position", + "mask-position-x", + "mask-position-y", + "mask-repeat", + "mask-size", + "mask-type", + "maskClip", + "maskComposite", + "maskContentUnits", + "maskImage", + "maskMode", + "maskOrigin", + "maskPosition", + "maskPositionX", + "maskPositionY", + "maskRepeat", + "maskSize", + "maskType", + "maskUnits", + "match", + "matchAll", + "matchMedia", + "matchMedium", + "matches", + "matrix", + "matrixTransform", + "max", + "max-block-size", + "max-height", + "max-inline-size", + "max-width", + "maxActions", + "maxAlternatives", + "maxBlockSize", + "maxChannelCount", + "maxChannels", + "maxConnectionsPerServer", + "maxDecibels", + "maxDistance", + "maxHeight", + "maxInlineSize", + "maxLayers", + "maxLength", + "maxMessageSize", + "maxPacketLifeTime", + "maxRetransmits", + "maxTouchPoints", + "maxValue", + "maxWidth", + "maxZoom", + "maximize", + "maximumFractionDigits", + "measure", + "measureText", + "media", + "mediaCapabilities", + "mediaDevices", + "mediaElement", + "mediaGroup", + "mediaKeys", + "mediaSession", + "mediaStream", + "mediaText", + "meetOrSlice", + "memory", + "menubar", + "mergeAttributes", + "message", + "messageClass", + "messageHandlers", + "messageType", + "metaKey", + "metadata", + "method", + "methodDetails", + "methodName", + "mid", + "mimeType", + "mimeTypes", + "min", + "min-block-size", + "min-height", + "min-inline-size", + "min-width", + "minBlockSize", + "minDecibels", + "minHeight", + "minInlineSize", + "minLength", + "minValue", + "minWidth", + "minZoom", + "minimize", + "minimumFractionDigits", + "minimumIntegerDigits", + "minute", + "miterLimit", + "mix-blend-mode", + "mixBlendMode", + "mm", + "mode", + "modify", + "month", + "motion", + "motionOffset", + "motionPath", + "motionRotation", + "mount", + "move", + "moveBy", + "moveEnd", + "moveFirst", + "moveFocusDown", + "moveFocusLeft", + "moveFocusRight", + "moveFocusUp", + "moveNext", + "moveRow", + "moveStart", + "moveTo", + "moveToBookmark", + "moveToElementText", + "moveToPoint", + "movementX", + "movementY", + "mozAdd", + "mozAnimationStartTime", + "mozAnon", + "mozApps", + "mozAudioCaptured", + "mozAudioChannelType", + "mozAutoplayEnabled", + "mozCancelAnimationFrame", + "mozCancelFullScreen", + "mozCancelRequestAnimationFrame", + "mozCaptureStream", + "mozCaptureStreamUntilEnded", + "mozClearDataAt", + "mozContact", + "mozContacts", + "mozCreateFileHandle", + "mozCurrentTransform", + "mozCurrentTransformInverse", + "mozCursor", + "mozDash", + "mozDashOffset", + "mozDecodedFrames", + "mozExitPointerLock", + "mozFillRule", + "mozFragmentEnd", + "mozFrameDelay", + "mozFullScreen", + "mozFullScreenElement", + "mozFullScreenEnabled", + "mozGetAll", + "mozGetAllKeys", + "mozGetAsFile", + "mozGetDataAt", + "mozGetMetadata", + "mozGetUserMedia", + "mozHasAudio", + "mozHasItem", + "mozHidden", + "mozImageSmoothingEnabled", + "mozIndexedDB", + "mozInnerScreenX", + "mozInnerScreenY", + "mozInputSource", + "mozIsTextField", + "mozItem", + "mozItemCount", + "mozItems", + "mozLength", + "mozLockOrientation", + "mozMatchesSelector", + "mozMovementX", + "mozMovementY", + "mozOpaque", + "mozOrientation", + "mozPaintCount", + "mozPaintedFrames", + "mozParsedFrames", + "mozPay", + "mozPointerLockElement", + "mozPresentedFrames", + "mozPreservesPitch", + "mozPressure", + "mozPrintCallback", + "mozRTCIceCandidate", + "mozRTCPeerConnection", + "mozRTCSessionDescription", + "mozRemove", + "mozRequestAnimationFrame", + "mozRequestFullScreen", + "mozRequestPointerLock", + "mozSetDataAt", + "mozSetImageElement", + "mozSourceNode", + "mozSrcObject", + "mozSystem", + "mozTCPSocket", + "mozTextStyle", + "mozTypesAt", + "mozUnlockOrientation", + "mozUserCancelled", + "mozVisibilityState", + "ms", + "msAnimation", + "msAnimationDelay", + "msAnimationDirection", + "msAnimationDuration", + "msAnimationFillMode", + "msAnimationIterationCount", + "msAnimationName", + "msAnimationPlayState", + "msAnimationStartTime", + "msAnimationTimingFunction", + "msBackfaceVisibility", + "msBlockProgression", + "msCSSOMElementFloatMetrics", + "msCaching", + "msCachingEnabled", + "msCancelRequestAnimationFrame", + "msCapsLockWarningOff", + "msClearImmediate", + "msClose", + "msContentZoomChaining", + "msContentZoomFactor", + "msContentZoomLimit", + "msContentZoomLimitMax", + "msContentZoomLimitMin", + "msContentZoomSnap", + "msContentZoomSnapPoints", + "msContentZoomSnapType", + "msContentZooming", + "msConvertURL", + "msCrypto", + "msDoNotTrack", + "msElementsFromPoint", + "msElementsFromRect", + "msExitFullscreen", + "msExtendedCode", + "msFillRule", + "msFirstPaint", + "msFlex", + "msFlexAlign", + "msFlexDirection", + "msFlexFlow", + "msFlexItemAlign", + "msFlexLinePack", + "msFlexNegative", + "msFlexOrder", + "msFlexPack", + "msFlexPositive", + "msFlexPreferredSize", + "msFlexWrap", + "msFlowFrom", + "msFlowInto", + "msFontFeatureSettings", + "msFullscreenElement", + "msFullscreenEnabled", + "msGetInputContext", + "msGetRegionContent", + "msGetUntransformedBounds", + "msGraphicsTrustStatus", + "msGridColumn", + "msGridColumnAlign", + "msGridColumnSpan", + "msGridColumns", + "msGridRow", + "msGridRowAlign", + "msGridRowSpan", + "msGridRows", + "msHidden", + "msHighContrastAdjust", + "msHyphenateLimitChars", + "msHyphenateLimitLines", + "msHyphenateLimitZone", + "msHyphens", + "msImageSmoothingEnabled", + "msImeAlign", + "msIndexedDB", + "msInterpolationMode", + "msIsStaticHTML", + "msKeySystem", + "msKeys", + "msLaunchUri", + "msLockOrientation", + "msManipulationViewsEnabled", + "msMatchMedia", + "msMatchesSelector", + "msMaxTouchPoints", + "msOrientation", + "msOverflowStyle", + "msPerspective", + "msPerspectiveOrigin", + "msPlayToDisabled", + "msPlayToPreferredSourceUri", + "msPlayToPrimary", + "msPointerEnabled", + "msRegionOverflow", + "msReleasePointerCapture", + "msRequestAnimationFrame", + "msRequestFullscreen", + "msSaveBlob", + "msSaveOrOpenBlob", + "msScrollChaining", + "msScrollLimit", + "msScrollLimitXMax", + "msScrollLimitXMin", + "msScrollLimitYMax", + "msScrollLimitYMin", + "msScrollRails", + "msScrollSnapPointsX", + "msScrollSnapPointsY", + "msScrollSnapType", + "msScrollSnapX", + "msScrollSnapY", + "msScrollTranslation", + "msSetImmediate", + "msSetMediaKeys", + "msSetPointerCapture", + "msTextCombineHorizontal", + "msTextSizeAdjust", + "msToBlob", + "msTouchAction", + "msTouchSelect", + "msTraceAsyncCallbackCompleted", + "msTraceAsyncCallbackStarting", + "msTraceAsyncOperationCompleted", + "msTraceAsyncOperationStarting", + "msTransform", + "msTransformOrigin", + "msTransformStyle", + "msTransition", + "msTransitionDelay", + "msTransitionDuration", + "msTransitionProperty", + "msTransitionTimingFunction", + "msUnlockOrientation", + "msUpdateAsyncCallbackRelation", + "msUserSelect", + "msVisibilityState", + "msWrapFlow", + "msWrapMargin", + "msWrapThrough", + "msWriteProfilerMark", + "msZoom", + "msZoomTo", + "mt", + "mul", + "multiEntry", + "multiSelectionObj", + "multiline", + "multiple", + "multiply", + "multiplySelf", + "mutableFile", + "muted", + "n", + "name", + "nameProp", + "namedItem", + "namedRecordset", + "names", + "namespaceURI", + "namespaces", + "naturalHeight", + "naturalWidth", + "navigate", + "navigation", + "navigationMode", + "navigationPreload", + "navigationStart", + "navigationType", + "navigator", + "near", + "nearestViewportElement", + "negative", + "negotiated", + "netscape", + "networkState", + "newScale", + "newTranslate", + "newURL", + "newValue", + "newValueSpecifiedUnits", + "newVersion", + "newhome", + "next", + "nextElementSibling", + "nextHopProtocol", + "nextNode", + "nextPage", + "nextSibling", + "nickname", + "noHref", + "noModule", + "noResize", + "noShade", + "noValidate", + "noWrap", + "node", + "nodeName", + "nodeType", + "nodeValue", + "nonce", + "normalize", + "normalizedPathSegList", + "notationName", + "notations", + "note", + "noteGrainOn", + "noteOff", + "noteOn", + "notify", + "now", + "npnNegotiatedProtocol", + "numOctaves", + "number", + "numberOfChannels", + "numberOfInputs", + "numberOfItems", + "numberOfOutputs", + "numberValue", + "numberingSystem", + "numeric", + "oMatchesSelector", + "object", + "object-fit", + "object-position", + "objectFit", + "objectPosition", + "objectStore", + "objectStoreNames", + "observe", + "observedAttributes", + "of", + "offscreenBuffering", + "offset", + "offset-anchor", + "offset-block-end", + "offset-block-start", + "offset-distance", + "offset-inline-end", + "offset-inline-start", + "offset-path", + "offset-rotate", + "offsetAnchor", + "offsetBlockEnd", + "offsetBlockStart", + "offsetDistance", + "offsetHeight", + "offsetInlineEnd", + "offsetInlineStart", + "offsetLeft", + "offsetNode", + "offsetParent", + "offsetPath", + "offsetRotate", + "offsetTop", + "offsetWidth", + "offsetX", + "offsetY", + "ok", + "oldURL", + "oldValue", + "oldVersion", + "olderShadowRoot", + "onDownloadProgress", + "onInstallStageChanged", + "onLine", + "onabort", + "onabsolutedeviceorientation", + "onactivate", + "onactive", + "onaddsourcebuffer", + "onaddstream", + "onaddtrack", + "onafterprint", + "onafterscriptexecute", + "onafterupdate", + "onanimationcancel", + "onanimationend", + "onanimationiteration", + "onanimationstart", + "onappinstalled", + "onaudioend", + "onaudioprocess", + "onaudiostart", + "onautocomplete", + "onautocompleteerror", + "onauxclick", + "onbeforeactivate", + "onbeforecopy", + "onbeforecut", + "onbeforedeactivate", + "onbeforeeditfocus", + "onbeforeinput", + "onbeforeinstallprompt", + "onbeforeload", + "onbeforepaste", + "onbeforeprint", + "onbeforescriptexecute", + "onbeforeunload", + "onbeforeupdate", + "onbeforexrselect", + "onbegin", + "onblocked", + "onblur", + "onbounce", + "onboundary", + "onbufferedamountlow", + "oncached", + "oncancel", + "oncandidatewindowhide", + "oncandidatewindowshow", + "oncandidatewindowupdate", + "oncanplay", + "oncanplaythrough", + "once", + "oncellchange", + "onchange", + "oncharacteristicvaluechanged", + "onchargingchange", + "onchargingtimechange", + "onchecking", + "onclick", + "onclose", + "onclosing", + "oncompassneedscalibration", + "oncomplete", + "onconnect", + "onconnecting", + "onconnectionavailable", + "onconnectionstatechange", + "oncontactchange", + "oncontextmenu", + "oncontrollerchange", + "oncontrolselect", + "oncopy", + "oncuechange", + "oncut", + "ondataavailable", + "ondatachannel", + "ondatasetchanged", + "ondatasetcomplete", + "ondblclick", + "ondeactivate", + "ondevicechange", + "ondevicelight", + "ondevicemotion", + "ondeviceorientation", + "ondeviceorientationabsolute", + "ondeviceproximity", + "ondischargingtimechange", + "ondisconnect", + "ondisplay", + "ondownloading", + "ondrag", + "ondragend", + "ondragenter", + "ondragexit", + "ondragleave", + "ondragover", + "ondragstart", + "ondrop", + "ondurationchange", + "onemptied", + "onencrypted", + "onend", + "onended", + "onenter", + "onenterpictureinpicture", + "onerror", + "onerrorupdate", + "onexit", + "onfilterchange", + "onfinish", + "onfocus", + "onfocusin", + "onfocusout", + "onformdata", + "onfreeze", + "onfullscreenchange", + "onfullscreenerror", + "ongatheringstatechange", + "ongattserverdisconnected", + "ongesturechange", + "ongestureend", + "ongesturestart", + "ongotpointercapture", + "onhashchange", + "onhelp", + "onicecandidate", + "onicecandidateerror", + "oniceconnectionstatechange", + "onicegatheringstatechange", + "oninactive", + "oninput", + "oninputsourceschange", + "oninvalid", + "onkeydown", + "onkeypress", + "onkeystatuseschange", + "onkeyup", + "onlanguagechange", + "onlayoutcomplete", + "onleavepictureinpicture", + "onlevelchange", + "onload", + "onloadT", + "onloadeddata", + "onloadedmetadata", + "onloadend", + "onloading", + "onloadingdone", + "onloadingerror", + "onloadstart", + "onlosecapture", + "onlostpointercapture", + "only", + "onmark", + "onmessage", + "onmessageerror", + "onmidimessage", + "onmousedown", + "onmouseenter", + "onmouseleave", + "onmousemove", + "onmouseout", + "onmouseover", + "onmouseup", + "onmousewheel", + "onmove", + "onmoveend", + "onmovestart", + "onmozfullscreenchange", + "onmozfullscreenerror", + "onmozorientationchange", + "onmozpointerlockchange", + "onmozpointerlockerror", + "onmscontentzoom", + "onmsfullscreenchange", + "onmsfullscreenerror", + "onmsgesturechange", + "onmsgesturedoubletap", + "onmsgestureend", + "onmsgesturehold", + "onmsgesturestart", + "onmsgesturetap", + "onmsgotpointercapture", + "onmsinertiastart", + "onmslostpointercapture", + "onmsmanipulationstatechanged", + "onmsneedkey", + "onmsorientationchange", + "onmspointercancel", + "onmspointerdown", + "onmspointerenter", + "onmspointerhover", + "onmspointerleave", + "onmspointermove", + "onmspointerout", + "onmspointerover", + "onmspointerup", + "onmssitemodejumplistitemremoved", + "onmsthumbnailclick", + "onmute", + "onnegotiationneeded", + "onnomatch", + "onnoupdate", + "onobsolete", + "onoffline", + "ononline", + "onopen", + "onorientationchange", + "onoverconstrained", + "onpage", + "onpagechange", + "onpagehide", + "onpageshow", + "onpaste", + "onpause", + "onpayerdetailchange", + "onpaymentmethodchange", + "onplay", + "onplaying", + "onpluginstreamstart", + "onpointercancel", + "onpointerdown", + "onpointerenter", + "onpointerleave", + "onpointerlockchange", + "onpointerlockerror", + "onpointermove", + "onpointerout", + "onpointerover", + "onpointerrawupdate", + "onpointerup", + "onpopstate", + "onprocessorerror", + "onprogress", + "onpropertychange", + "onratechange", + "onreading", + "onreadystatechange", + "onrejectionhandled", + "onrelease", + "onremove", + "onremovesourcebuffer", + "onremovestream", + "onremovetrack", + "onrepeat", + "onreset", + "onresize", + "onresizeend", + "onresizestart", + "onresourcetimingbufferfull", + "onresult", + "onresume", + "onrowenter", + "onrowexit", + "onrowsdelete", + "onrowsinserted", + "onscroll", + "onsearch", + "onsecuritypolicyviolation", + "onseeked", + "onseeking", + "onselect", + "onselectedcandidatepairchange", + "onselectend", + "onselectionchange", + "onselectstart", + "onshippingaddresschange", + "onshippingoptionchange", + "onshow", + "onsignalingstatechange", + "onsoundend", + "onsoundstart", + "onsourceclose", + "onsourceclosed", + "onsourceended", + "onsourceopen", + "onspeechend", + "onspeechstart", + "onsqueeze", + "onsqueezeend", + "onsqueezestart", + "onstalled", + "onstart", + "onstatechange", + "onstop", + "onstorage", + "onstoragecommit", + "onsubmit", + "onsuccess", + "onsuspend", + "onterminate", + "ontextinput", + "ontimeout", + "ontimeupdate", + "ontoggle", + "ontonechange", + "ontouchcancel", + "ontouchend", + "ontouchmove", + "ontouchstart", + "ontrack", + "ontransitioncancel", + "ontransitionend", + "ontransitionrun", + "ontransitionstart", + "onunhandledrejection", + "onunload", + "onunmute", + "onupdate", + "onupdateend", + "onupdatefound", + "onupdateready", + "onupdatestart", + "onupgradeneeded", + "onuserproximity", + "onversionchange", + "onvisibilitychange", + "onvoiceschanged", + "onvolumechange", + "onvrdisplayactivate", + "onvrdisplayconnect", + "onvrdisplaydeactivate", + "onvrdisplaydisconnect", + "onvrdisplaypresentchange", + "onwaiting", + "onwaitingforkey", + "onwarning", + "onwebkitanimationend", + "onwebkitanimationiteration", + "onwebkitanimationstart", + "onwebkitcurrentplaybacktargetiswirelesschanged", + "onwebkitfullscreenchange", + "onwebkitfullscreenerror", + "onwebkitkeyadded", + "onwebkitkeyerror", + "onwebkitkeymessage", + "onwebkitmouseforcechanged", + "onwebkitmouseforcedown", + "onwebkitmouseforceup", + "onwebkitmouseforcewillbegin", + "onwebkitneedkey", + "onwebkitorientationchange", + "onwebkitplaybacktargetavailabilitychanged", + "onwebkitpointerlockchange", + "onwebkitpointerlockerror", + "onwebkitresourcetimingbufferfull", + "onwebkittransitionend", + "onwheel", + "onzoom", + "opacity", + "open", + "openCursor", + "openDatabase", + "openKeyCursor", + "opened", + "opener", + "opera", + "operationType", + "operator", + "opr", + "opsProfile", + "optimum", + "options", + "or", + "order", + "orderX", + "orderY", + "ordered", + "org", + "organization", + "orient", + "orientAngle", + "orientType", + "orientation", + "orientationX", + "orientationY", + "orientationZ", + "origin", + "originalPolicy", + "originalTarget", + "orphans", + "oscpu", + "outcome", + "outerHTML", + "outerHeight", + "outerText", + "outerWidth", + "outline", + "outline-color", + "outline-offset", + "outline-style", + "outline-width", + "outlineColor", + "outlineOffset", + "outlineStyle", + "outlineWidth", + "outputBuffer", + "outputLatency", + "outputs", + "overflow", + "overflow-anchor", + "overflow-block", + "overflow-inline", + "overflow-wrap", + "overflow-x", + "overflow-y", + "overflowAnchor", + "overflowBlock", + "overflowInline", + "overflowWrap", + "overflowX", + "overflowY", + "overrideMimeType", + "oversample", + "overscroll-behavior", + "overscroll-behavior-block", + "overscroll-behavior-inline", + "overscroll-behavior-x", + "overscroll-behavior-y", + "overscrollBehavior", + "overscrollBehaviorBlock", + "overscrollBehaviorInline", + "overscrollBehaviorX", + "overscrollBehaviorY", + "ownKeys", + "ownerDocument", + "ownerElement", + "ownerNode", + "ownerRule", + "ownerSVGElement", + "owningElement", + "p1", + "p2", + "p3", + "p4", + "packetSize", + "packets", + "pad", + "padEnd", + "padStart", + "padding", + "padding-block", + "padding-block-end", + "padding-block-start", + "padding-bottom", + "padding-inline", + "padding-inline-end", + "padding-inline-start", + "padding-left", + "padding-right", + "padding-top", + "paddingBlock", + "paddingBlockEnd", + "paddingBlockStart", + "paddingBottom", + "paddingInline", + "paddingInlineEnd", + "paddingInlineStart", + "paddingLeft", + "paddingRight", + "paddingTop", + "page", + "page-break-after", + "page-break-before", + "page-break-inside", + "pageBreakAfter", + "pageBreakBefore", + "pageBreakInside", + "pageCount", + "pageLeft", + "pageT", + "pageTop", + "pageX", + "pageXOffset", + "pageY", + "pageYOffset", + "pages", + "paint-order", + "paintOrder", + "paintRequests", + "paintType", + "paintWorklet", + "palette", + "pan", + "panningModel", + "parameters", + "parent", + "parentElement", + "parentNode", + "parentRule", + "parentStyleSheet", + "parentTextEdit", + "parentWindow", + "parse", + "parseAll", + "parseFloat", + "parseFromString", + "parseInt", + "part", + "participants", + "passive", + "password", + "pasteHTML", + "path", + "pathLength", + "pathSegList", + "pathSegType", + "pathSegTypeAsLetter", + "pathname", + "pattern", + "patternContentUnits", + "patternMismatch", + "patternTransform", + "patternUnits", + "pause", + "pauseAnimations", + "pauseOnExit", + "pauseTransformFeedback", + "paused", + "payerEmail", + "payerName", + "payerPhone", + "paymentManager", + "pc", + "peerIdentity", + "pending", + "pendingLocalDescription", + "pendingRemoteDescription", + "percent", + "performance", + "periodicSync", + "permission", + "permissionState", + "permissions", + "persist", + "persisted", + "personalbar", + "perspective", + "perspective-origin", + "perspectiveOrigin", + "perspectiveOriginX", + "perspectiveOriginY", + "phone", + "phoneticFamilyName", + "phoneticGivenName", + "photo", + "pictureInPictureElement", + "pictureInPictureEnabled", + "pictureInPictureWindow", + "ping", + "pipeThrough", + "pipeTo", + "pitch", + "pixelBottom", + "pixelDepth", + "pixelHeight", + "pixelLeft", + "pixelRight", + "pixelStorei", + "pixelTop", + "pixelUnitToMillimeterX", + "pixelUnitToMillimeterY", + "pixelWidth", + "place-content", + "place-items", + "place-self", + "placeContent", + "placeItems", + "placeSelf", + "placeholder", + "platform", + "platforms", + "play", + "playEffect", + "playState", + "playbackRate", + "playbackState", + "playbackTime", + "played", + "playoutDelayHint", + "playsInline", + "plugins", + "pluginspage", + "pname", + "pointer-events", + "pointerBeforeReferenceNode", + "pointerEnabled", + "pointerEvents", + "pointerId", + "pointerLockElement", + "pointerType", + "points", + "pointsAtX", + "pointsAtY", + "pointsAtZ", + "polygonOffset", + "pop", + "populateMatrix", + "popupWindowFeatures", + "popupWindowName", + "popupWindowURI", + "port", + "port1", + "port2", + "ports", + "posBottom", + "posHeight", + "posLeft", + "posRight", + "posTop", + "posWidth", + "pose", + "position", + "positionAlign", + "positionX", + "positionY", + "positionZ", + "postError", + "postMessage", + "postalCode", + "poster", + "pow", + "powerEfficient", + "powerOff", + "preMultiplySelf", + "precision", + "preferredStyleSheetSet", + "preferredStylesheetSet", + "prefix", + "preload", + "prepend", + "presentation", + "preserveAlpha", + "preserveAspectRatio", + "preserveAspectRatioString", + "pressed", + "pressure", + "prevValue", + "preventDefault", + "preventExtensions", + "preventSilentAccess", + "previousElementSibling", + "previousNode", + "previousPage", + "previousRect", + "previousScale", + "previousSibling", + "previousTranslate", + "primaryKey", + "primitiveType", + "primitiveUnits", + "principals", + "print", + "priority", + "privateKey", + "probablySupportsContext", + "process", + "processIceMessage", + "processingEnd", + "processingStart", + "product", + "productId", + "productName", + "productSub", + "profile", + "profileEnd", + "profiles", + "projectionMatrix", + "promise", + "prompt", + "properties", + "propertyIsEnumerable", + "propertyName", + "protocol", + "protocolLong", + "prototype", + "provider", + "pseudoClass", + "pseudoElement", + "pt", + "publicId", + "publicKey", + "published", + "pulse", + "push", + "pushManager", + "pushNotification", + "pushState", + "put", + "putImageData", + "px", + "quadraticCurveTo", + "qualifier", + "quaternion", + "query", + "queryCommandEnabled", + "queryCommandIndeterm", + "queryCommandState", + "queryCommandSupported", + "queryCommandText", + "queryCommandValue", + "querySelector", + "querySelectorAll", + "queryUsageAndQuota", + "queueMicrotask", + "quote", + "quotes", + "r", + "r1", + "r2", + "race", + "rad", + "radiogroup", + "radiusX", + "radiusY", + "random", + "range", + "rangeCount", + "rangeMax", + "rangeMin", + "rangeOffset", + "rangeOverflow", + "rangeParent", + "rangeUnderflow", + "rate", + "ratio", + "raw", + "rawId", + "read", + "readAsArrayBuffer", + "readAsBinaryString", + "readAsBlob", + "readAsDataURL", + "readAsText", + "readBuffer", + "readEntries", + "readOnly", + "readPixels", + "readReportRequested", + "readText", + "readTransaction", + "readValue", + "readable", + "ready", + "readyState", + "reason", + "reboot", + "receivedAlert", + "receivedTime", + "receiver", + "receivers", + "recipient", + "reconnect", + "record", + "recordEnd", + "recordNumber", + "recordsAvailable", + "recordset", + "rect", + "red", + "redEyeReduction", + "redirect", + "redirectCount", + "redirectEnd", + "redirectStart", + "redirected", + "reduce", + "reduceRight", + "reduction", + "refDistance", + "refX", + "refY", + "referenceNode", + "referenceSpace", + "referrer", + "referrerPolicy", + "refresh", + "region", + "regionAnchorX", + "regionAnchorY", + "regionId", + "regions", + "register", + "registerContentHandler", + "registerElement", + "registerProperty", + "registerProtocolHandler", + "reject", + "rel", + "relList", + "relatedAddress", + "relatedNode", + "relatedPort", + "relatedTarget", + "release", + "releaseCapture", + "releaseEvents", + "releaseInterface", + "releaseLock", + "releasePointerCapture", + "releaseShaderCompiler", + "reliable", + "reliableWrite", + "reload", + "rem", + "remainingSpace", + "remote", + "remoteDescription", + "remove", + "removeAllRanges", + "removeAttribute", + "removeAttributeNS", + "removeAttributeNode", + "removeBehavior", + "removeChild", + "removeCue", + "removeEventListener", + "removeFilter", + "removeImport", + "removeItem", + "removeListener", + "removeNamedItem", + "removeNamedItemNS", + "removeNode", + "removeParameter", + "removeProperty", + "removeRange", + "removeRegion", + "removeRule", + "removeRules", + "removeSiteSpecificTrackingException", + "removeSourceBuffer", + "removeStream", + "removeTrack", + "removeVariable", + "removeWakeLockListener", + "removeWebWideTrackingException", + "removed", + "removedNodes", + "renderHeight", + "renderState", + "renderTime", + "renderWidth", + "renderbufferStorage", + "renderbufferStorageMultisample", + "renderedBuffer", + "renderingMode", + "renotify", + "repeat", + "replace", + "replaceAdjacentText", + "replaceAll", + "replaceChild", + "replaceChildren", + "replaceData", + "replaceId", + "replaceItem", + "replaceNode", + "replaceState", + "replaceSync", + "replaceTrack", + "replaceWholeText", + "replaceWith", + "reportValidity", + "request", + "requestAnimationFrame", + "requestAutocomplete", + "requestData", + "requestDevice", + "requestFrame", + "requestFullscreen", + "requestHitTestSource", + "requestHitTestSourceForTransientInput", + "requestId", + "requestIdleCallback", + "requestMIDIAccess", + "requestMediaKeySystemAccess", + "requestPermission", + "requestPictureInPicture", + "requestPointerLock", + "requestPresent", + "requestQuota", + "requestReferenceSpace", + "requestSession", + "requestStart", + "requestStorageAccess", + "requestSubmit", + "requestTime", + "requestVideoFrameCallback", + "requestedLocale", + "requestingWindow", + "requireInteraction", + "required", + "requiredExtensions", + "requiredFeatures", + "reset", + "resetPose", + "resetTransform", + "resize", + "resizeBy", + "resizeTo", + "resolve", + "resolved", + "resolvedOptions", + "resource-history", + "resourcesFramesExpanded", + "response", + "responseBody", + "responseEnd", + "responseReady", + "responseStart", + "responseText", + "responseType", + "responseURL", + "responseXML", + "restartIce", + "restore", + "result", + "resultIndex", + "resultType", + "results", + "resume", + "resumeTransformFeedback", + "retry", + "returnValue", + "rev", + "reverse", + "reversed", + "revocable", + "revokeObjectURL", + "rgbColor", + "right", + "rightContext", + "rightDegrees", + "rightMargin", + "rightProjectionMatrix", + "rightViewMatrix", + "role", + "rolloffFactor", + "root", + "rootBounds", + "rootElement", + "rootMargin", + "rotate", + "rotateAxisAngle", + "rotateAxisAngleSelf", + "rotateFromVector", + "rotateFromVectorSelf", + "rotateSelf", + "rotation", + "rotationAngle", + "rotationRate", + "round", + "row-gap", + "rowGap", + "rowIndex", + "rowSpan", + "rows", + "rowsAffected", + "rtcpTransport", + "rtt", + "ruby-align", + "ruby-position", + "rubyAlign", + "rubyOverhang", + "rubyPosition", + "rules", + "runningState", + "runtime", + "runtimeStyle", + "rx", + "ry", + "s", + "safari", + "sample", + "sampleCoverage", + "sampleRate", + "samplerParameterf", + "samplerParameteri", + "sandbox", + "save", + "saveData", + "scale", + "scale3d", + "scale3dSelf", + "scaleNonUniform", + "scaleNonUniformSelf", + "scaleSelf", + "scheme", + "scissor", + "scope", + "scopeName", + "scoped", + "screen", + "screenBrightness", + "screenEnabled", + "screenLeft", + "screenPixelToMillimeterX", + "screenPixelToMillimeterY", + "screenTop", + "screenX", + "screenY", + "script", + "scriptURL", + "scripts", + "scroll", + "scroll-behavior", + "scroll-margin", + "scroll-margin-block", + "scroll-margin-block-end", + "scroll-margin-block-start", + "scroll-margin-bottom", + "scroll-margin-inline", + "scroll-margin-inline-end", + "scroll-margin-inline-start", + "scroll-margin-left", + "scroll-margin-right", + "scroll-margin-top", + "scroll-padding", + "scroll-padding-block", + "scroll-padding-block-end", + "scroll-padding-block-start", + "scroll-padding-bottom", + "scroll-padding-inline", + "scroll-padding-inline-end", + "scroll-padding-inline-start", + "scroll-padding-left", + "scroll-padding-right", + "scroll-padding-top", + "scroll-snap-align", + "scroll-snap-coordinate", + "scroll-snap-destination", + "scroll-snap-points-x", + "scroll-snap-points-y", + "scroll-snap-type", + "scroll-snap-type-x", + "scroll-snap-type-y", + "scrollAmount", + "scrollBehavior", + "scrollBy", + "scrollByLines", + "scrollByPages", + "scrollDelay", + "scrollHeight", + "scrollIntoView", + "scrollIntoViewIfNeeded", + "scrollLeft", + "scrollLeftMax", + "scrollMargin", + "scrollMarginBlock", + "scrollMarginBlockEnd", + "scrollMarginBlockStart", + "scrollMarginBottom", + "scrollMarginInline", + "scrollMarginInlineEnd", + "scrollMarginInlineStart", + "scrollMarginLeft", + "scrollMarginRight", + "scrollMarginTop", + "scrollMaxX", + "scrollMaxY", + "scrollPadding", + "scrollPaddingBlock", + "scrollPaddingBlockEnd", + "scrollPaddingBlockStart", + "scrollPaddingBottom", + "scrollPaddingInline", + "scrollPaddingInlineEnd", + "scrollPaddingInlineStart", + "scrollPaddingLeft", + "scrollPaddingRight", + "scrollPaddingTop", + "scrollRestoration", + "scrollSnapAlign", + "scrollSnapCoordinate", + "scrollSnapDestination", + "scrollSnapMargin", + "scrollSnapMarginBottom", + "scrollSnapMarginLeft", + "scrollSnapMarginRight", + "scrollSnapMarginTop", + "scrollSnapPointsX", + "scrollSnapPointsY", + "scrollSnapStop", + "scrollSnapType", + "scrollSnapTypeX", + "scrollSnapTypeY", + "scrollTo", + "scrollTop", + "scrollTopMax", + "scrollWidth", + "scrollX", + "scrollY", + "scrollbar-color", + "scrollbar-width", + "scrollbar3dLightColor", + "scrollbarArrowColor", + "scrollbarBaseColor", + "scrollbarColor", + "scrollbarDarkShadowColor", + "scrollbarFaceColor", + "scrollbarHighlightColor", + "scrollbarShadowColor", + "scrollbarTrackColor", + "scrollbarWidth", + "scrollbars", + "scrolling", + "scrollingElement", + "sctp", + "sctpCauseCode", + "sdp", + "sdpLineNumber", + "sdpMLineIndex", + "sdpMid", + "seal", + "search", + "searchBox", + "searchBoxJavaBridge_", + "searchParams", + "second", + "sectionRowIndex", + "secureConnectionStart", + "security", + "seed", + "seekToNextFrame", + "seekable", + "seeking", + "select", + "selectAllChildren", + "selectAlternateInterface", + "selectConfiguration", + "selectNode", + "selectNodeContents", + "selectNodes", + "selectSingleNode", + "selectSubString", + "selected", + "selectedIndex", + "selectedOption", + "selectedOptions", + "selectedStyleSheetSet", + "selectedStylesheetSet", + "selection", + "selectionDirection", + "selectionEnd", + "selectionStart", + "selector", + "selectorText", + "self", + "send", + "sendAsBinary", + "sendBeacon", + "sendMessage", + "sender", + "sensitivity", + "sentAlert", + "sentTimestamp", + "separator", + "serialNumber", + "serializeToString", + "serverTiming", + "service", + "serviceWorker", + "session", + "sessionId", + "sessionStorage", + "set", + "setActionHandler", + "setActive", + "setAlpha", + "setAppBadge", + "setAttribute", + "setAttributeNS", + "setAttributeNode", + "setAttributeNodeNS", + "setBaseAndExtent", + "setBigInt64", + "setBigUint64", + "setBingCurrentSearchDefault", + "setCapture", + "setCodecPreferences", + "setColor", + "setCompositeOperation", + "setConfiguration", + "setCurrentTime", + "setCustomValidity", + "setData", + "setDate", + "setDirection", + "setDragImage", + "setEnd", + "setEndAfter", + "setEndBefore", + "setEndPoint", + "setFillColor", + "setFilterRes", + "setFloat32", + "setFloat64", + "setFloatValue", + "setFormValue", + "setFullYear", + "setHeaderValue", + "setHours", + "setIdentityProvider", + "setImmediate", + "setInt16", + "setInt32", + "setInt8", + "setInterval", + "setItem", + "setKeyframes", + "setLineCap", + "setLineDash", + "setLineJoin", + "setLineWidth", + "setLiveSeekableRange", + "setLocalDescription", + "setMatrix", + "setMatrixValue", + "setMediaKeys", + "setMilliseconds", + "setMinutes", + "setMiterLimit", + "setMonth", + "setNamedItem", + "setNamedItemNS", + "setNonUserCodeExceptions", + "setOrientToAngle", + "setOrientToAuto", + "setOrientation", + "setOverrideHistoryNavigationMode", + "setPaint", + "setParameter", + "setParameters", + "setPeriodicWave", + "setPointerCapture", + "setPosition", + "setPositionState", + "setPreference", + "setProperty", + "setPrototypeOf", + "setRGBColor", + "setRGBColorICCColor", + "setRadius", + "setRangeText", + "setRemoteDescription", + "setRequestHeader", + "setResizable", + "setResourceTimingBufferSize", + "setRotate", + "setScale", + "setSeconds", + "setSelectionRange", + "setServerCertificate", + "setShadow", + "setSinkId", + "setSkewX", + "setSkewY", + "setStart", + "setStartAfter", + "setStartBefore", + "setStdDeviation", + "setStreams", + "setStringValue", + "setStrokeColor", + "setSuggestResult", + "setTargetAtTime", + "setTargetValueAtTime", + "setTime", + "setTimeout", + "setTransform", + "setTranslate", + "setUTCDate", + "setUTCFullYear", + "setUTCHours", + "setUTCMilliseconds", + "setUTCMinutes", + "setUTCMonth", + "setUTCSeconds", + "setUint16", + "setUint32", + "setUint8", + "setUri", + "setValidity", + "setValueAtTime", + "setValueCurveAtTime", + "setVariable", + "setVelocity", + "setVersion", + "setYear", + "settingName", + "settingValue", + "sex", + "shaderSource", + "shadowBlur", + "shadowColor", + "shadowOffsetX", + "shadowOffsetY", + "shadowRoot", + "shape", + "shape-image-threshold", + "shape-margin", + "shape-outside", + "shape-rendering", + "shapeImageThreshold", + "shapeMargin", + "shapeOutside", + "shapeRendering", + "sheet", + "shift", + "shiftKey", + "shiftLeft", + "shippingAddress", + "shippingOption", + "shippingType", + "show", + "showHelp", + "showModal", + "showModalDialog", + "showModelessDialog", + "showNotification", + "sidebar", + "sign", + "signal", + "signalingState", + "signature", + "silent", + "sin", + "singleNodeValue", + "sinh", + "sinkId", + "sittingToStandingTransform", + "size", + "sizeToContent", + "sizeX", + "sizeZ", + "sizes", + "skewX", + "skewXSelf", + "skewY", + "skewYSelf", + "slice", + "slope", + "slot", + "small", + "smil", + "smooth", + "smoothingTimeConstant", + "snapToLines", + "snapshotItem", + "snapshotLength", + "some", + "sort", + "sortingCode", + "source", + "sourceBuffer", + "sourceBuffers", + "sourceCapabilities", + "sourceFile", + "sourceIndex", + "sourceURL", + "sources", + "spacing", + "span", + "speak", + "speakAs", + "speaking", + "species", + "specified", + "specularConstant", + "specularExponent", + "speechSynthesis", + "speed", + "speedOfSound", + "spellcheck", + "splice", + "split", + "splitText", + "spreadMethod", + "sqrt", + "src", + "srcElement", + "srcFilter", + "srcObject", + "srcUrn", + "srcdoc", + "srclang", + "srcset", + "stack", + "stackTraceLimit", + "stacktrace", + "stageParameters", + "standalone", + "standby", + "start", + "startContainer", + "startE", + "startIce", + "startLoadTime", + "startMessages", + "startNotifications", + "startOffset", + "startRendering", + "startSoftwareUpdate", + "startTime", + "startsWith", + "state", + "status", + "statusCode", + "statusMessage", + "statusText", + "statusbar", + "stdDeviationX", + "stdDeviationY", + "stencilFunc", + "stencilFuncSeparate", + "stencilMask", + "stencilMaskSeparate", + "stencilOp", + "stencilOpSeparate", + "step", + "stepDown", + "stepMismatch", + "stepUp", + "sticky", + "stitchTiles", + "stop", + "stop-color", + "stop-opacity", + "stopColor", + "stopImmediatePropagation", + "stopNotifications", + "stopOpacity", + "stopPropagation", + "stopped", + "storage", + "storageArea", + "storageName", + "storageStatus", + "store", + "storeSiteSpecificTrackingException", + "storeWebWideTrackingException", + "stpVersion", + "stream", + "streams", + "strength", + "stretch", + "strike", + "stringValue", + "stringify", + "stroke", + "stroke-dasharray", + "stroke-dashoffset", + "stroke-linecap", + "stroke-linejoin", + "stroke-miterlimit", + "stroke-opacity", + "stroke-width", + "strokeColor", + "strokeDasharray", + "strokeDashoffset", + "strokeLinecap", + "strokeLinejoin", + "strokeMiterlimit", + "strokeOpacity", + "strokeRect", + "strokeStyle", + "strokeText", + "strokeWidth", + "style", + "styleFloat", + "styleMap", + "styleMedia", + "styleSheet", + "styleSheetSets", + "styleSheets", + "sub", + "subarray", + "subject", + "submit", + "submitFrame", + "submitter", + "subscribe", + "substr", + "substring", + "substringData", + "subtle", + "subtree", + "suffix", + "suffixes", + "summary", + "sup", + "supported", + "supportedContentEncodings", + "supportedEntryTypes", + "supportedLocalesOf", + "supports", + "supportsSession", + "surfaceScale", + "surroundContents", + "suspend", + "suspendRedraw", + "swapCache", + "swapNode", + "sweepFlag", + "symbols", + "sync", + "sysexEnabled", + "system", + "systemCode", + "systemId", + "systemLanguage", + "systemXDPI", + "systemYDPI", + "tBodies", + "tFoot", + "tHead", + "tabIndex", + "tabSize", + "table", + "table-layout", + "tableLayout", + "tableValues", + "tag", + "tagName", + "tagUrn", + "tags", + "taintEnabled", + "takeHeapSnapshot", + "takePhoto", + "takeRecords", + "tan", + "tangentialPressure", + "tanh", + "target", + "targetElement", + "targetRayMode", + "targetRaySpace", + "targetTouches", + "targetX", + "targetY", + "tcpType", + "tee", + "tel", + "terminate", + "test", + "texImage2D", + "texImage3D", + "texParameterf", + "texParameteri", + "texStorage2D", + "texStorage3D", + "texSubImage2D", + "texSubImage3D", + "text", + "text-align", + "text-align-last", + "text-anchor", + "text-combine-upright", + "text-decoration", + "text-decoration-color", + "text-decoration-line", + "text-decoration-skip-ink", + "text-decoration-style", + "text-decoration-thickness", + "text-emphasis", + "text-emphasis-color", + "text-emphasis-position", + "text-emphasis-style", + "text-indent", + "text-justify", + "text-orientation", + "text-overflow", + "text-rendering", + "text-shadow", + "text-transform", + "text-underline-offset", + "text-underline-position", + "text/pdf", + "textAlign", + "textAlignLast", + "textAnchor", + "textAutospace", + "textBaseline", + "textCombineUpright", + "textContent", + "textDecoration", + "textDecorationBlink", + "textDecorationColor", + "textDecorationLine", + "textDecorationLineThrough", + "textDecorationNone", + "textDecorationOverline", + "textDecorationSkipInk", + "textDecorationStyle", + "textDecorationThickness", + "textDecorationUnderline", + "textEmphasis", + "textEmphasisColor", + "textEmphasisPosition", + "textEmphasisStyle", + "textIndent", + "textJustify", + "textJustifyTrim", + "textKashida", + "textKashidaSpace", + "textLength", + "textOrientation", + "textOverflow", + "textRendering", + "textShadow", + "textSizeAdjust", + "textTracks", + "textTransform", + "textUnderlineOffset", + "textUnderlinePosition", + "then", + "threadId", + "threshold", + "thresholds", + "tiltX", + "tiltY", + "time", + "timeEnd", + "timeLog", + "timeOrigin", + "timeRemaining", + "timeStamp", + "timeZone", + "timeZoneName", + "timecode", + "timeline", + "timelineEnd", + "timelineTime", + "timeout", + "timestamp", + "timestampOffset", + "timing", + "title", + "to", + "toArray", + "toBlob", + "toDataURL", + "toDateString", + "toElement", + "toExponential", + "toFixed", + "toFloat32Array", + "toFloat64Array", + "toGMTString", + "toISOString", + "toJSON", + "toLocaleDateString", + "toLocaleFormat", + "toLocaleLowerCase", + "toLocaleString", + "toLocaleTimeString", + "toLocaleUpperCase", + "toLowerCase", + "toMatrix", + "toMethod", + "toPrecision", + "toPrimitive", + "toSdp", + "toSource", + "toStaticHTML", + "toString", + "toStringTag", + "toSum", + "toTimeString", + "toUTCString", + "toUpperCase", + "toggle", + "toggleAttribute", + "toggleLongPressEnabled", + "tone", + "toneBuffer", + "tooLong", + "tooShort", + "toolbar", + "top", + "topMargin", + "total", + "totalFrameDelay", + "totalJSHeapSize", + "totalSize", + "totalVideoFrames", + "touch-action", + "touchAction", + "touched", + "touches", + "trace", + "track", + "trackVisibility", + "tran", + "transaction", + "transactions", + "transceiver", + "transferControlToOffscreen", + "transferFromImageBitmap", + "transferImageBitmap", + "transferIn", + "transferOut", + "transferSize", + "transferToImageBitmap", + "transform", + "transform-box", + "transform-origin", + "transform-style", + "transformBox", + "transformFeedbackVaryings", + "transformOrigin", + "transformOriginX", + "transformOriginY", + "transformOriginZ", + "transformPoint", + "transformString", + "transformStyle", + "transformToDocument", + "transformToFragment", + "transition", + "transition-delay", + "transition-duration", + "transition-property", + "transition-timing-function", + "transitionDelay", + "transitionDuration", + "transitionProperty", + "transitionTimingFunction", + "translate", + "translateSelf", + "translationX", + "translationY", + "transport", + "trim", + "trimEnd", + "trimLeft", + "trimRight", + "trimStart", + "trueSpeed", + "trunc", + "truncate", + "trustedTypes", + "turn", + "twist", + "type", + "typeDetail", + "typeMismatch", + "typeMustMatch", + "types", + "tz", + "u2f", + "ubound", + "undefined", + "unescape", + "uneval", + "unicode", + "unicode-bidi", + "unicodeBidi", + "unicodeRange", + "uniform1f", + "uniform1fv", + "uniform1i", + "uniform1iv", + "uniform1ui", + "uniform1uiv", + "uniform2f", + "uniform2fv", + "uniform2i", + "uniform2iv", + "uniform2ui", + "uniform2uiv", + "uniform3f", + "uniform3fv", + "uniform3i", + "uniform3iv", + "uniform3ui", + "uniform3uiv", + "uniform4f", + "uniform4fv", + "uniform4i", + "uniform4iv", + "uniform4ui", + "uniform4uiv", + "uniformBlockBinding", + "uniformMatrix2fv", + "uniformMatrix2x3fv", + "uniformMatrix2x4fv", + "uniformMatrix3fv", + "uniformMatrix3x2fv", + "uniformMatrix3x4fv", + "uniformMatrix4fv", + "uniformMatrix4x2fv", + "uniformMatrix4x3fv", + "unique", + "uniqueID", + "uniqueNumber", + "unit", + "unitType", + "units", + "unloadEventEnd", + "unloadEventStart", + "unlock", + "unmount", + "unobserve", + "unpause", + "unpauseAnimations", + "unreadCount", + "unregister", + "unregisterContentHandler", + "unregisterProtocolHandler", + "unscopables", + "unselectable", + "unshift", + "unsubscribe", + "unsuspendRedraw", + "unsuspendRedrawAll", + "unwatch", + "unwrapKey", + "upDegrees", + "upX", + "upY", + "upZ", + "update", + "updateCommands", + "updateEnabled", + "updateIce", + "updateInterval", + "updatePlaybackRate", + "updateRenderState", + "updateSettings", + "updateTiming", + "updateViaCache", + "updateWith", + "updated", + "updating", + "upgrade", + "upload", + "uploadTotal", + "uploaded", + "upper", + "upperBound", + "upperOpen", + "uri", + "url", + "urn", + "urns", + "usage", + "usages", + "usb", + "usbVersionMajor", + "usbVersionMinor", + "usbVersionSubminor", + "useCurrentView", + "useGrouping", + "useMap", + "useProgram", + "usedJSHeapSize", + "usedSpace", + "user-select", + "userActivation", + "userAgent", + "userChoice", + "userHandle", + "userHint", + "userLanguage", + "userProfile", + "userSelect", + "userVisibleOnly", + "userZoom", + "username", + "usernameFragment", + "utterance", + "uuid", + "v8BreakIterator", + "v8Parse", + "vAlign", + "vLink", + "valid", + "validate", + "validateProgram", + "validationMessage", + "validity", + "value", + "valueAsDate", + "valueAsNumber", + "valueAsString", + "valueInSpecifiedUnits", + "valueMissing", + "valueOf", + "valueText", + "valueType", + "values", + "variable", + "variant", + "vector-effect", + "vectorEffect", + "velocityAngular", + "velocityExpansion", + "velocityX", + "velocityY", + "vendor", + "vendorId", + "vendorSub", + "verify", + "version", + "vertexAttrib1f", + "vertexAttrib1fv", + "vertexAttrib2f", + "vertexAttrib2fv", + "vertexAttrib3f", + "vertexAttrib3fv", + "vertexAttrib4f", + "vertexAttrib4fv", + "vertexAttribDivisor", + "vertexAttribDivisorANGLE", + "vertexAttribI4i", + "vertexAttribI4iv", + "vertexAttribI4ui", + "vertexAttribI4uiv", + "vertexAttribIPointer", + "vertexAttribPointer", + "vertical", + "vertical-align", + "verticalAlign", + "verticalOverflow", + "vh", + "vibrate", + "vibrationActuator", + "video/x-ms-asf", + "video/x-ms-asf-plugin", + "video/x-ms-wm", + "video/x-ms-wmv", + "video/x-ms-wvx", + "videoBitsPerSecond", + "videoHeight", + "videoTracks", + "videoWidth", + "view", + "viewBox", + "viewBoxString", + "viewTarget", + "viewTargetString", + "viewport", + "viewportAnchorX", + "viewportAnchorY", + "viewportElement", + "views", + "violatedDirective", + "visibility", + "visibilityState", + "visible", + "visualViewport", + "vlinkColor", + "vmax", + "vmin", + "voice", + "voiceURI", + "volume", + "vrml", + "vspace", + "vw", + "w", + "wait", + "waitSync", + "waiting", + "wake", + "wakeLock", + "wand", + "warn", + "wasAlternateProtocolAvailable", + "wasClean", + "wasDiscarded", + "wasFetchedViaSpdy", + "wasNpnNegotiated", + "watch", + "watchAvailability", + "watchPosition", + "webdriver", + "webkitAddKey", + "webkitAlignContent", + "webkitAlignItems", + "webkitAlignSelf", + "webkitAnimation", + "webkitAnimationDelay", + "webkitAnimationDirection", + "webkitAnimationDuration", + "webkitAnimationFillMode", + "webkitAnimationIterationCount", + "webkitAnimationName", + "webkitAnimationPlayState", + "webkitAnimationTimingFunction", + "webkitAppRegion", + "webkitAppearance", + "webkitAspectRatio", + "webkitAudioContext", + "webkitAudioDecodedByteCount", + "webkitAudioPannerNode", + "webkitBackdropFilter", + "webkitBackfaceVisibility", + "webkitBackground", + "webkitBackgroundAttachment", + "webkitBackgroundClip", + "webkitBackgroundColor", + "webkitBackgroundComposite", + "webkitBackgroundImage", + "webkitBackgroundOrigin", + "webkitBackgroundPosition", + "webkitBackgroundPositionX", + "webkitBackgroundPositionY", + "webkitBackgroundRepeat", + "webkitBackgroundSize", + "webkitBackingStorePixelRatio", + "webkitBorderAfter", + "webkitBorderAfterColor", + "webkitBorderAfterStyle", + "webkitBorderAfterWidth", + "webkitBorderBefore", + "webkitBorderBeforeColor", + "webkitBorderBeforeStyle", + "webkitBorderBeforeWidth", + "webkitBorderBottomLeftRadius", + "webkitBorderBottomRightRadius", + "webkitBorderEnd", + "webkitBorderEndColor", + "webkitBorderEndStyle", + "webkitBorderEndWidth", + "webkitBorderFit", + "webkitBorderHorizontalSpacing", + "webkitBorderImage", + "webkitBorderImageOutset", + "webkitBorderImageRepeat", + "webkitBorderImageSlice", + "webkitBorderImageSource", + "webkitBorderImageWidth", + "webkitBorderRadius", + "webkitBorderStart", + "webkitBorderStartColor", + "webkitBorderStartStyle", + "webkitBorderStartWidth", + "webkitBorderTopLeftRadius", + "webkitBorderTopRightRadius", + "webkitBorderVerticalSpacing", + "webkitBoxAlign", + "webkitBoxDecorationBreak", + "webkitBoxDirection", + "webkitBoxFlex", + "webkitBoxFlexGroup", + "webkitBoxLines", + "webkitBoxOrdinalGroup", + "webkitBoxOrient", + "webkitBoxPack", + "webkitBoxReflect", + "webkitBoxShadow", + "webkitBoxSizing", + "webkitCancelAnimationFrame", + "webkitCancelFullScreen", + "webkitCancelKeyRequest", + "webkitCancelRequestAnimationFrame", + "webkitClearResourceTimings", + "webkitClipPath", + "webkitClosedCaptionsVisible", + "webkitColumnAxis", + "webkitColumnBreakAfter", + "webkitColumnBreakBefore", + "webkitColumnBreakInside", + "webkitColumnCount", + "webkitColumnGap", + "webkitColumnProgression", + "webkitColumnRule", + "webkitColumnRuleColor", + "webkitColumnRuleStyle", + "webkitColumnRuleWidth", + "webkitColumnSpan", + "webkitColumnWidth", + "webkitColumns", + "webkitConvertPointFromNodeToPage", + "webkitConvertPointFromPageToNode", + "webkitCreateShadowRoot", + "webkitCurrentFullScreenElement", + "webkitCurrentPlaybackTargetIsWireless", + "webkitCursorVisibility", + "webkitDashboardRegion", + "webkitDecodedFrameCount", + "webkitDirectionInvertedFromDevice", + "webkitDisplayingFullscreen", + "webkitDroppedFrameCount", + "webkitEnterFullScreen", + "webkitEnterFullscreen", + "webkitEntries", + "webkitExitFullScreen", + "webkitExitFullscreen", + "webkitExitPointerLock", + "webkitFilter", + "webkitFlex", + "webkitFlexBasis", + "webkitFlexDirection", + "webkitFlexFlow", + "webkitFlexGrow", + "webkitFlexShrink", + "webkitFlexWrap", + "webkitFontFeatureSettings", + "webkitFontKerning", + "webkitFontSizeDelta", + "webkitFontSmoothing", + "webkitForce", + "webkitFullScreenKeyboardInputAllowed", + "webkitFullscreenElement", + "webkitFullscreenEnabled", + "webkitGenerateKeyRequest", + "webkitGetAsEntry", + "webkitGetDatabaseNames", + "webkitGetEntries", + "webkitGetEntriesByName", + "webkitGetEntriesByType", + "webkitGetFlowByName", + "webkitGetGamepads", + "webkitGetImageDataHD", + "webkitGetNamedFlows", + "webkitGetRegionFlowRanges", + "webkitGetUserMedia", + "webkitHasClosedCaptions", + "webkitHidden", + "webkitHighlight", + "webkitHyphenateCharacter", + "webkitHyphenateLimitAfter", + "webkitHyphenateLimitBefore", + "webkitHyphenateLimitLines", + "webkitHyphens", + "webkitIDBCursor", + "webkitIDBDatabase", + "webkitIDBDatabaseError", + "webkitIDBDatabaseException", + "webkitIDBFactory", + "webkitIDBIndex", + "webkitIDBKeyRange", + "webkitIDBObjectStore", + "webkitIDBRequest", + "webkitIDBTransaction", + "webkitImageSmoothingEnabled", + "webkitIndexedDB", + "webkitInitMessageEvent", + "webkitInitialLetter", + "webkitIsFullScreen", + "webkitJustifyContent", + "webkitKeys", + "webkitLineAlign", + "webkitLineBoxContain", + "webkitLineBreak", + "webkitLineClamp", + "webkitLineDash", + "webkitLineDashOffset", + "webkitLineGrid", + "webkitLineSnap", + "webkitLocale", + "webkitLockOrientation", + "webkitLogicalHeight", + "webkitLogicalWidth", + "webkitMarginAfter", + "webkitMarginAfterCollapse", + "webkitMarginBefore", + "webkitMarginBeforeCollapse", + "webkitMarginBottomCollapse", + "webkitMarginCollapse", + "webkitMarginEnd", + "webkitMarginStart", + "webkitMarginTopCollapse", + "webkitMarquee", + "webkitMarqueeDirection", + "webkitMarqueeIncrement", + "webkitMarqueeRepetition", + "webkitMarqueeSpeed", + "webkitMarqueeStyle", + "webkitMask", + "webkitMaskBoxImage", + "webkitMaskBoxImageOutset", + "webkitMaskBoxImageRepeat", + "webkitMaskBoxImageSlice", + "webkitMaskBoxImageSource", + "webkitMaskBoxImageWidth", + "webkitMaskClip", + "webkitMaskComposite", + "webkitMaskImage", + "webkitMaskOrigin", + "webkitMaskPosition", + "webkitMaskPositionX", + "webkitMaskPositionY", + "webkitMaskRepeat", + "webkitMaskRepeatX", + "webkitMaskRepeatY", + "webkitMaskSize", + "webkitMaskSourceType", + "webkitMatchesSelector", + "webkitMaxLogicalHeight", + "webkitMaxLogicalWidth", + "webkitMediaStream", + "webkitMinLogicalHeight", + "webkitMinLogicalWidth", + "webkitNbspMode", + "webkitNotifications", + "webkitOfflineAudioContext", + "webkitOpacity", + "webkitOrder", + "webkitOrientation", + "webkitPaddingAfter", + "webkitPaddingBefore", + "webkitPaddingEnd", + "webkitPaddingStart", + "webkitPeerConnection00", + "webkitPersistentStorage", + "webkitPerspective", + "webkitPerspectiveOrigin", + "webkitPerspectiveOriginX", + "webkitPerspectiveOriginY", + "webkitPointerLockElement", + "webkitPostMessage", + "webkitPreservesPitch", + "webkitPrintColorAdjust", + "webkitPutImageDataHD", + "webkitRTCPeerConnection", + "webkitRegionOverset", + "webkitRelativePath", + "webkitRequestAnimationFrame", + "webkitRequestFileSystem", + "webkitRequestFullScreen", + "webkitRequestFullscreen", + "webkitRequestPointerLock", + "webkitResolveLocalFileSystemURL", + "webkitRtlOrdering", + "webkitRubyPosition", + "webkitSetMediaKeys", + "webkitSetResourceTimingBufferSize", + "webkitShadowRoot", + "webkitShapeImageThreshold", + "webkitShapeMargin", + "webkitShapeOutside", + "webkitShowPlaybackTargetPicker", + "webkitSlice", + "webkitSpeechGrammar", + "webkitSpeechGrammarList", + "webkitSpeechRecognition", + "webkitSpeechRecognitionError", + "webkitSpeechRecognitionEvent", + "webkitStorageInfo", + "webkitSupportsFullscreen", + "webkitSvgShadow", + "webkitTapHighlightColor", + "webkitTemporaryStorage", + "webkitTextCombine", + "webkitTextDecoration", + "webkitTextDecorationColor", + "webkitTextDecorationLine", + "webkitTextDecorationSkip", + "webkitTextDecorationStyle", + "webkitTextDecorationsInEffect", + "webkitTextEmphasis", + "webkitTextEmphasisColor", + "webkitTextEmphasisPosition", + "webkitTextEmphasisStyle", + "webkitTextFillColor", + "webkitTextOrientation", + "webkitTextSecurity", + "webkitTextSizeAdjust", + "webkitTextStroke", + "webkitTextStrokeColor", + "webkitTextStrokeWidth", + "webkitTextUnderlinePosition", + "webkitTextZoom", + "webkitTransform", + "webkitTransformOrigin", + "webkitTransformOriginX", + "webkitTransformOriginY", + "webkitTransformOriginZ", + "webkitTransformStyle", + "webkitTransition", + "webkitTransitionDelay", + "webkitTransitionDuration", + "webkitTransitionProperty", + "webkitTransitionTimingFunction", + "webkitURL", + "webkitUnlockOrientation", + "webkitUserDrag", + "webkitUserModify", + "webkitUserSelect", + "webkitVideoDecodedByteCount", + "webkitVisibilityState", + "webkitWirelessVideoPlaybackDisabled", + "webkitWritingMode", + "webkitdirectory", + "webkitdropzone", + "webstore", + "weekday", + "weight", + "whatToShow", + "wheelDelta", + "wheelDeltaX", + "wheelDeltaY", + "whenDefined", + "which", + "white-space", + "whiteSpace", + "wholeText", + "widows", + "width", + "will-change", + "willChange", + "willValidate", + "window", + "withCredentials", + "word-break", + "word-spacing", + "word-wrap", + "wordBreak", + "wordSpacing", + "wordWrap", + "workerStart", + "wrap", + "wrapKey", + "writable", + "writableAuxiliaries", + "write", + "writeText", + "writeValue", + "writeWithoutResponse", + "writeln", + "writing-mode", + "writingMode", + "x", + "x1", + "x2", + "xChannelSelector", + "xmlEncoding", + "xmlStandalone", + "xmlVersion", + "xmlbase", + "xmllang", + "xmlspace", + "xor", + "xr", + "y", + "y1", + "y2", + "yChannelSelector", + "yandex", + "year", + "z", + "z-index", + "zIndex", + "zoom", + "zoomAndPan", + "zoomRectScreen" +] diff --git a/node_modules/uglify-js/tools/exports.js b/node_modules/uglify-js/tools/exports.js new file mode 100644 index 0000000..1d2d510 --- /dev/null +++ b/node_modules/uglify-js/tools/exports.js @@ -0,0 +1,8 @@ +exports["Dictionary"] = Dictionary; +exports["is_statement"] = is_statement; +exports["List"] = List; +exports["minify"] = minify; +exports["parse"] = parse; +exports["push_uniq"] = push_uniq; +exports["TreeTransformer"] = TreeTransformer; +exports["TreeWalker"] = TreeWalker; diff --git a/node_modules/uglify-js/tools/node.js b/node_modules/uglify-js/tools/node.js new file mode 100644 index 0000000..7ca1982 --- /dev/null +++ b/node_modules/uglify-js/tools/node.js @@ -0,0 +1,110 @@ +var fs = require("fs"); + +exports.FILES = [ + require.resolve("../lib/utils.js"), + require.resolve("../lib/ast.js"), + require.resolve("../lib/transform.js"), + require.resolve("../lib/parse.js"), + require.resolve("../lib/scope.js"), + require.resolve("../lib/compress.js"), + require.resolve("../lib/output.js"), + require.resolve("../lib/sourcemap.js"), + require.resolve("../lib/mozilla-ast.js"), + require.resolve("../lib/propmangle.js"), + require.resolve("../lib/minify.js"), + require.resolve("./exports.js"), +]; + +new Function("domprops", "exports", function() { + var code = exports.FILES.map(function(file) { + return fs.readFileSync(file, "utf8"); + }); + code.push("exports.describe_ast = " + describe_ast.toString()); + return code.join("\n\n"); +}())(require("./domprops.json"), exports); + +function to_comment(value) { + if (typeof value != "string") value = JSON.stringify(value, function(key, value) { + return typeof value == "function" ? "<[ " + value + " ]>" : value; + }, 2); + return "// " + value.replace(/\n/g, "\n// "); +} + +if (+process.env["UGLIFY_BUG_REPORT"]) exports.minify = function(files, options) { + if (typeof options == "undefined") options = "<>"; + var code = [ + "// UGLIFY_BUG_REPORT", + to_comment(options), + ]; + if (typeof files == "string") { + code.push(""); + code.push("//-------------------------------------------------------------") + code.push("// INPUT CODE", files); + } else for (var name in files) { + code.push(""); + code.push("//-------------------------------------------------------------") + code.push(to_comment(name), files[name]); + } + if (options.sourceMap && options.sourceMap.url) { + code.push(""); + code.push("//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9"); + } + var result = { code: code.join("\n") }; + if (options.sourceMap) result.map = '{"version":3,"sources":[],"names":[],"mappings":""}'; + return result; +}; + +function describe_ast() { + var out = OutputStream({ beautify: true }); + doitem(AST_Node); + return out.get() + "\n"; + + function doitem(ctor) { + out.print("AST_" + ctor.TYPE); + var props = ctor.SELF_PROPS.filter(function(prop) { + return !/^\$/.test(prop); + }); + if (props.length > 0) { + out.space(); + out.with_parens(function() { + props.forEach(function(prop, i) { + if (i) out.space(); + out.print(prop); + }); + }); + } + if (ctor.documentation) { + out.space(); + out.print_string(ctor.documentation); + } + if (ctor.SUBCLASSES.length > 0) { + out.space(); + out.with_block(function() { + ctor.SUBCLASSES.sort(function(a, b) { + return a.TYPE < b.TYPE ? -1 : 1; + }).forEach(function(ctor, i) { + out.indent(); + doitem(ctor); + out.newline(); + }); + }); + } + } +} + +function infer_options(options) { + var result = exports.minify("", options); + return result.error && result.error.defs; +} + +exports.default_options = function() { + var defs = infer_options({ 0: 0 }); + Object.keys(defs).forEach(function(component) { + var options = {}; + options[component] = { 0: 0 }; + if (options = infer_options(options)) { + defs[component] = options; + } + }); + return defs; +}; diff --git a/node_modules/uglify-js/tools/tty.js b/node_modules/uglify-js/tools/tty.js new file mode 100644 index 0000000..395c48e --- /dev/null +++ b/node_modules/uglify-js/tools/tty.js @@ -0,0 +1,22 @@ +// workaround for tty output truncation on Node.js +try { + // prevent buffer overflow and other asynchronous bugs + process.stdout._handle.setBlocking(true); + process.stderr._handle.setBlocking(true); +} catch (e) { + // ensure output buffers are flushed before process termination + var exit = process.exit; + process.exit = function() { + var args = [].slice.call(arguments); + process.once("uncaughtException", function() { + (function callback() { + if (process.stdout.bufferSize || process.stderr.bufferSize) { + setTimeout(callback, 1); + } else { + exit.apply(process, args); + } + })(); + }); + throw exit; + }; +} diff --git a/node_modules/zlib/.npmignore b/node_modules/zlib/.npmignore new file mode 100644 index 0000000..0058b67 --- /dev/null +++ b/node_modules/zlib/.npmignore @@ -0,0 +1,2 @@ +build +.lock-wscript \ No newline at end of file diff --git a/node_modules/zlib/LICENSE b/node_modules/zlib/LICENSE new file mode 100644 index 0000000..8311c9c --- /dev/null +++ b/node_modules/zlib/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2011, Konstantin Käfer +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * 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. + * Neither the name of node-zlib nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +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 Konstantin Käfer 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. diff --git a/node_modules/zlib/Makefile b/node_modules/zlib/Makefile new file mode 100644 index 0000000..4b64961 --- /dev/null +++ b/node_modules/zlib/Makefile @@ -0,0 +1,15 @@ +build: + node-waf build + +clean: + node-waf clean + +ifndef only +test: build + @expresso -I lib test/*.test.js +else +test: build + @expresso -I lib test/${only}.test.js +endif + +.PHONY: build clean test diff --git a/node_modules/zlib/README.md b/node_modules/zlib/README.md new file mode 100644 index 0000000..f06ffd4 --- /dev/null +++ b/node_modules/zlib/README.md @@ -0,0 +1,54 @@ +# NAME + +node-zlib - Simple, synchronous deflate/inflate for node.js buffers. + + + +# USAGE + +Install with `npm install zlib`. + + var Buffer = require('buffer').Buffer; + var zlib = require('zlib'); + + var input = new Buffer('lorem ipsum dolor sit amet'); + var compressed = zlib.deflate(input); + var output = zlib.inflate(compressed); + +Note that `node-zlib` is only intended for small (< 128 KB) data that you already have buffered. It is not meant for input/output streams. + +# BUILDING + +Make sure you have `zlib` installed. Mac OS X ships with it by default. + +To obtain and build the bindings: + + git clone git://github.com/kkaefer/node-zlib.git + cd node-zlib + ./configure + make + +You can also use [`npm`](https://github.com/isaacs/npm) to download and install them: + + npm install zlib + + + +# TESTS + +[expresso](https://github.com/visionmedia/expresso) is required to run unit tests. + + npm install expresso + make test + + + +# CONTRIBUTORS + +* [Konstantin Käfer](https://github.com/kkaefer) + + + +# LICENSE + +`node-zlib` is [BSD licensed](https://github.com/kkaefer/node-zlib/raw/master/LICENSE). diff --git a/node_modules/zlib/configure b/node_modules/zlib/configure new file mode 100755 index 0000000..dd549cd --- /dev/null +++ b/node_modules/zlib/configure @@ -0,0 +1,2 @@ +#!/bin/sh +node-waf configure \ No newline at end of file diff --git a/node_modules/zlib/index.js b/node_modules/zlib/index.js new file mode 100644 index 0000000..df32a46 --- /dev/null +++ b/node_modules/zlib/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/zlib'); diff --git a/node_modules/zlib/lib/zlib.js b/node_modules/zlib/lib/zlib.js new file mode 100644 index 0000000..bc49811 --- /dev/null +++ b/node_modules/zlib/lib/zlib.js @@ -0,0 +1 @@ +module.exports = require('./zlib_bindings'); diff --git a/node_modules/zlib/package.json b/node_modules/zlib/package.json new file mode 100644 index 0000000..f6b0fe2 --- /dev/null +++ b/node_modules/zlib/package.json @@ -0,0 +1,18 @@ +{ + "name": "zlib", + "description": "Simple, synchronous deflate/inflate for buffers", + "version": "1.0.5", + "homepage": "https://github.com/kkaefer/node-zlib", + "author": "Konstantin Käfer ", + "repository": { + "type": "git", + "url": "git://github.com/kkaefer/node-zlib.git" + }, + "engines": { + "node": ">=0.2.0" + }, + "licenses": [ + { "type": "BSD" } + ], + "main": "./lib/zlib" +} diff --git a/node_modules/zlib/src/node-zlib.cc b/node_modules/zlib/src/node-zlib.cc new file mode 100644 index 0000000..b2c7e14 --- /dev/null +++ b/node_modules/zlib/src/node-zlib.cc @@ -0,0 +1,95 @@ +#include +#include +#include +#include + +#include +#include +#include + +using namespace v8; +using namespace node; + +// node v0.2.x compatibility +#if NODE_VERSION_AT_LEAST(0,3,0) + #define Buffer_Data Buffer::Data + #define Buffer_Length Buffer::Length + #define Buffer_New Buffer::New +#else + inline char* Buffer_Data(Handle obj) { + return (ObjectWrap::Unwrap(obj))->data(); + } + inline size_t Buffer_Length(Handle obj) { + return (ObjectWrap::Unwrap(obj))->length(); + } + inline Buffer* Buffer_New(char* data, size_t length) { + Buffer* buffer = Buffer::New(length); + memcpy(buffer->data(), data, length); + return buffer; + } +#endif + + +z_stream deflate_s; +z_stream inflate_s; + +inline Handle ZLib_error(const char* msg = NULL) { + return ThrowException(Exception::Error( + String::New(msg ? msg : "Unknown Error"))); +} + +#define ZLib_Xflate(x, factor) \ +Handle ZLib_##x##flate(const Arguments& args) { \ + HandleScope scope; \ + \ + if (args.Length() < 1 || !Buffer::HasInstance(args[0])) { \ + return ZLib_error("Expected Buffer as first argument"); \ + } \ + \ + if ((x##flateReset(&x##flate_s)) != Z_OK) { \ + assert((false, "ZLib stream is beyond repair")); \ + } \ + \ + Local input = args[0]->ToObject(); \ + x##flate_s.next_in = (Bytef*)Buffer_Data(input); \ + int length = x##flate_s.avail_in = Buffer_Length(input); \ + \ + int ret; \ + char* result = NULL; \ + \ + int compressed = 0; \ + do { \ + result = (char*)realloc(result, compressed + factor * length); \ + if (!result) return ZLib_error("Could not allocate memory"); \ + \ + x##flate_s.avail_out = factor * length; \ + x##flate_s.next_out = (Bytef*)result + compressed; \ + \ + ret = x##flate(&x##flate_s, Z_FINISH); \ + if (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) { \ + free(result); \ + return ZLib_error(x##flate_s.msg); \ + } \ + \ + compressed += (factor * length - x##flate_s.avail_out); \ + } while (x##flate_s.avail_out == 0); \ + \ + Buffer* output = Buffer_New(result, compressed); \ + free(result); \ + return scope.Close(Local::New(output->handle_)); \ +} + +ZLib_Xflate(de, 1); +ZLib_Xflate(in, 2); + +extern "C" void init (Handle target) { + deflate_s.zalloc = inflate_s.zalloc = Z_NULL; + deflate_s.zfree = inflate_s.zfree = Z_NULL; + deflate_s.opaque = inflate_s.opaque = Z_NULL; + + deflateInit(&deflate_s, Z_DEFAULT_COMPRESSION); + inflateInit(&inflate_s); + + NODE_SET_METHOD(target, "deflate", ZLib_deflate); + NODE_SET_METHOD(target, "inflate", ZLib_inflate); +} diff --git a/node_modules/zlib/test/deflate.test.js b/node_modules/zlib/test/deflate.test.js new file mode 100644 index 0000000..c27b7ec --- /dev/null +++ b/node_modules/zlib/test/deflate.test.js @@ -0,0 +1,23 @@ +var assert = require('assert'); +var Buffer = require('buffer').Buffer; +var zlib = require('../lib/zlib'); + +exports['test deflate/inflate buffer'] = function(beforeExit) { + var input = new Buffer('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'); + var compressed = zlib.deflate(input); + var output = zlib.inflate(compressed); + assert.deepEqual(input, output); +}; + +exports['test deflate/inflate with high compression ratio'] = function(beforeExit) { + var input = new Buffer('[" !!!!!!!########################$$$$$$$$$$$$$$$$%%%%%%%%%% %%%%%%%%%%%%%%%% % %"," !!!!!!########################$$$$$$$$$$$$$$$$$%%%%%%%%%%% %%%%%%%%%%%%% %%%% %%"," !!!!!########################$$$$$$$$$$$$$$$$$%%%%%%%%%%%%% %%%%%%% %%%%%% %%"," !!!!!###########################$$$$$$$$$$$$$$$$$%%%%%%%%%%%%% %%% %%%%%%%%%%"," !!!!###########################$$$$$$$$$$$$$$$$$%%%%%%%%%%%%% %%%%%%%%%%%%"," !!!!!!###################### ###$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%% %%%%%%%%%%%%"," ! !!!!!###################### $$$$$$$$$$$$$$%%%%%%%%%%%%%% %%%%%%%%%%%%%%"," !!!!!!!##################### $$$$$$$$$$$$$%%%%%%%%%%%%%% %%%%%%%%%%%%%%%"," !!!!!!!#################### $$$$$$$$$$$$%%%%%%%%%%%%% %%%%%%%%%%%%%%"," !!!!!##################### $$$$$$$$$$$$$%%%%%%%%%%%%%% %%%%%%%%%%%%%%"," ! !!!!!##################### $$$$$$$$$$$$%%%%%%%%%%%%%% % %%% %%%%%%%%%%%%%"," ! !!!!!!!##################### $$$$$$$$$$$$$%%%%%%%%%%%%%%% %%%% %%%%%%%%%%%%%"," !!!!!!##################### $$$$$$$$$$$$$$$$%%%%%%%%%%%%%% %%%%% % %%%%%%%%%%%%"," !!!!!!###################### $$$$$$$$$$$$$$$$%%%%%%%%%%%%%% %%%%%%% %%%%%%%%%%%%%"," ! !!!!!!!!##################### $$$$$$$$$$$$$$$$$%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!#################### $$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!################### $$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%"," !!! !!!!####################### $$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%"," !!!! !!!######################## $$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%"," ! !! !!!!####################### $$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!! ! !!!###################### $$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ! ! !!!!!!!!#################### $$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!#################### $ $$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!!################## $$$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!! !!!!!!!!!!################## $$$$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!! !!!!!!!!!!################# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!! !!!!!!!!!!!!!################# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!!!!!!############### $$$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!!!!!!!!############### $$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!!!!!!!!!############### $$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!!!!!!!!!############### $$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!!!!!!!!!############### $$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!!!!!!!!!!############# $$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!!!!!!!!!!!############ $$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!!!!!!!!!!!############ $$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ! ! !!!!!!!!!!!!!!!!!!############ $$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!!!!!!!!!############## $$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!!!!!!!!!!############## $$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!!!!!!!!!!################ $ $$$$$$$$$$$$$ $$$% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!! !!!!!!!!!!!!!!!!################ $ $$$$$$$$$$$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!!!!!!!!!################# & & $ $$$$$$ $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ! !!!!!!!!!!!!!!!!!!################## & $ $$$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ! !!!!!!!!!!!!!!!!!##################### $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!!! !!!#################### %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!! !!!!!!!!!!! !!!############## ##### \'\'\' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ! !!!!!!!!!!!! !!!################### \'\'\'\'\'\'\'\'\'\'\'\'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!! !!!################### \'\'\'\'\'\'\'\'\'\'\'\'\'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!!! #!################## \'\'\'\'\'\'\'\'\'\'\'\'\'\'\'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!!! ################## \'\' \'\'\'\'\'\'\'\'\'\'\'\'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!!!! ################ \'\'\'\'\'\'\'\'\'\'\'\'\'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!!!! ################ \'\'\'\' \'\'\'\'\'\'\'\'\'\'\'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!!!! ############### \'\' \'\'\'\'\'\'\'\'\'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," !!!! ############## \' \'\'(\'\'\'\'\'\'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ############# # ((((\'\'\'\'\'\'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ) ############## # ( (((((\'\'\'\'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ) ############## ## ((( (((((((((%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," )) ############ ## (((( ((((((((((%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," )))) ############ # (((((( (((((((((((%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ) ))) ########### # # ((((((((((((((((((%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," )) ))) ########### ((((((((((((((((((((%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," )))))) ########### ((((((((((((((((((((%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," )))))))) ######### # (((****((((*(((((((((%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ))))))) ########## (************((((((((%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ))))))) )) #### **************(((((+++%+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ))))) ) ))) #### ***************((+++++++%++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," )))) ) )))) #### ***************++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," )))) )) )))) # ***************++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ))) )) ) ) %**************+++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," )))) ) ) %%%%**********++++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ,,,, ))) -- %%%%%%%%*********++++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ,,, ) , ----- %%%%%%%*********+++++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ,,,,,, ,,,, ------- ----%%%%%%-*******+++++++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ,,,,,, ,,,,,, -----------------------*****+*++++++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," , ,,,,, ,,,,,,,, -------------------------***+++++++++++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%",". ,,,,,,,,,,,,,,, --------------------------+++++++++++++++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"," ,,,,,,,,,,,,,,,,,,,,---------------------------+++++++++++++++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%",". /// ,,,,,,,,,,,,,,,,,,,,---------------------------+++++++++++++++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%",". /////,,,,,,,,,,,,,,,,,,,,---------------------------++++++++++++++++++++++%+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%",". .. /////,,,,,,,,,,,,,,,,,,,,----------------------------+++++++++++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%","..... ///////,,,,,,,,,,,,,,,,,,,,,---------------------------+++++++++++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%","..... //////,,,,,,,,,,,,,,,,,,,,,,-------------------------+++++++++++++++++++++++%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%","..... ////////,,,,,,,,,,,,,,,,,,,,,------------------------+++++++++++++++++++++++++%%0000%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%","..... ////////,,,,,,,,,,,,,,,,,,,,,,--------------------------++++++++++++++++++++000000000%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%",".... //////,,,,,,,,,,,,,,,,,,,,,,,,--------------------------++000000++++++++++++0000000000%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%","... //////,,,,,,,,,,,,,,,,,,,,,,,,-------------------------+0000000000+++++0+++00000000000%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%",".. ///11///,,,,,,,,,,,,,,,,,,,,,,,,,-------------------------0000000000000000000+0000000000%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%","..... 111111111/,,,,,,,,,,,,,,,,,,,,,,,,,-------------------------0000000000000000000000000000000%%%%%%%%%%%%%%%%%%%%%%%%%%%%%","... 22111111111/,,,,,,,,,,,,,,,,,,,,,,,3,3-------------------------00000000000000000000000000000000%%%%%%%%%%%%%%%%%%%%%%%%%%%"," 2222211111111,,,,,,,,,,,,,,,,,,,,,,33333------------------------00000000000000000000000000000000%%%%%%%%%%%%%%%%%%%%%%%%%%%"," 2222221111111,,,,,,,,,,,,,,,,,,,,333333333----------------------00000000000000000000000000000000%%%%%%%%%%%%%%%%%%%%%%%%%%%"," 2222222111111,,,,,,,,,,,,,,,,,,33333333333--3------------------000000000000000000000000000000000000%00%%%%%%%%%%%%%%%%%%%%%"," 22222222111114,,,,,,,,,,,,,,,,,3333333333333333----------------00000000000000000000000000000000000000000%0%%%%%%%%%%%%%%%%%%"," 22222222222211144,,,,,,,,,,,,,,,,,33333333333333333-------------000000000000000000000000000000000000000000000%%%%%%%%%%%%%%%%%"," 222222222222222144,,,,,,,,,,,,,,,,,333333333333333333-----------000000000000000000000000000000000000000000000000%0%%%%%%%%%%%%%"," 222222222222222222,,,,,,,,,,,,,,,,,,33333333333333335555-55555--00000000000000000000000000000000000000000000000000%%%%%%%%%%%%%","2222222222222222222222,,,,,,,,,,,,,,,,33333333333333555555555555-0000000000000000000000000000000000000000000000000%%%%%%%%%%%%%%","222222222222222222222222,,,,,,,,,,,,,,,333366333333555555555555500000000000000000000000000000000000000000000000000%%%%%%%%%%%%%%","22222222222222222222222,,,,,,,,,,,,,,,,,3366666665555555555555550000000000000000000000000000000000000000000000000%%%%%%%%%%%%%%%","22222222222222222222222,,,,,,,,,,,,,,,,666666666555555555557775500000000000000000000000000000000000000000000000000%%%%%%%%%%%%%%","2222222222222222222222,,,,,,,,,,,,,,,66666666666655555557577777770000000000089990000000000000000000000000000000000%%%%%%%%%%%%%%","2222222222222222222222,,,,,,,,,,,,,,,66666666666675555777777777777880000000888999990000000000000000000000000000000%%%%%%%%%%%%%%","2222222222222222222222,,,,,,,,,,,,,,,66666666666677757777777777788888880888888999999000000000000000000000000000%%%%%%%%%%%%%%%%%","2222222222222222222222::::::6,66,6666,66666666667777777777777778888888888888888999900000000000000000000000000%%%%%%%%%%%%%%%%%%%","22222222222222222222::::::::6,6666666666666666677777777777777778888888888888888999999000000000000000000000000%%%%%%%%%%%%%%%%%%%","22222222222222222222::::::::6666666666666666666777777777777777888888888888888888999990000000000000000000000 %%%%%%%%%%%%%%%%","2222222222222222222:::::::::::;6;;;;6666666666<7777777777777778888888888888888888999990000000000000000000 %%%%%%%%%%%%%%%%%%","222222222222222222:::::::::::;;;;;;;;;;6666<<<<77777777777777888888888888888888889999900 0000000000 %%%%%%%%%%%%%%%%%%%%","22222222222222222222::::;::;;;;;;;;;;;;<<<<<<<===777777777777888888888888888888889900000 000000000 %%%%%%%%%%%%%%%%%%%","22222222222222222222:::;;;;;;;;;;;;;;;;<<<<<<=====777777>>88888888888888888888889990000 00 00 %%%%%%%%%%%%%%%%%%%","22222222222222222222;;;;;;;;;;;;;;;;;;;<<<<<<======77=>>>>>888888888888888888888890000 000 %%%%%%%%%%%%%%%%%%%%","22222222222222222222;;;;;;;;;;;;;;;;; <<<<==========>>>>>>8888888888888888888899000 000000 %%%%%%%%%%%%%%%%%%%%%","222222222222222222222;;;;;;;;;;;;;; ================>>>>>8888888888888888888880088 000000 000% %%%%%%%%%%%%%%%%%%%%","2222222222222222222;;;;;;;;;;;;;;;;; == ==?=????=?==>>>>>>>88888888888888888888888 00000 00 %%%%%%%%%%%%%%%%%%%%%%%","22222222222222222222;;;;;;;;;;;;;;; = ==???????????>>>>>888888888888888888888888 0000 %%%%%%%%%%%%%%%%%%%%%","22222222222222222222;;;;;;;;;;;;;;; = ===?????????>>>>>>>>8>88888888888888888 000 %%%%%%%%%%%%%%%%%%%","22222222222222222222;;;;; ;;;;;;;;; ====????????>>>>>>>>>>88888888888888888 %%%%%%%%%%%%%%%%%%","2222222222222222222222;; ;;;;;;;; ===?????????>>>>>>>>>@88888888888@8888 %%%%%%%%%%%%%%%%","2222222222222222222222; ;;;;;;;; ===????????>>>>>>>>@@88888888@@@@@@88 %%%%%%%%%%%%%%%","222222222222222222222 ;;;;;;;;; ===???????>>>>>>>>@@@@@@@@@@@@@@@@@@ %%%%%%%%%%%%%%","22222222222 222 ;;;;;;;;;; = =?????A>>>>>>>>>@@@@@@@@@@@@@@@ BBB%%%%%%%%%%","222222222 ;;;;;;;;;; = =???AAA>>>>>>>>>@@@@@@@@@@@@@@ BBBBBB%%%%%","22C222222 ;;;;;;;;; ??AAAAA>>>>>>@@@@@@@@@@@@@@@@ BBBBBBBB%%%","CCCCC2222 222 ;;;;;;;;; =AAADD>>>>>>@@@@@@@@@@@@@@@ BBBBBBBBB","CCCCCCCCCC 222 ;;;;;;;; AADDD>>>>E@@@@@@@@@@@@@@@ BBBBBBBBB","CCCCCCCCCC 22 ;;;;;;;;; ADDD>EEEEE@@@@@@@@@@@@F@@ BBBBBBBBB","CCCCCCCCC 22 ;;;;;;;;;;;; DDDEEEEEEE@@@@@@@@@FFFFF FFFFFFFF BBBBBBBBB","CCCCCCC 2 ;;;;;;;;;; DDDEEEEEEE@@@G@@@@@GFFFFF FFFFFFFFFFFF BBBFBBBBB","CCCCCC ;;;;;;; DDDEEEEEEGGGGGGGGGGFFFFFFFF FFFFFFFFFFFFFFFF FFFFFFBBBBB"]'); + var compressed = zlib.deflate(input); + var output = zlib.inflate(compressed); + assert.deepEqual(input, output); +}; + +exports['test inflate #2'] = function(beforeExit) { + var compressed = new Buffer('\x78\x9c\xab\x56\x4a\x2f\xca\x4c\x51\xb2\x8a\x56\x52\xa0\x10\x28\xe9\x8c\x1a\x31\x6a\xc4\xa8\x11\xa3\x46\x8c\x1a\x31\x6a\xc4\xa8\x11\xa3\x46\x8c\x1a\x31\x6a\x04\x12\x50\x04\x02\x2a\x18\x01\x01\x64\x1b\x81\x64\x06\xdc\x10\xd2\x8c\x50\x44\x36\x02\x66\x06\x05\xae\x80\x99\x41\x72\x8c\x60\x9a\x41\x46\xa4\x0e\x0e\x23\x80\x81\xaa\x40\xa9\x11\x0a\x28\x46\x28\x52\xe6\x0a\x45\x0a\x8c\x40\x0e\x10\xf2\xb3\x19\x15\x8c\x80\x1b\x42\x69\x66\x57\x54\x54\xa6\xbc\xbc\xa0\x82\x11\x43\xb3\xe0\x1b\x42\x46\xa8\x50\xc1\x15\x2a\xa4\x1a\x42\xb9\x47\x54\x95\x62\x75\x94\xb2\x53\x2b\x8b\x41\x03\x19\x40\xe3\x7c\x23\x80\x84\x7b\x08\x90\xf0\x0e\x02\x12\xae\xce\x4a\xb1\xb5\x00\x83\x32\x27\xf3', 'binary'); + var output = zlib.inflate(compressed); + assert.equal(output.toString(), '{"grid":[" "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," !!!! "," !!!!!!!!!! "," !!!!!!!!!!! "," ! !!!!!!!!!!!! "," !!!!!!!!!!!!! "," !!!!!!!!!!!!! "," !!!!!!!!!!! "," !!!!!!!!!!! "," ! !!!!!!! "," !!!!!!! !"," ! !!!!!!!! !"," ! !!!!!!!!!!!"," !!!!!!!!!"," !!!!!!!"," !!#"," #"," "," "," "," "," "," "," $ "," $$ "," %"],"keys":["","MX","GT","KR","EC"]}'); +}; diff --git a/node_modules/zlib/test/inflate.test.js b/node_modules/zlib/test/inflate.test.js new file mode 100644 index 0000000..ebbc606 --- /dev/null +++ b/node_modules/zlib/test/inflate.test.js @@ -0,0 +1,33 @@ +var assert = require('assert'); +var Buffer = require('buffer').Buffer; +var zlib = require('../lib/zlib'); + +exports['test header inflate fail'] = function(beforeExit) { + var compressed = new Buffer('\x78\x80\x9c\xab\x56\x4a\x93\xaf\x46\x00\x1b\xa9\x02\x77\x92\x0f', 'binary'); + assert.throws(function() { var output = zlib.inflate(compressed); }, + "incorrect header check"); + + var compressed = new Buffer('\x78\x9c\xab\x56\x4a\x2f\xca\x4c\x51\xb2\x8a\x56\x52\xa0\x10\x28\xe9\x8c\x1a\x31\x6a\xc4\xa8\x11\xa3\x46\x8c\x1a\x31\x6a\xc4\xa8\x11\xa3\x46\x8c\x1a\x31\x6a\x04\x12\x50\x04\x02\x2a\x18\x01\x01\x64\x1b\x81\x64\x06\xdc\x10\xd2\x8c\x50\x44\x36\x02\x66\x06\x05\xae\x80\x99\x41\x72\x8c\x60\x9a\x41\x46\xa4\x0e\x0e\x23\x80\x81\xaa\x40\xa9\x11\x0a\x28\x46\x28\x52\xe6\x0a\x45\x0a\x8c\x40\x0e\x10\xf2\xb3\x19\x15\x8c\x80\x1b\x42\x69\x66\x57\x54\x54\xa6\xbc\xbc\xa0\x82\x11\x43\xb3\xe0\x1b\x42\x46\xa8\x50\xc1\x15\x2a\xa4\x1a\x42\xb9\x47\x54\x95\x62\x75\x94\xb2\x53\x2b\x8b\x41\x03\x19\x40\xe3\x7c\x23\x80\x84\x7b\x08\x90\xf0\x0e\x02\x12\xae\xce\x4a\xb1\xb5\x00\x83\x32\x27\xf3', 'binary'); + var output = zlib.inflate(compressed); + assert.equal(output.toString(), '{"grid":[" "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," !!!! "," !!!!!!!!!! "," !!!!!!!!!!! "," ! !!!!!!!!!!!! "," !!!!!!!!!!!!! "," !!!!!!!!!!!!! "," !!!!!!!!!!! "," !!!!!!!!!!! "," ! !!!!!!! "," !!!!!!! !"," ! !!!!!!!! !"," ! !!!!!!!!!!!"," !!!!!!!!!"," !!!!!!!"," !!#"," #"," "," "," "," "," "," "," $ "," $$ "," %"],"keys":["","MX","GT","KR","EC"]}'); +}; + +exports['test truncated inflate fail'] = function(beforeExit) { + var compressed = new Buffer('\x78\x9c\xab\x56\x4a\x2f\xca\x4c\x51\xb2\x8a\x56\x52\xa0\x10\x28\xe9\x8c\x1a\x31\x6a\xc4\xa8\x11\xa3\x46\x8c\x1a\x31\x6a\xc4\xa8\x11\xa3\x46\x8c\x1a\x31\x6a\x04\x12\x50\x04\x02\x2a\x18\x01\x01\x64\x1b\x81\x64\x06\xdc\x10\xd2\x8c\x50\x44\x36\x02\x66\x06\x05\xae\x80\x99\x41\x72\x8c\x60\x9a\x41\x46\xa4\x0e\x0e\x23\x80\x81\xaa\x40\xa9\x11\x0a\x28\x46\x28\x52\xe6\x0a\x45\x0a\x8c\x40\x0e\x10\xf2\xb3\x19\x15\x8c\x80\x1b\x42\x69\x66\x57\x54\x54\xa6', 'binary'); + var output = zlib.inflate(compressed); + assert.equal(output.toString(), '{"grid":[" "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," !!!! "," !!!!!!!!!! "," !!!!!!!!!!! "," ! !!!!!!!!!!!! "," !!!!!!!!!!!!! "," !!!!!!!!!!!!! "," !!!!!!!!!!! "," !!!!!!!!!!! "," ! !!!!!!! "," !!!!!!! !"," ! !!!!!!!! !"," ! !!!!!!!!!!!"," !!!!!!!!!"," !!!!!!!"," !!#'); + + var compressed = new Buffer('\x78\x9c\xab\x56\x4a\x2f\xca\x4c\x51\xb2\x8a\x56\x52\xa0\x10\x28\xe9\x8c\x1a\x31\x6a\xc4\xa8\x11\xa3\x46\x8c\x1a\x31\x6a\xc4\xa8\x11\xa3\x46\x8c\x1a\x31\x6a\x04\x12\x50\x04\x02\x2a\x18\x01\x01\x64\x1b\x81\x64\x06\xdc\x10\xd2\x8c\x50\x44\x36\x02\x66\x06\x05\xae\x80\x99\x41\x72\x8c\x60\x9a\x41\x46\xa4\x0e\x0e\x23\x80\x81\xaa\x40\xa9\x11\x0a\x28\x46\x28\x52\xe6\x0a\x45\x0a\x8c\x40\x0e\x10\xf2\xb3\x19\x15\x8c\x80\x1b\x42\x69\x66\x57\x54\x54\xa6\xbc\xbc\xa0\x82\x11\x43\xb3\xe0\x1b\x42\x46\xa8\x50\xc1\x15\x2a\xa4\x1a\x42\xb9\x47\x54\x95\x62\x75\x94\xb2\x53\x2b\x8b\x41\x03\x19\x40\xe3\x7c\x23\x80\x84\x7b\x08\x90\xf0\x0e\x02\x12\xae\xce\x4a\xb1\xb5\x00\x83\x32\x27\xf3', 'binary'); + var output = zlib.inflate(compressed); + assert.equal(output.toString(), '{"grid":[" "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," !!!! "," !!!!!!!!!! "," !!!!!!!!!!! "," ! !!!!!!!!!!!! "," !!!!!!!!!!!!! "," !!!!!!!!!!!!! "," !!!!!!!!!!! "," !!!!!!!!!!! "," ! !!!!!!! "," !!!!!!! !"," ! !!!!!!!! !"," ! !!!!!!!!!!!"," !!!!!!!!!"," !!!!!!!"," !!#"," #"," "," "," "," "," "," "," $ "," $$ "," %"],"keys":["","MX","GT","KR","EC"]}'); +}; + +exports['test bogus inflate fail'] = function(beforeExit) { + var compressed = new Buffer('bahbahfoobar', 'binary'); + assert.throws(function() { var output = zlib.inflate(compressed); }, + "incorrect header check"); + + var compressed = new Buffer('\x78\x9c\xab\x56\x4a\x2f\xca\x4c\x51\xb2\x8a\x56\x52\xa0\x10\x28\xe9\x8c\x1a\x31\x6a\xc4\xa8\x11\xa3\x46\x8c\x1a\x31\x6a\xc4\xa8\x11\xa3\x46\x8c\x1a\x31\x6a\x04\x12\x50\x04\x02\x2a\x18\x01\x01\x64\x1b\x81\x64\x06\xdc\x10\xd2\x8c\x50\x44\x36\x02\x66\x06\x05\xae\x80\x99\x41\x72\x8c\x60\x9a\x41\x46\xa4\x0e\x0e\x23\x80\x81\xaa\x40\xa9\x11\x0a\x28\x46\x28\x52\xe6\x0a\x45\x0a\x8c\x40\x0e\x10\xf2\xb3\x19\x15\x8c\x80\x1b\x42\x69\x66\x57\x54\x54\xa6\xbc\xbc\xa0\x82\x11\x43\xb3\xe0\x1b\x42\x46\xa8\x50\xc1\x15\x2a\xa4\x1a\x42\xb9\x47\x54\x95\x62\x75\x94\xb2\x53\x2b\x8b\x41\x03\x19\x40\xe3\x7c\x23\x80\x84\x7b\x08\x90\xf0\x0e\x02\x12\xae\xce\x4a\xb1\xb5\x00\x83\x32\x27\xf3', 'binary'); + var output = zlib.inflate(compressed); + assert.equal(output.toString(), '{"grid":[" "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," !!!! "," !!!!!!!!!! "," !!!!!!!!!!! "," ! !!!!!!!!!!!! "," !!!!!!!!!!!!! "," !!!!!!!!!!!!! "," !!!!!!!!!!! "," !!!!!!!!!!! "," ! !!!!!!! "," !!!!!!! !"," ! !!!!!!!! !"," ! !!!!!!!!!!!"," !!!!!!!!!"," !!!!!!!"," !!#"," #"," "," "," "," "," "," "," $ "," $$ "," %"],"keys":["","MX","GT","KR","EC"]}'); +}; diff --git a/node_modules/zlib/wscript b/node_modules/zlib/wscript new file mode 100644 index 0000000..ad3919c --- /dev/null +++ b/node_modules/zlib/wscript @@ -0,0 +1,38 @@ +import os +import Options +from os.path import exists +from shutil import copy2 as copy + +TARGET = 'zlib_bindings' +TARGET_FILE = '%s.node' % TARGET +built = 'build/default/%s' % TARGET_FILE +dest = 'lib/%s' % TARGET_FILE + +def set_options(opt): + opt.tool_options("compiler_cxx") + +def configure(conf): + conf.check_tool("compiler_cxx") + conf.check_tool("node_addon") + if not conf.check(lib="z", libpath=['/usr/local/lib'], uselib_store="ZLIB"): + conf.fatal('Missing zlib'); + + linkflags = [] + if os.environ.has_key('LINKFLAGS'): + linkflags.extend(os.environ['LINKFLAGS'].split(' ')) + conf.env.append_value("LINKFLAGS", linkflags) + +def build(bld): + obj = bld.new_task_gen("cxx", "shlib", "node_addon") + obj.cxxflags = ["-g", "-D_FILE_OFFSET_BITS=64", "-D_LARGEFILE_SOURCE", "-Wall"] + obj.target = TARGET + obj.source = "src/node-zlib.cc" + obj.uselib = "ZLIB" + +def shutdown(): + if Options.commands['clean']: + if exists(TARGET_FILE): + unlink(TARGET_FILE) + else: + if exists(built): + copy(built, dest) \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..c42d473 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,121 @@ +{ + "name": "web-deploy", + "version": "0.0.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "web-deploy", + "version": "0.0.1", + "license": "ISC", + "dependencies": { + "@minify-html/node": "^0.15.0", + "@putout/minify": "^3.8.5", + "clean-css": "^5.3.3", + "uglify-js": "^3.17.4", + "zlib": "^1.0.5" + } + }, + "node_modules/@minify-html/node": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@minify-html/node/-/node-0.15.0.tgz", + "integrity": "sha512-ANzt6ZBiqtwrepVXRfa0Qn/woCkINFBjQEKiXyBmg7+51mIFQHVAUbAm6UHRrT0L3xoPG0BX0/XI3NqtjK8Vyg==", + "bin": { + "minify-html": "cli.js" + }, + "engines": { + "node": ">= 8.6.0" + }, + "optionalDependencies": { + "@minify-html/node-darwin-arm64": "0.15.0", + "@minify-html/node-darwin-x64": "0.15.0", + "@minify-html/node-linux-arm64": "0.15.0", + "@minify-html/node-linux-x64": "0.15.0", + "@minify-html/node-win32-x64": "0.15.0" + } + }, + "node_modules/@minify-html/node-darwin-x64": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@minify-html/node-darwin-x64/-/node-darwin-x64-0.15.0.tgz", + "integrity": "sha512-D9M9UDku/8I5VEMS0gTLFFQK1DFXK8io+QZvR5cbya4u8NmdDQix/t3EyCR4Wgv/Gfk86gwIS+zfMSvuKcpb5A==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@minify-html/node-linux-x64": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@minify-html/node-linux-x64/-/node-linux-x64-0.15.0.tgz", + "integrity": "sha512-cO893EV6O9ZHUFX+2Yge546OCo/eCiatjzJDmUmrPP56fQ7pzTRquHs4ko3t8Rg6tMKG7RT49mBuF09JWPnrgg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@minify-html/node-win32-x64": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@minify-html/node-win32-x64/-/node-win32-x64-0.15.0.tgz", + "integrity": "sha512-n92IFdtntchlUtyrq13pRI8TT3sOddbzuo4EPTSeocuTJMXaR77v0JYDu0fIjxXNawgGq6nBEeicxAcH4CbvUQ==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@putout/minify": { + "version": "3.8.5", + "resolved": "https://registry.npmjs.org/@putout/minify/-/minify-3.8.5.tgz", + "integrity": "sha512-m7Umg719m9kqcq7kV6RXtoRZZyUKn1YQOExfpgbHCYCJvwHPR2J/lADtgtkCFZslUKIyqSsjYUmQeKqDGJpXDg==", + "engines": { + "node": ">=18" + } + }, + "node_modules/clean-css": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/clean-css/-/clean-css-5.3.3.tgz", + "integrity": "sha512-D5J+kHaVb/wKSFcyyV75uCn8fiY4sV38XJoe4CUyGQ+mOU/fMVYUdH1hJC+CJQ5uY3EnW27SbJYS4X8BiLrAFg==", + "dependencies": { + "source-map": "~0.6.0" + }, + "engines": { + "node": ">= 10.0" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/uglify-js": { + "version": "3.17.4", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.17.4.tgz", + "integrity": "sha512-T9q82TJI9e/C1TAxYvfb16xO120tMVFZrGA3f9/P4424DNu6ypK103y0GPFVa17yotwSyZW5iYXgjYHkGrJW/g==", + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/zlib": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/zlib/-/zlib-1.0.5.tgz", + "integrity": "sha512-40fpE2II+Cd3k8HWTWONfeKE2jL+P42iWJ1zzps5W51qcTsOUKM5Q5m2PFb0CLxlmFAaUuUdJGc3OfZy947v0w==", + "hasInstallScript": true, + "engines": { + "node": ">=0.2.0" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..4e53533 --- /dev/null +++ b/package.json @@ -0,0 +1,25 @@ +{ + "name": "web-deploy", + "version": "0.0.1", + "description": "Minify and compress files for the web", + "main": "process.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/git.fjla.uk/web-deploy.git" + }, + "author": "Frederick Boniface", + "license": "ISC", + "bugs": { + "url": "https://github.com/git.fjla.uk/web-deploy/issues" + }, + "homepage": "https://github.com/git.fjla.uk/web-deploy#readme", + "dependencies": { + "@minify-html/node": "^0.15.0", + "clean-css": "^5.3.3", + "uglify-js": "^3.17.4", + "zlib": "^1.0.5" + } +} diff --git a/process.js b/process.js new file mode 100644 index 0000000..a4711f8 --- /dev/null +++ b/process.js @@ -0,0 +1,123 @@ +const MinifyHTML = require('@minify-html/node') +const UglifyJS = require('uglify-js') +const CleanCss = require('clean-css') +const Zlib = require('zlib') +const fs = require('fs') +const path = require('path') + +const input_dir = "/deploy/in" +const output_dir = "/deploy/out" + +function ensureDirectoryExists(file_path) { + const file_dir = path.dirname(file_path) + if (!fs.existsSync(file_dir)) { + fs.mkdirSync(file_dir) + } +} + +function minifyHtml(input_file, output_file) { + const opts = {keep_spaces_between_attributes: true, keep_comments: true} + const minified = MinifyHTML.minify(fs.readFileSync(input_file), opts) + ensureDirectoryExists(output_file) + fs.writeFileSync(output_file, minified) +} + +function minifyCss(input_file, output_file) { + input = fs.readFileSync(input_file) + const output = new CleanCss().minify(input) + fs.writeFileSync(output_file, output.styles) +} + +function minifyJs(input_file, output_file) { + const input = fs.readFileSync(input_file, 'utf8') + const minified = UglifyJS.minify(input) + fs.writeFileSync(output_file, minified.code, 'utf8') +} + +function minifyJson(input_file, output_file) { + const json = fs.readFileSync(input_file, 'utf8') + const parsed = JSON.parse(json) + const minified = JSON.stringify(parsed) + fs.writeFileSync(output_file, minified, 'utf8') +} + +function minifyXml(input_file, output_file) { + // Not yet available +} + +function compressGzip(input_path, output_path) { + const input = fs.createReadStream(input_path) + const gzip = Zlib.createGzip() + const output = fs.createWriteStream(output_path) + input.pipe(gzip).pipe(output) + output.on('finish', () => { + return + }) +} + +function compressBrotli(input_path, output_path) { + const input = fs.createReadStream(input_path) + const brotli = Zlib.createBrotliCompress() + const output = fs.createWriteStream(output_path) + input.pipe(brotli).pipe(output) + output.on('finish', () => { + return + }) +} + +processable_extentions = ['.html', '.css', '.js', '.json', '.xml', '.log', '.md', '.svg', '.wasm', '.yaml', '.yml', '.vcard', '.ical'] + +// Loop over file and subdirectories + +function processFiles(inputDir, outputDir) { + fs.readdirSync(inputDir).forEach(file => { + const inputFile = path.join(inputDir, file); + const outputFile = path.join(outputDir, file); + + if (fs.statSync(inputFile).isDirectory()) { + const nestedOutputDir = path.join(outputDir, file); + fs.mkdirSync(nestedOutputDir, { recursive: true }); + processFiles(inputFile, nestedOutputDir); // Recursive call with nested input and output directories + } else { + const extension = path.extname(file).toLowerCase(); + switch (extension) { + case '.html': + minifyHtml(inputFile, outputFile); + break; + case '.css': + minifyCss(inputFile, outputFile); + break; + case '.js': + minifyJs(inputFile, outputFile); + break; + case '.json': + minifyJson(inputFile, outputFile); + break; + case '.xml': + minifyXml(inputFile, outputFile); + break; + default: + fs.copyFileSync(inputFile, outputFile); + } + } + }); +} + +function compressFiles(directory) { + fs.readdirSync(directory).forEach(file => { + const file_path = path.join(directory, file); + + if (fs.statSync(file_path).isDirectory()) { + compressFiles(file_path); + } else { + const extension = path.extname(file).toLowerCase(); + if (processable_extentions.includes(extension)) { + compressGzip(file_path, file_path + '.gz'); + compressBrotli(file_path, file_path + '.br'); + } + } + }); +} + +processFiles(input_dir, output_dir); +compressFiles(output_dir); \ No newline at end of file diff --git a/test.dockerfile b/test.dockerfile new file mode 100644 index 0000000..6be0b74 --- /dev/null +++ b/test.dockerfile @@ -0,0 +1,10 @@ +FROM ubuntu:22.04 +RUN apt update \ + && apt install -y nodejs npm \ + && apt clean +WORKDIR /app +COPY package* ./ +RUN npm i +COPY process.js ./ +COPY test_input/ /deploy/in/ +RUN node process.js diff --git a/test_input/json/test.json b/test_input/json/test.json new file mode 100644 index 0000000..f486a93 --- /dev/null +++ b/test_input/json/test.json @@ -0,0 +1,6 @@ +{ + "userId": 1, + "id": 1, + "title": "delectus aut autem", + "completed": false + } \ No newline at end of file diff --git a/test_input/test.css b/test_input/test.css new file mode 100644 index 0000000..b7bb2c5 --- /dev/null +++ b/test_input/test.css @@ -0,0 +1,4 @@ +th { + width: 100; + height: 1000; +} \ No newline at end of file diff --git a/test_input/test.html b/test_input/test.html new file mode 100644 index 0000000..4579945 --- /dev/null +++ b/test_input/test.html @@ -0,0 +1,13 @@ + + + + test-file + + +

    This

    +

    Is

    +

    A

    +

    Test

    +
    file
    + + \ No newline at end of file diff --git a/test_input/test.js b/test_input/test.js new file mode 100644 index 0000000..7b70934 --- /dev/null +++ b/test_input/test.js @@ -0,0 +1,8 @@ +function myFunction() { + document.getElementById("demo").innerHTML = "Paragraph changed."; + } + +async function logger() { + console.log("hello, how're you today"); + console.error("ERR MSG"); +} \ No newline at end of file