progress on migrating to heex templates and font-icons

This commit is contained in:
Adam Piontek 2022-08-13 07:32:36 -04:00
parent d43daafdb7
commit 3eff955672
21793 changed files with 2161968 additions and 16895 deletions

404
assets_old/node_modules/terser/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,404 @@
# Changelog
## v5.6.1
- Mark assignments to the `.prototype` of a class as pure
- Parenthesize `await` on the left of `**` (while accepting legacy non-parenthesised input)
- Avoided outputting NUL bytes in optimized RegExps, to stop the output from breaking other tools
- Added `exports` to domprops (#939)
- Fixed a crash when spreading `...this`
- Fixed the computed size of arrow functions, which improves their inlining
## v5.6.0
- Added top-level await
- Beautify option has been removed in #895
- Private properties, getters and setters have been added in #913 and some more commits
- Docs improvements: #896, #903, #916
## v5.5.1
- Fixed object properties with unicode surrogates on safari.
## v5.5.0
- Fixed crash when inlining uninitialized variable into template string.
- The sourcemap for dist was removed for being too large.
## v5.4.0
- Logical assignment
- Change `let x = undefined` to just `let x`
- Removed some optimizations for template strings, placing them behind `unsafe` options. Reason: adding strings is not equivalent to template strings, due to valueOf differences.
- The AST_Token class was slimmed down in order to use less memory.
## v5.3.8
- Restore node 13 support
## v5.3.7
Hotfix release, fixes package.json "engines" syntax
## v5.3.6
- Fixed parentheses when outputting `??` mixed with `||` and `&&`
- Improved hygiene of the symbol generator
## v5.3.5
- Avoid moving named functions into default exports.
- Enabled transform() for chain expressions. This allows AST transformers to reach inside chain expressions.
## v5.3.4
- Fixed a crash when hoisting (with `hoist_vars`) a destructuring variable declaration
## v5.3.3
- `source-map` library has been updated, bringing memory usage and CPU time improvements when reading input source maps (the SourceMapConsumer is now WASM based).
- The `wrap_func_args` option now also wraps arrow functions, as opposed to only function expressions.
## v5.3.2
- Prevented spread operations from being expanded when the expanded array/object contains getters, setters, or array holes.
- Fixed _very_ slow self-recursion in some cases of removing extraneous parentheses from `+` operations.
## v5.3.1
- An issue with destructuring declarations when `pure_getters` is enabled has been fixed
- Fixed a crash when chain expressions need to be shallowly compared
- Made inlining functions more conservative to make sure a function that contains a reference to itself isn't moved into a place that can create multiple instances of itself.
## v5.3.0
- Fixed a crash when compressing object spreads in some cases
- Fixed compiletime evaluation of optional chains (caused typeof a?.b to always return "object")
- domprops has been updated to contain every single possible prop
## v5.2.1
- The parse step now doesn't accept an `ecma` option, so that all ES code is accepted.
- Optional dotted chains now accept keywords, just like dotted expressions (`foo?.default`)
## v5.2.0
- Optional chaining syntax is now supported.
- Consecutive await expressions don't have unnecessary parens
- Taking the variable name's length (after mangling) into consideration when deciding to inline
## v5.1.0
- `import.meta` is now supported
- Typescript typings have been improved
## v5.0.0
- `in` operator now taken into account during property mangle.
- Fixed infinite loop in face of a reference loop in some situations.
- Kept exports and imports around even if there's something which will throw before them.
- The main exported bundle for commonjs, dist/bundle.min.js is no longer minified.
## v5.0.0-beta.0
- BREAKING: `minify()` is now async and rejects a promise instead of returning an error.
- BREAKING: Internal AST is no longer exposed, so that it can be improved without releasing breaking changes.
- BREAKING: Lowest supported node version is 10
- BREAKING: There are no more warnings being emitted
- Module is now distributed as a dual package - You can `import` and `require()` too.
- Inline improvements were made
## v4.8.0
- Support for numeric separators (`million = 1_000_000`) was added.
- Assigning properties to a class is now assumed to be pure.
- Fixed bug where `yield` wasn't considered a valid property key in generators.
## v4.7.0
- A bug was fixed where an arrow function would have the wrong size
- `arguments` object is now considered safe to retrieve properties from (useful for `length`, or `0`) even when `pure_getters` is not set.
- Fixed erroneous `const` declarations without value (which is invalid) in some corner cases when using `collapse_vars`.
## v4.6.13
- Fixed issue where ES5 object properties were being turned into ES6 object properties due to more lax unicode rules.
- Fixed parsing of BigInt with lowercase `e` in them.
## v4.6.12
- Fixed subtree comparison code, making it see that `[1,[2, 3]]` is different from `[1, 2, [3]]`
- Printing of unicode identifiers has been improved
## v4.6.11
- Read unused classes' properties and method keys, to figure out if they use other variables.
- Prevent inlining into block scopes when there are name collisions
- Functions are no longer inlined into parameter defaults, because they live in their own special scope.
- When inlining identity functions, take into account the fact they may be used to drop `this` in function calls.
- Nullish coalescing operator (`x ?? y`), plus basic optimization for it.
- Template literals in binary expressions such as `+` have been further optimized
## v4.6.10
- Do not use reduce_vars when classes are present
## v4.6.9
- Check if block scopes actually exist in blocks
## v4.6.8
- Take into account "executed bits" of classes like static properties or computed keys, when checking if a class evaluation might throw or have side effects.
## v4.6.7
- Some new performance gains through a `AST_Node.size()` method which measures a node's source code length without printing it to a string first.
- An issue with setting `--comments` to `false` in the CLI has been fixed.
- Fixed some issues with inlining
- `unsafe_symbols` compress option was added, which turns `Symbol("name")` into just `Symbol()`
- Brought back compress performance improvement through the `AST_Node.equivalent_to(other)` method (which was reverted in v4.6.6).
## v4.6.6
(hotfix release)
- Reverted code to 4.6.4 to allow for more time to investigate an issue.
## v4.6.5 (REVERTED)
- Improved compress performance through using a new method to see if two nodes are equivalent, instead of printing them to a string.
## v4.6.4
- The `"some"` value in the `comments` output option now preserves `@lic` and other important comments when using `//`
- `</script>` is now better escaped in regex, and in comments, when using the `inline_script` output option
- Fixed an issue when transforming `new RegExp` into `/.../` when slashes are included in the source
- `AST_Node.prototype.constructor` now exists, allowing for easier debugging of crashes
- Multiple if statements with the same consequents are now collapsed
- Typescript typings improvements
- Optimizations while looking for surrogate pairs in strings
## v4.6.3
- Annotations such as `/*#__NOINLINE__*/` and `/*#__PURE__*/` may now be preserved using the `preserve_annotations` output option
- A TypeScript definition update for the `keep_quoted` output option.
## v4.6.2
- A bug where functions were inlined into other functions with scope conflicts has been fixed.
- `/*#__NOINLINE__*/` annotation fixed for more use cases where inlining happens.
## v4.6.1
- Fixed an issue where a class is duplicated by reduce_vars when there's a recursive reference to the class.
## v4.6.0
- Fixed issues with recursive class references.
- BigInt evaluation has been prevented, stopping Terser from evaluating BigInts like it would do regular numbers.
- Class property support has been added
## v4.5.1
(hotfix release)
- Fixed issue where `() => ({})[something]` was not parenthesised correctly.
## v4.5.0
- Inlining has been improved
- An issue where keep_fnames combined with functions declared through variables was causing name shadowing has been fixed
- You can now set the ES version through their year
- The output option `keep_numbers` has been added, which prevents Terser from turning `1000` into `1e3` and such
- Internal small optimisations and refactors
## v4.4.3
- Number and BigInt parsing has been fixed
- `/*#__INLINE__*/` annotation fixed for arrow functions with non-block bodies.
- Functional tests have been added, using [this repository](https://github.com/terser/terser-functional-tests).
- A memory leak, where the entire AST lives on after compression, has been plugged.
## v4.4.2
- Fixed a problem with inlining identity functions
## v4.4.1
*note:* This introduced a feature, therefore it should have been a minor release.
- Fixed a crash when `unsafe` was enabled.
- An issue has been fixed where `let` statements might be collapsed out of their scope.
- Some error messages have been improved by adding quotes around variable names.
## v4.4.0
- Added `/*#__INLINE__*/` and `/*#__NOINLINE__*/` annotations for calls. If a call has one of these, it either forces or forbids inlining.
## v4.3.11
- Fixed a problem where `window` was considered safe to access, even though there are situations where it isn't (Node.js, workers...)
- Fixed an error where `++` and `--` were considered side-effect free
- `Number(x)` now needs both `unsafe` and and `unsafe_math` to be compressed into `+x` because `x` might be a `BigInt`
- `keep_fnames` now correctly supports regexes when the function is in a variable declaration
## v4.3.10
- Fixed syntax error when repeated semicolons were encountered in classes
- Fixed invalid output caused by the creation of empty sequences internally
- Scopes are now updated when scopes are inlined into them
## v4.3.9
- Fixed issue with mangle's `keep_fnames` option, introduced when adding code to keep variable names of anonymous functions
## v4.3.8
- Typescript typings fix
## v4.3.7
- Parsing of regex options in the CLI (which broke in v4.3.5) was fixed.
- typescript definition updates
## v4.3.6
(crash hotfix)
## v4.3.5
- Fixed an issue with DOS line endings strings separated by `\` and a new line.
- Improved fix for the output size regression related to unused references within the extends section of a class.
- Variable names of anonymous functions (eg: `const x = () => { ... }` or `var func = function () {...}`) are now preserved when keep_fnames is true.
- Fixed performance degradation introduced for large payloads in v4.2.0
## v4.3.4
- Fixed a regression where the output size was increased when unused classes were referred to in the extends clause of a class.
- Small typescript typings fixes.
- Comments with `@preserve`, `@license`, `@cc_on` as well as comments starting with `/*!` and `/**!` are now preserved by default.
## v4.3.3
- Fixed a problem where parsing template strings would mix up octal notation and a slash followed by a zero representing a null character.
- Started accepting the name `async` in destructuring arguments with default value.
- Now Terser takes into account side effects inside class `extends` clauses.
- Added parens whenever there's a comment between a return statement and the returned value, to prevent issues with ASI.
- Stopped using raw RegExp objects, since the spec is going to continue to evolve. This ensures Terser is able to process new, unknown RegExp flags and features. This is a breaking change in the AST node AST_RegExp.
## v4.3.2
- Typescript typing fix
- Ensure that functions can't be inlined, by reduce_vars, into places where they're accessing variables with the same name, but from somewhere else.
## v4.3.1
- Fixed an issue from 4.3.0 where any block scope within a for loop erroneously had its parent set to the function scopee
- Fixed an issue where compressing IIFEs with argument expansions would result in some parameters becoming undefined
- addEventListener options argument's properties are now part of the DOM properties list.
## v4.3.0
- Do not drop computed object keys with side effects
- Functions passed to other functions in calls are now wrapped in parentheses by default, which speeds up loading most modules
- Objects with computed properties are now less likely to be hoisted
- Speed and memory efficiency optimizations
- Fixed scoping issues with `try` and `switch`
## v4.2.1
- Minor refactors
- Fixed a bug similar to #369 in collapse_vars
- Functions can no longer be inlined into a place where they're going to be compared with themselves.
- reduce_funcs option is now legacy, as using reduce_vars without reduce_funcs caused some weird corner cases. As a result, it is now implied in reduce_vars and can't be turned off without turning off reduce_vars.
- Bug which would cause a random stack overflow has now been fixed.
## v4.2.0
- When the source map URL is `inline`, don't write it to a file.
- Fixed output parens when a lambda literal is the tag on a tagged template string.
- The `mangle.properties.undeclared` option was added. This enables the property mangler to mangle properties of variables which can be found in the name cache, but whose properties are not known to this Terser run.
- The v8 bug where the toString and source representations of regexes like `RegExp("\\\n")` includes an actual newline is now fixed.
- Now we're guaranteed to not have duplicate comments in the output
- Domprops updates
## v4.1.4
- Fixed a crash when inlining a function into somewhere else when it has interdependent, non-removable variables.
## v4.1.3
- Several issues with the `reduce_vars` option were fixed.
- Starting this version, we only have a dist/bundle.min.js
## v4.1.2
- The hotfix was hotfixed
## v4.1.1
- Fixed a bug where toplevel scopes were being mixed up with lambda scopes
## v4.1.0
- Internal functions were replaced by `Object.assign`, `Array.prototype.some`, `Array.prototype.find` and `Array.prototype.every`.
- A serious issue where some ESM-native code was broken was fixed.
- Performance improvements were made.
- Support for BigInt was added.
- Inline efficiency was improved. Functions are now being inlined more proactively instead of being inlined only after another Compressor pass.
## v4.0.2
(Hotfix release. Reverts unmapped segments PR [#342](https://github.com/terser/terser/pull/342), which will be put back on Terser when the upstream issue is resolved)
## v4.0.1
- Collisions between the arguments of inlined functions and names in the outer scope are now being avoided while inlining
- Unmapped segments are now preserved when compressing a file which has source maps
- Default values of functions are now correctly converted from Mozilla AST to Terser AST
- JSON ⊂ ECMAScript spec (if you don't know what this is you don't need to)
- Export AST_* classes to library users
- Fixed issue with `collapse_vars` when functions are created with the same name as a variable which already exists
- Added `MutationObserverInit` (Object with options for initialising a mutation observer) properties to the DOM property list
- Custom `Error` subclasses are now internally used instead of old-school Error inheritance hacks.
- Documentation fixes
- Performance optimizations
## v4.0.0
- **breaking change**: The `variables` property of all scopes has become a standard JavaScript `Map` as opposed to the old bespoke `Dictionary` object.
- Typescript definitions were fixed
- `terser --help` was fixed
- The public interface was cleaned up
- Fixed optimisation of `Array` and `new Array`
- Added the `keep_quoted=strict` mode to mangle_props, which behaves more like Google Closure Compiler by mangling all unquoted property names, instead of reserving quoted property names automatically.
- Fixed parent functions' parameters being shadowed in some cases
- Allowed Terser to run in a situation where there are custom functions attached to Object.prototype
- And more bug fixes, optimisations and internal changes
## v3.17.0
- More DOM properties added to --mangle-properties's DOM property list
- Closed issue where if 2 functions had the same argument name, Terser would not inline them together properly
- Fixed issue with `hasOwnProperty.call`
- You can now list files to minify in a Terser config file
- Started replacing `new Array(<number>)` with an array literal
- Started using ES6 capabilities like `Set` and the `includes` method for strings and arrays
## v3.16.1
- Fixed issue where Terser being imported with `import` would cause it not to work due to the `__esModule` property. (PR #254 was submitted, which was nice, but since it wasn't a pure commonJS approach I decided to go with my own solution)
## v3.16.0
- No longer leaves names like Array or Object or window as a SimpleStatement (statement which is just a single expression).
- Add support for sections sourcemaps (IndexedSourceMapConsumer)
- Drops node.js v4 and starts using commonJS
- Is now built with rollup
## v3.15.0
- Inlined spread syntax (`[...[1, 2, 3], 4, 5] => [1, 2, 3, 4, 5]`) in arrays and objects.
- Fixed typo in compressor warning
- Fixed inline source map input bug
- Fixed parsing of template literals with unnecessary escapes (Like `\\a`)

29
assets_old/node_modules/terser/LICENSE generated vendored Normal file
View file

@ -0,0 +1,29 @@
Terser is released under the BSD license:
Copyright 2012-2018 (c) Mihai Bazon <mihai.bazon@gmail.com>
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.

15
assets_old/node_modules/terser/PATRONS.md generated vendored Normal file
View file

@ -0,0 +1,15 @@
# Our patrons
These are the first-tier patrons from [Patreon](https://www.patreon.com/fabiosantoscode). My appreciation goes to everyone on this list for supporting the project!
* 38elements
* Alan Orozco
* Aria Buckles
* CKEditor
* Mariusz Nowak
* Nakshatra Mukhopadhyay
* Philippe Léger
* Piotrek Koszuliński
* Serhiy Shyyko
* Viktor Hubert
* 龙腾道

1327
assets_old/node_modules/terser/README.md generated vendored Normal file

File diff suppressed because it is too large Load diff

10
assets_old/node_modules/terser/bin/package.json generated vendored Normal file
View file

@ -0,0 +1,10 @@
{
"name": "bin",
"private": true,
"version": "1.0.0",
"main": "terser",
"type": "commonjs",
"author": "",
"license": "BSD-2-Clause",
"description": "A package to hold the Terser bin bundle as commonjs while keeping the rest of it ESM."
}

21
assets_old/node_modules/terser/bin/terser generated vendored Executable file
View file

@ -0,0 +1,21 @@
#!/usr/bin/env node
"use strict";
require("../tools/exit.cjs");
try {
require("source-map-support").install();
} catch (err) {}
const fs = require("fs");
const path = require("path");
const program = require("commander");
const packageJson = require("../package.json");
const { _run_cli: run_cli } = require("..");
run_cli({ program, packageJson, fs, path }).catch((error) => {
console.error(error);
process.exitCode = 1;
});

21
assets_old/node_modules/terser/bin/terser.mjs generated vendored Executable file
View file

@ -0,0 +1,21 @@
#!/usr/bin/env node
"use strict";
import "../tools/exit.cjs";
import fs from "fs"
import path from "path"
import program from "commander"
import { run_cli } from "../lib/cli.js"
const packageJson = {
name: "terser",
version: "experimental module CLI"
}
run_cli({ program, packageJson, fs, path }).catch((error) => {
console.error(error);
process.exitCode = 1;
});

10
assets_old/node_modules/terser/bin/uglifyjs generated vendored Executable file
View file

@ -0,0 +1,10 @@
#!/usr/bin/env node
// -*- js -*-
/* eslint-env node */
"use strict";
process.stderr.write( "DEPRECATION WARNING: uglifyjs binary will soon be discontinued!\n");
process.stderr.write("Please use \"terser\" instead.\n\n");
require("./terser");

0
assets_old/node_modules/terser/dist/.gitkeep generated vendored Normal file
View file

27099
assets_old/node_modules/terser/dist/bundle.min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

10
assets_old/node_modules/terser/dist/package.json generated vendored Normal file
View file

@ -0,0 +1,10 @@
{
"name": "dist",
"private": true,
"version": "1.0.0",
"main": "bundle.min.js",
"type": "commonjs",
"author": "",
"license": "BSD-2-Clause",
"description": "A package to hold the Terser dist bundle as commonjs while keeping the rest of it ESM. Nothing to see here."
}

1850
assets_old/node_modules/terser/lib/ast.js generated vendored Normal file

File diff suppressed because it is too large Load diff

477
assets_old/node_modules/terser/lib/cli.js generated vendored Normal file
View file

@ -0,0 +1,477 @@
import { minify, _default_options } from "../main.js";
import { parse } from "./parse.js";
import {
AST_Assign,
AST_Array,
AST_Constant,
AST_Node,
AST_PropAccess,
AST_RegExp,
AST_Sequence,
AST_Symbol,
AST_Token,
walk
} from "./ast.js";
import { OutputStream } from "./output.js";
export async function run_cli({ program, packageJson, fs, path }) {
const skip_keys = new Set([ "cname", "parent_scope", "scope", "uses_eval", "uses_with" ]);
var files = {};
var options = {
compress: false,
mangle: false
};
const default_options = await _default_options();
program.version(packageJson.name + " " + packageJson.version);
program.parseArgv = program.parse;
program.parse = undefined;
if (process.argv.includes("ast")) program.helpInformation = describe_ast;
else if (process.argv.includes("options")) program.helpInformation = function() {
var text = [];
for (var option in default_options) {
text.push("--" + (option === "sourceMap" ? "source-map" : option) + " options:");
text.push(format_object(default_options[option]));
text.push("");
}
return text.join("\n");
};
program.option("-p, --parse <options>", "Specify parser options.", parse_js());
program.option("-c, --compress [options]", "Enable compressor/specify compressor options.", parse_js());
program.option("-m, --mangle [options]", "Mangle names/specify mangler options.", parse_js());
program.option("--mangle-props [options]", "Mangle properties/specify mangler options.", parse_js());
program.option("-f, --format [options]", "Format options.", parse_js());
program.option("-b, --beautify [options]", "Alias for --format.", parse_js());
program.option("-o, --output <file>", "Output file (default STDOUT).");
program.option("--comments [filter]", "Preserve copyright comments in the output.");
program.option("--config-file <file>", "Read minify() options from JSON file.");
program.option("-d, --define <expr>[=value]", "Global definitions.", parse_js("define"));
program.option("--ecma <version>", "Specify ECMAScript release: 5, 2015, 2016 or 2017...");
program.option("-e, --enclose [arg[,...][:value[,...]]]", "Embed output in a big function with configurable arguments and values.");
program.option("--ie8", "Support non-standard Internet Explorer 8.");
program.option("--keep-classnames", "Do not mangle/drop class names.");
program.option("--keep-fnames", "Do not mangle/drop function names. Useful for code relying on Function.prototype.name.");
program.option("--module", "Input is an ES6 module");
program.option("--name-cache <file>", "File to hold mangled name mappings.");
program.option("--rename", "Force symbol expansion.");
program.option("--no-rename", "Disable symbol expansion.");
program.option("--safari10", "Support non-standard Safari 10.");
program.option("--source-map [options]", "Enable source map/specify source map options.", parse_js());
program.option("--timings", "Display operations run time on STDERR.");
program.option("--toplevel", "Compress and/or mangle variables in toplevel scope.");
program.option("--wrap <name>", "Embed everything as a function with “exports” corresponding to “name” globally.");
program.arguments("[files...]").parseArgv(process.argv);
if (program.configFile) {
options = JSON.parse(read_file(program.configFile));
}
if (!program.output && program.sourceMap && program.sourceMap.url != "inline") {
fatal("ERROR: cannot write source map to STDOUT");
}
[
"compress",
"enclose",
"ie8",
"mangle",
"module",
"safari10",
"sourceMap",
"toplevel",
"wrap"
].forEach(function(name) {
if (name in program) {
options[name] = program[name];
}
});
if ("ecma" in program) {
if (program.ecma != (program.ecma | 0)) fatal("ERROR: ecma must be an integer");
const ecma = program.ecma | 0;
if (ecma > 5 && ecma < 2015)
options.ecma = ecma + 2009;
else
options.ecma = ecma;
}
if (program.format || program.beautify) {
const chosenOption = program.format || program.beautify;
options.format = typeof chosenOption === "object" ? chosenOption : {};
}
if (program.comments) {
if (typeof options.format != "object") options.format = {};
options.format.comments = typeof program.comments == "string" ? (program.comments == "false" ? false : program.comments) : "some";
}
if (program.define) {
if (typeof options.compress != "object") options.compress = {};
if (typeof options.compress.global_defs != "object") options.compress.global_defs = {};
for (var expr in program.define) {
options.compress.global_defs[expr] = program.define[expr];
}
}
if (program.keepClassnames) {
options.keep_classnames = true;
}
if (program.keepFnames) {
options.keep_fnames = true;
}
if (program.mangleProps) {
if (program.mangleProps.domprops) {
delete program.mangleProps.domprops;
} else {
if (typeof program.mangleProps != "object") program.mangleProps = {};
if (!Array.isArray(program.mangleProps.reserved)) program.mangleProps.reserved = [];
}
if (typeof options.mangle != "object") options.mangle = {};
options.mangle.properties = program.mangleProps;
}
if (program.nameCache) {
options.nameCache = JSON.parse(read_file(program.nameCache, "{}"));
}
if (program.output == "ast") {
options.format = {
ast: true,
code: false
};
}
if (program.parse) {
if (!program.parse.acorn && !program.parse.spidermonkey) {
options.parse = program.parse;
} else if (program.sourceMap && program.sourceMap.content == "inline") {
fatal("ERROR: inline source map only works with built-in parser");
}
}
if (~program.rawArgs.indexOf("--rename")) {
options.rename = true;
} else if (!program.rename) {
options.rename = false;
}
let convert_path = name => name;
if (typeof program.sourceMap == "object" && "base" in program.sourceMap) {
convert_path = function() {
var base = program.sourceMap.base;
delete options.sourceMap.base;
return function(name) {
return path.relative(base, name);
};
}();
}
let filesList;
if (options.files && options.files.length) {
filesList = options.files;
delete options.files;
} else if (program.args.length) {
filesList = program.args;
}
if (filesList) {
simple_glob(filesList).forEach(function(name) {
files[convert_path(name)] = read_file(name);
});
} else {
await new Promise((resolve) => {
var chunks = [];
process.stdin.setEncoding("utf8");
process.stdin.on("data", function(chunk) {
chunks.push(chunk);
}).on("end", function() {
files = [ chunks.join("") ];
resolve();
});
process.stdin.resume();
});
}
await run_cli();
function convert_ast(fn) {
return AST_Node.from_mozilla_ast(Object.keys(files).reduce(fn, null));
}
async function run_cli() {
var content = program.sourceMap && program.sourceMap.content;
if (content && content !== "inline") {
options.sourceMap.content = read_file(content, content);
}
if (program.timings) options.timings = true;
try {
if (program.parse) {
if (program.parse.acorn) {
files = convert_ast(function(toplevel, name) {
return require("acorn").parse(files[name], {
ecmaVersion: 2018,
locations: true,
program: toplevel,
sourceFile: name,
sourceType: options.module || program.parse.module ? "module" : "script"
});
});
} else if (program.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);
}
let result;
try {
result = await minify(files, options);
} catch (ex) {
if (ex.name == "SyntaxError") {
print_error("Parse error at " + ex.filename + ":" + ex.line + "," + ex.col);
var col = ex.col;
var lines = files[ex.filename].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, " ") + "^");
}
}
if (ex.defs) {
print_error("Supported options:");
print_error(format_object(ex.defs));
}
fatal(ex);
return;
}
if (program.output == "ast") {
if (!options.compress && !options.mangle) {
result.ast.figure_out_scope({});
}
console.log(JSON.stringify(result.ast, function(key, value) {
if (value) switch (key) {
case "thedef":
return symdef(value);
case "enclosed":
return value.length ? value.map(symdef) : undefined;
case "variables":
case "functions":
case "globals":
return value.size ? collect_from_map(value, symdef) : undefined;
}
if (skip_keys.has(key)) return;
if (value instanceof AST_Token) return;
if (value instanceof Map) return;
if (value instanceof AST_Node) {
var result = {
_class: "AST_" + value.TYPE
};
if (value.block_scope) {
result.variables = value.block_scope.variables;
result.functions = value.block_scope.functions;
result.enclosed = value.block_scope.enclosed;
}
value.CTOR.PROPS.forEach(function(prop) {
result[prop] = value[prop];
});
return result;
}
return value;
}, 2));
} else if (program.output == "spidermonkey") {
try {
const minified = await minify(result.code, {
compress: false,
mangle: false,
format: {
ast: true,
code: false
}
});
console.log(JSON.stringify(minified.ast.to_mozilla_ast(), null, 2));
} catch (ex) {
fatal(ex);
return;
}
} else if (program.output) {
fs.writeFileSync(program.output, result.code);
if (options.sourceMap && options.sourceMap.url !== "inline" && result.map) {
fs.writeFileSync(program.output + ".map", result.map);
}
} else {
console.log(result.code);
}
if (program.nameCache) {
fs.writeFileSync(program.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:");
print_error(message);
process.exit(1);
}
// A file glob function that only supports "*" and "?" wildcards in the basename.
// Example: "foo/bar/*baz??.*.js"
// Argument `glob` may be a string or an array of strings.
// Returns an array of strings. Garbage in, garbage out.
function simple_glob(glob) {
if (Array.isArray(glob)) {
return [].concat.apply([], glob.map(simple_glob));
}
if (glob && glob.match(/[*?]/)) {
var dir = path.dirname(glob);
try {
var entries = fs.readdirSync(dir);
} 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);
}).map(function(name) {
return path.join(dir, name);
});
if (results.length) return results;
}
}
return [ glob ];
}
function read_file(path, default_value) {
try {
return fs.readFileSync(path, "utf8");
} catch (ex) {
if ((ex.code == "ENOENT" || ex.code == "ENAMETOOLONG") && default_value != null) return default_value;
fatal(ex);
}
}
function parse_js(flag) {
return function(value, options) {
options = options || {};
try {
walk(parse(value, { expression: true }), node => {
if (node instanceof AST_Assign) {
var name = node.left.print_to_string();
var value = node.right;
if (flag) {
options[name] = value;
} else if (value instanceof AST_Array) {
options[name] = value.elements.map(to_string);
} else if (value instanceof AST_RegExp) {
value = value.value;
options[name] = new RegExp(value.source, value.flags);
} else {
options[name] = to_string(value);
}
return true;
}
if (node instanceof AST_Symbol || node instanceof AST_PropAccess) {
var name = node.print_to_string();
options[name] = true;
return true;
}
if (!(node instanceof AST_Sequence)) throw node;
function to_string(value) {
return value instanceof AST_Constant ? value.getValue() : value.print_to_string({
quote_keys: true
});
}
});
} catch(ex) {
if (flag) {
fatal("Error parsing arguments for '" + flag + "': " + value);
} else {
options[value] = null;
}
}
return options;
};
}
function symdef(def) {
var ret = (1e6 + def.id) + " " + def.name;
if (def.mangled_name) ret += " " + def.mangled_name;
return ret;
}
function collect_from_map(map, callback) {
var result = [];
map.forEach(function (def) {
result.push(callback(def));
});
return result;
}
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 describe_ast() {
var out = OutputStream({ beautify: true });
function doitem(ctor) {
out.print("AST_" + ctor.TYPE);
const props = ctor.SELF_PROPS.filter(prop => !/^\$/.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.forEach(function(ctor) {
out.indent();
doitem(ctor);
out.newline();
});
});
}
}
doitem(AST_Node);
return out + "\n";
}
}

7739
assets_old/node_modules/terser/lib/compress/index.js generated vendored Normal file

File diff suppressed because it is too large Load diff

308
assets_old/node_modules/terser/lib/equivalent-to.js generated vendored Normal file
View file

@ -0,0 +1,308 @@
import {
AST_Array,
AST_Atom,
AST_Await,
AST_BigInt,
AST_Binary,
AST_Block,
AST_Call,
AST_Catch,
AST_Chain,
AST_Class,
AST_ClassProperty,
AST_ConciseMethod,
AST_Conditional,
AST_Debugger,
AST_Definitions,
AST_Destructuring,
AST_Directive,
AST_Do,
AST_Dot,
AST_EmptyStatement,
AST_Expansion,
AST_Export,
AST_Finally,
AST_For,
AST_ForIn,
AST_ForOf,
AST_If,
AST_Import,
AST_ImportMeta,
AST_Jump,
AST_LabeledStatement,
AST_Lambda,
AST_LoopControl,
AST_NameMapping,
AST_NewTarget,
AST_Node,
AST_Number,
AST_Object,
AST_ObjectGetter,
AST_ObjectKeyVal,
AST_ObjectProperty,
AST_ObjectSetter,
AST_PrefixedTemplateString,
AST_PropAccess,
AST_RegExp,
AST_Sequence,
AST_SimpleStatement,
AST_String,
AST_Super,
AST_Switch,
AST_SwitchBranch,
AST_Symbol,
AST_TemplateSegment,
AST_TemplateString,
AST_This,
AST_Toplevel,
AST_Try,
AST_Unary,
AST_VarDef,
AST_While,
AST_With,
AST_Yield
} from "./ast.js";
const shallow_cmp = (node1, node2) => {
return (
node1 === null && node2 === null
|| node1.TYPE === node2.TYPE && node1.shallow_cmp(node2)
);
};
export const equivalent_to = (tree1, tree2) => {
if (!shallow_cmp(tree1, tree2)) return false;
const walk_1_state = [tree1];
const walk_2_state = [tree2];
const walk_1_push = walk_1_state.push.bind(walk_1_state);
const walk_2_push = walk_2_state.push.bind(walk_2_state);
while (walk_1_state.length && walk_2_state.length) {
const node_1 = walk_1_state.pop();
const node_2 = walk_2_state.pop();
if (!shallow_cmp(node_1, node_2)) return false;
node_1._children_backwards(walk_1_push);
node_2._children_backwards(walk_2_push);
if (walk_1_state.length !== walk_2_state.length) {
// Different number of children
return false;
}
}
return walk_1_state.length == 0 && walk_2_state.length == 0;
};
// Creates a shallow compare function
const mkshallow = (props) => {
const comparisons = Object
.keys(props)
.map(key => {
if (props[key] === "eq") {
return `this.${key} === other.${key}`;
} else if (props[key] === "exist") {
return `(this.${key} == null ? other.${key} == null : this.${key} === other.${key})`;
} else {
throw new Error(`mkshallow: Unexpected instruction: ${props[key]}`);
}
})
.join(" && ");
return new Function("other", "return " + comparisons);
};
const pass_through = () => true;
AST_Node.prototype.shallow_cmp = function () {
throw new Error("did not find a shallow_cmp function for " + this.constructor.name);
};
AST_Debugger.prototype.shallow_cmp = pass_through;
AST_Directive.prototype.shallow_cmp = mkshallow({ value: "eq" });
AST_SimpleStatement.prototype.shallow_cmp = pass_through;
AST_Block.prototype.shallow_cmp = pass_through;
AST_EmptyStatement.prototype.shallow_cmp = pass_through;
AST_LabeledStatement.prototype.shallow_cmp = mkshallow({ "label.name": "eq" });
AST_Do.prototype.shallow_cmp = pass_through;
AST_While.prototype.shallow_cmp = pass_through;
AST_For.prototype.shallow_cmp = mkshallow({
init: "exist",
condition: "exist",
step: "exist"
});
AST_ForIn.prototype.shallow_cmp = pass_through;
AST_ForOf.prototype.shallow_cmp = pass_through;
AST_With.prototype.shallow_cmp = pass_through;
AST_Toplevel.prototype.shallow_cmp = pass_through;
AST_Expansion.prototype.shallow_cmp = pass_through;
AST_Lambda.prototype.shallow_cmp = mkshallow({
is_generator: "eq",
async: "eq"
});
AST_Destructuring.prototype.shallow_cmp = mkshallow({
is_array: "eq"
});
AST_PrefixedTemplateString.prototype.shallow_cmp = pass_through;
AST_TemplateString.prototype.shallow_cmp = pass_through;
AST_TemplateSegment.prototype.shallow_cmp = mkshallow({
"value": "eq"
});
AST_Jump.prototype.shallow_cmp = pass_through;
AST_LoopControl.prototype.shallow_cmp = pass_through;
AST_Await.prototype.shallow_cmp = pass_through;
AST_Yield.prototype.shallow_cmp = mkshallow({
is_star: "eq"
});
AST_If.prototype.shallow_cmp = mkshallow({
alternative: "exist"
});
AST_Switch.prototype.shallow_cmp = pass_through;
AST_SwitchBranch.prototype.shallow_cmp = pass_through;
AST_Try.prototype.shallow_cmp = mkshallow({
bcatch: "exist",
bfinally: "exist"
});
AST_Catch.prototype.shallow_cmp = mkshallow({
argname: "exist"
});
AST_Finally.prototype.shallow_cmp = pass_through;
AST_Definitions.prototype.shallow_cmp = pass_through;
AST_VarDef.prototype.shallow_cmp = mkshallow({
value: "exist"
});
AST_NameMapping.prototype.shallow_cmp = pass_through;
AST_Import.prototype.shallow_cmp = mkshallow({
imported_name: "exist",
imported_names: "exist"
});
AST_ImportMeta.prototype.shallow_cmp = pass_through;
AST_Export.prototype.shallow_cmp = mkshallow({
exported_definition: "exist",
exported_value: "exist",
exported_names: "exist",
module_name: "eq",
is_default: "eq",
});
AST_Call.prototype.shallow_cmp = pass_through;
AST_Sequence.prototype.shallow_cmp = pass_through;
AST_PropAccess.prototype.shallow_cmp = pass_through;
AST_Chain.prototype.shallow_cmp = pass_through;
AST_Dot.prototype.shallow_cmp = mkshallow({
property: "eq"
});
AST_Unary.prototype.shallow_cmp = mkshallow({
operator: "eq"
});
AST_Binary.prototype.shallow_cmp = mkshallow({
operator: "eq"
});
AST_Conditional.prototype.shallow_cmp = pass_through;
AST_Array.prototype.shallow_cmp = pass_through;
AST_Object.prototype.shallow_cmp = pass_through;
AST_ObjectProperty.prototype.shallow_cmp = pass_through;
AST_ObjectKeyVal.prototype.shallow_cmp = mkshallow({
key: "eq"
});
AST_ObjectSetter.prototype.shallow_cmp = mkshallow({
static: "eq"
});
AST_ObjectGetter.prototype.shallow_cmp = mkshallow({
static: "eq"
});
AST_ConciseMethod.prototype.shallow_cmp = mkshallow({
static: "eq",
is_generator: "eq",
async: "eq",
});
AST_Class.prototype.shallow_cmp = mkshallow({
name: "exist",
extends: "exist",
});
AST_ClassProperty.prototype.shallow_cmp = mkshallow({
static: "eq"
});
AST_Symbol.prototype.shallow_cmp = mkshallow({
name: "eq"
});
AST_NewTarget.prototype.shallow_cmp = pass_through;
AST_This.prototype.shallow_cmp = pass_through;
AST_Super.prototype.shallow_cmp = pass_through;
AST_String.prototype.shallow_cmp = mkshallow({
value: "eq"
});
AST_Number.prototype.shallow_cmp = mkshallow({
value: "eq"
});
AST_BigInt.prototype.shallow_cmp = mkshallow({
value: "eq"
});
AST_RegExp.prototype.shallow_cmp = function (other) {
return (
this.value.flags === other.value.flags
&& this.value.source === other.value.source
);
};
AST_Atom.prototype.shallow_cmp = pass_through;

268
assets_old/node_modules/terser/lib/minify.js generated vendored Normal file
View file

@ -0,0 +1,268 @@
"use strict";
/* eslint-env browser, es6, node */
import {
defaults,
map_from_object,
map_to_object,
HOP,
} from "./utils/index.js";
import { AST_Toplevel } from "./ast.js";
import { parse } from "./parse.js";
import { OutputStream } from "./output.js";
import { Compressor } from "./compress/index.js";
import { base54 } from "./scope.js";
import { SourceMap } from "./sourcemap.js";
import {
mangle_properties,
reserve_quoted_keys,
} from "./propmangle.js";
var to_ascii = typeof atob == "undefined" ? function(b64) {
return Buffer.from(b64, "base64").toString();
} : atob;
var to_base64 = typeof btoa == "undefined" ? function(str) {
return Buffer.from(str).toString("base64");
} : btoa;
function read_source_map(code) {
var match = /(?:^|[^.])\/\/# sourceMappingURL=data:application\/json(;[\w=-]*)?;base64,([+/0-9A-Za-z]*=*)\s*$/.exec(code);
if (!match) {
console.warn("inline source map not found");
return null;
}
return to_ascii(match[2]);
}
function set_shorthand(name, options, keys) {
if (options[name]) {
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 Map();
} else if (!(cache.props instanceof Map)) {
cache.props = map_from_object(cache.props);
}
}
function cache_to_json(cache) {
return {
props: map_to_object(cache.props)
};
}
async function minify(files, options) {
options = defaults(options, {
compress: {},
ecma: undefined,
enclose: false,
ie8: false,
keep_classnames: undefined,
keep_fnames: false,
mangle: {},
module: false,
nameCache: null,
output: null,
format: null,
parse: {},
rename: undefined,
safari10: false,
sourceMap: false,
timings: false,
toplevel: false,
warnings: false,
wrap: false,
}, true);
var timings = options.timings && {
start: Date.now()
};
if (options.keep_classnames === undefined) {
options.keep_classnames = options.keep_fnames;
}
if (options.rename === undefined) {
options.rename = options.compress && options.mangle;
}
if (options.output && options.format) {
throw new Error("Please only specify either output or format option, preferrably format.");
}
options.format = options.format || options.output || {};
set_shorthand("ecma", options, [ "parse", "compress", "format" ]);
set_shorthand("ie8", options, [ "compress", "mangle", "format" ]);
set_shorthand("keep_classnames", options, [ "compress", "mangle" ]);
set_shorthand("keep_fnames", options, [ "compress", "mangle" ]);
set_shorthand("module", options, [ "parse", "compress", "mangle" ]);
set_shorthand("safari10", options, [ "mangle", "format" ]);
set_shorthand("toplevel", options, [ "compress", "mangle" ]);
set_shorthand("warnings", options, [ "compress" ]); // legacy
var quoted_props;
if (options.mangle) {
options.mangle = defaults(options.mangle, {
cache: options.nameCache && (options.nameCache.vars || {}),
eval: false,
ie8: false,
keep_classnames: false,
keep_fnames: false,
module: false,
properties: false,
reserved: [],
safari10: false,
toplevel: 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.sourceMap) {
options.sourceMap = defaults(options.sourceMap, {
asObject: false,
content: null,
filename: null,
includeSources: false,
root: null,
url: null,
}, true);
}
if (timings) timings.parse = Date.now();
var toplevel;
if (files instanceof AST_Toplevel) {
toplevel = files;
} else {
if (typeof files == "string") {
files = [ files ];
}
options.parse = options.parse || {};
options.parse.toplevel = null;
for (var name in files) if (HOP(files, name)) {
options.parse.filename = name;
options.parse.toplevel = parse(files[name], options.parse);
if (options.sourceMap && options.sourceMap.content == "inline") {
if (Object.keys(files).length > 1)
throw new Error("inline source map only works with singular input");
options.sourceMap.content = read_source_map(files[name]);
}
}
toplevel = options.parse.toplevel;
}
if (quoted_props && options.mangle.properties.keep_quoted !== "strict") {
reserve_quoted_keys(toplevel, quoted_props);
}
if (options.wrap) {
toplevel = toplevel.wrap_commonjs(options.wrap);
}
if (options.enclose) {
toplevel = toplevel.wrap_enclose(options.enclose);
}
if (timings) timings.rename = Date.now();
// disable rename on harmony due to expand_names bug in for-of loops
// https://github.com/mishoo/UglifyJS2/issues/2794
if (0 && options.rename) {
toplevel.figure_out_scope(options.mangle);
toplevel.expand_names(options.mangle);
}
if (timings) timings.compress = Date.now();
if (options.compress) {
toplevel = new Compressor(options.compress, {
mangle_options: options.mangle
}).compress(toplevel);
}
if (timings) timings.scope = Date.now();
if (options.mangle) toplevel.figure_out_scope(options.mangle);
if (timings) timings.mangle = Date.now();
if (options.mangle) {
base54.reset();
toplevel.compute_char_frequency(options.mangle);
toplevel.mangle_names(options.mangle);
}
if (timings) timings.properties = Date.now();
if (options.mangle && options.mangle.properties) {
toplevel = mangle_properties(toplevel, options.mangle.properties);
}
if (timings) timings.format = Date.now();
var result = {};
if (options.format.ast) {
result.ast = toplevel;
}
if (!HOP(options.format, "code") || options.format.code) {
if (options.sourceMap) {
options.format.source_map = await SourceMap({
file: options.sourceMap.filename,
orig: options.sourceMap.content,
root: options.sourceMap.root
});
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)) {
options.format.source_map.get().setSourceContent(name, files[name]);
}
}
}
delete options.format.ast;
delete options.format.code;
var stream = OutputStream(options.format);
toplevel.print(stream);
result.code = stream.get();
if (options.sourceMap) {
if(options.sourceMap.asObject) {
result.map = options.format.source_map.get().toJSON();
} else {
result.map = options.format.source_map.toString();
}
if (options.sourceMap.url == "inline") {
var sourceMap = typeof result.map === "object" ? JSON.stringify(result.map) : result.map;
result.code += "\n//# sourceMappingURL=data:application/json;charset=utf-8;base64," + to_base64(sourceMap);
} else if (options.sourceMap.url) {
result.code += "\n//# sourceMappingURL=" + options.sourceMap.url;
}
}
}
if (options.nameCache && options.mangle) {
if (options.mangle.cache) options.nameCache.vars = cache_to_json(options.mangle.cache);
if (options.mangle.properties && options.mangle.properties.cache) {
options.nameCache.props = cache_to_json(options.mangle.properties.cache);
}
}
if (options.format && options.format.source_map) {
options.format.source_map.destroy();
}
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.format - timings.properties),
format: 1e-3 * (timings.end - timings.format),
total: 1e-3 * (timings.end - timings.start)
};
}
return result;
}
export {
minify,
to_ascii,
};

1334
assets_old/node_modules/terser/lib/mozilla-ast.js generated vendored Normal file

File diff suppressed because it is too large Load diff

2283
assets_old/node_modules/terser/lib/output.js generated vendored Normal file

File diff suppressed because it is too large Load diff

3352
assets_old/node_modules/terser/lib/parse.js generated vendored Normal file

File diff suppressed because one or more lines are too long

353
assets_old/node_modules/terser/lib/propmangle.js generated vendored Normal file
View file

@ -0,0 +1,353 @@
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
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";
/* global global, self */
import {
defaults,
push_uniq,
} from "./utils/index.js";
import { base54 } from "./scope.js";
import {
AST_Binary,
AST_Call,
AST_ClassPrivateProperty,
AST_Conditional,
AST_Dot,
AST_DotHash,
AST_ObjectKeyVal,
AST_ObjectProperty,
AST_PrivateMethod,
AST_Sequence,
AST_String,
AST_Sub,
TreeTransformer,
TreeWalker,
} from "./ast.js";
import { domprops } from "../tools/domprops.js";
function find_builtins(reserved) {
domprops.forEach(add);
// Compatibility fix for some standard defined globals not defined on every js environment
var new_globals = ["Symbol", "Map", "Promise", "Proxy", "Reflect", "Set", "WeakMap", "WeakSet"];
var objects = {};
var global_ref = typeof global === "object" ? global : self;
new_globals.forEach(function (new_global) {
objects[new_global] = global_ref[new_global] || new Function();
});
[
"null",
"true",
"false",
"NaN",
"Infinity",
"-Infinity",
"undefined",
].forEach(add);
[ Object, Array, Function, Number,
String, Boolean, Error, Math,
Date, RegExp, objects.Symbol, ArrayBuffer,
DataView, decodeURI, decodeURIComponent,
encodeURI, encodeURIComponent, eval, EvalError,
Float32Array, Float64Array, Int8Array, Int16Array,
Int32Array, isFinite, isNaN, JSON, objects.Map, parseFloat,
parseInt, objects.Promise, objects.Proxy, RangeError, ReferenceError,
objects.Reflect, objects.Set, SyntaxError, TypeError, Uint8Array,
Uint8ClampedArray, Uint16Array, Uint32Array, URIError,
objects.WeakMap, objects.WeakSet
].forEach(function(ctor) {
Object.getOwnPropertyNames(ctor).map(add);
if (ctor.prototype) {
Object.getOwnPropertyNames(ctor.prototype).map(add);
}
});
function add(name) {
reserved.add(name);
}
}
function reserve_quoted_keys(ast, reserved) {
function add(name) {
push_uniq(reserved, name);
}
ast.walk(new TreeWalker(function(node) {
if (node instanceof AST_ObjectKeyVal && node.quote) {
add(node.key);
} else if (node instanceof AST_ObjectProperty && node.quote) {
add(node.key.name);
} else if (node instanceof AST_Sub) {
addStrings(node.property, add);
}
}));
}
function addStrings(node, add) {
node.walk(new TreeWalker(function(node) {
if (node instanceof AST_Sequence) {
addStrings(node.tail_node(), add);
} else if (node instanceof AST_String) {
add(node.value);
} else if (node instanceof AST_Conditional) {
addStrings(node.consequent, add);
addStrings(node.alternative, add);
}
return true;
}));
}
function mangle_properties(ast, options) {
options = defaults(options, {
builtins: false,
cache: null,
debug: false,
keep_quoted: false,
only_cache: false,
regex: null,
reserved: null,
undeclared: false,
}, true);
var reserved_option = options.reserved;
if (!Array.isArray(reserved_option)) reserved_option = [reserved_option];
var reserved = new Set(reserved_option);
if (!options.builtins) find_builtins(reserved);
var cname = -1;
var cprivate = -1;
var cache;
var private_cache = new Map();
if (options.cache) {
cache = options.cache.props;
cache.forEach(function(mangled_name) {
reserved.add(mangled_name);
});
} else {
cache = new Map();
}
var regex = options.regex && new RegExp(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 falsey. Also treat passing 'true'
// the same as passing an empty string.
var debug = options.debug !== false;
var debug_name_suffix;
if (debug) {
debug_name_suffix = (options.debug === true ? "" : options.debug);
}
var names_to_mangle = new Set();
var unmangleable = new Set();
var private_properties = new Set();
var keep_quoted_strict = options.keep_quoted === "strict";
// step 1: find candidates to mangle
ast.walk(new TreeWalker(function(node) {
if (
node instanceof AST_ClassPrivateProperty
|| node instanceof AST_PrivateMethod
) {
private_properties.add(node.key.name);
} else if (node instanceof AST_DotHash) {
private_properties.add(node.property);
} else if (node instanceof AST_ObjectKeyVal) {
if (typeof node.key == "string" &&
(!keep_quoted_strict || !node.quote)) {
add(node.key);
}
} else if (node instanceof AST_ObjectProperty) {
// setter or getter, since KeyVal is handled above
if (!keep_quoted_strict || !node.key.end.quote) {
add(node.key.name);
}
} else if (node instanceof AST_Dot) {
var declared = !!options.undeclared;
if (!declared) {
var root = node;
while (root.expression) {
root = root.expression;
}
declared = !(root.thedef && root.thedef.undeclared);
}
if (declared &&
(!keep_quoted_strict || !node.quote)) {
add(node.property);
}
} else if (node instanceof AST_Sub) {
if (!keep_quoted_strict) {
addStrings(node.property, add);
}
} else if (node instanceof AST_Call
&& node.expression.print_to_string() == "Object.defineProperty") {
addStrings(node.args[1], add);
} else if (node instanceof AST_Binary && node.operator === "in") {
addStrings(node.left, add);
}
}));
// step 2: transform the tree, renaming properties
return ast.transform(new TreeTransformer(function(node) {
if (
node instanceof AST_ClassPrivateProperty
|| node instanceof AST_PrivateMethod
) {
node.key.name = mangle_private(node.key.name);
} else if (node instanceof AST_DotHash) {
node.property = mangle_private(node.property);
} else if (node instanceof AST_ObjectKeyVal) {
if (typeof node.key == "string" &&
(!keep_quoted_strict || !node.quote)) {
node.key = mangle(node.key);
}
} else if (node instanceof AST_ObjectProperty) {
// setter, getter, method or class field
if (!keep_quoted_strict || !node.key.end.quote) {
node.key.name = mangle(node.key.name);
}
} else if (node instanceof AST_Dot) {
if (!keep_quoted_strict || !node.quote) {
node.property = mangle(node.property);
}
} else if (!options.keep_quoted && node instanceof AST_Sub) {
node.property = mangleStrings(node.property);
} else if (node instanceof AST_Call
&& node.expression.print_to_string() == "Object.defineProperty") {
node.args[1] = mangleStrings(node.args[1]);
} else if (node instanceof AST_Binary && node.operator === "in") {
node.left = mangleStrings(node.left);
}
}));
// only function declarations after this line
function can_mangle(name) {
if (unmangleable.has(name)) return false;
if (reserved.has(name)) return false;
if (options.only_cache) {
return cache.has(name);
}
if (/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name)) return false;
return true;
}
function should_mangle(name) {
if (regex && !regex.test(name)) return false;
if (reserved.has(name)) return false;
return cache.has(name)
|| names_to_mangle.has(name);
}
function add(name) {
if (can_mangle(name))
names_to_mangle.add(name);
if (!should_mangle(name)) {
unmangleable.add(name);
}
}
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_name_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));
}
cache.set(name, mangled);
}
return mangled;
}
function mangle_private(name) {
let mangled = private_cache.get(name);
if (!mangled) {
mangled = base54(++cprivate);
private_cache.set(name, mangled);
}
return mangled;
}
function mangleStrings(node) {
return node.transform(new TreeTransformer(function(node) {
if (node instanceof AST_Sequence) {
var last = node.expressions.length - 1;
node.expressions[last] = mangleStrings(node.expressions[last]);
} else if (node instanceof AST_String) {
node.value = mangle(node.value);
} else if (node instanceof AST_Conditional) {
node.consequent = mangleStrings(node.consequent);
node.alternative = mangleStrings(node.alternative);
}
return node;
}));
}
}
export {
reserve_quoted_keys,
mangle_properties,
};

994
assets_old/node_modules/terser/lib/scope.js generated vendored Normal file
View file

@ -0,0 +1,994 @@
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
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";
import {
defaults,
keep_name,
mergeSort,
push_uniq,
make_node,
return_false,
return_this,
return_true,
string_template,
} from "./utils/index.js";
import {
AST_Arrow,
AST_Block,
AST_Call,
AST_Catch,
AST_Class,
AST_Conditional,
AST_DefClass,
AST_Defun,
AST_Destructuring,
AST_Dot,
AST_DotHash,
AST_Export,
AST_For,
AST_ForIn,
AST_Function,
AST_Import,
AST_IterationStatement,
AST_Label,
AST_LabeledStatement,
AST_LabelRef,
AST_Lambda,
AST_LoopControl,
AST_NameMapping,
AST_Node,
AST_Scope,
AST_Sequence,
AST_String,
AST_Sub,
AST_Switch,
AST_SwitchBranch,
AST_Symbol,
AST_SymbolBlockDeclaration,
AST_SymbolCatch,
AST_SymbolClass,
AST_SymbolConst,
AST_SymbolDefClass,
AST_SymbolDefun,
AST_SymbolExport,
AST_SymbolFunarg,
AST_SymbolImport,
AST_SymbolLambda,
AST_SymbolLet,
AST_SymbolMethod,
AST_SymbolRef,
AST_SymbolVar,
AST_Toplevel,
AST_VarDef,
AST_With,
TreeWalker,
walk
} from "./ast.js";
import {
RESERVED_WORDS,
js_error,
} from "./parse.js";
const MASK_EXPORT_DONT_MANGLE = 1 << 0;
const MASK_EXPORT_WANT_MANGLE = 1 << 1;
let function_defs = null;
let unmangleable_names = null;
class SymbolDef {
constructor(scope, orig, init) {
this.name = orig.name;
this.orig = [ orig ];
this.init = init;
this.eliminated = 0;
this.assignments = 0;
this.scope = scope;
this.replaced = 0;
this.global = false;
this.export = 0;
this.mangled_name = null;
this.undeclared = false;
this.id = SymbolDef.next_id++;
this.chained = false;
this.direct_access = false;
this.escaped = 0;
this.recursive_refs = 0;
this.references = [];
this.should_replace = undefined;
this.single_use = false;
this.fixed = false;
Object.seal(this);
}
fixed_value() {
if (!this.fixed || this.fixed instanceof AST_Node) return this.fixed;
return this.fixed();
}
unmangleable(options) {
if (!options) options = {};
if (
function_defs &&
function_defs.has(this.id) &&
keep_name(options.keep_fnames, this.orig[0].name)
) return true;
return this.global && !options.toplevel
|| (this.export & MASK_EXPORT_DONT_MANGLE)
|| this.undeclared
|| !options.eval && this.scope.pinned()
|| (this.orig[0] instanceof AST_SymbolLambda
|| this.orig[0] instanceof AST_SymbolDefun) && keep_name(options.keep_fnames, this.orig[0].name)
|| this.orig[0] instanceof AST_SymbolMethod
|| (this.orig[0] instanceof AST_SymbolClass
|| this.orig[0] instanceof AST_SymbolDefClass) && keep_name(options.keep_classnames, this.orig[0].name);
}
mangle(options) {
const cache = options.cache && options.cache.props;
if (this.global && cache && cache.has(this.name)) {
this.mangled_name = cache.get(this.name);
} else if (!this.mangled_name && !this.unmangleable(options)) {
var s = this.scope;
var sym = this.orig[0];
if (options.ie8 && sym instanceof AST_SymbolLambda)
s = s.parent_scope;
const redefinition = redefined_catch_def(this);
this.mangled_name = redefinition
? redefinition.mangled_name || redefinition.name
: s.next_mangled(options, this);
if (this.global && cache) {
cache.set(this.name, this.mangled_name);
}
}
}
}
SymbolDef.next_id = 1;
function redefined_catch_def(def) {
if (def.orig[0] instanceof AST_SymbolCatch
&& def.scope.is_block_scope()
) {
return def.scope.get_defun_scope().variables.get(def.name);
}
}
AST_Scope.DEFMETHOD("figure_out_scope", function(options, { parent_scope = null, toplevel = this } = {}) {
options = defaults(options, {
cache: null,
ie8: false,
safari10: false,
});
if (!(toplevel instanceof AST_Toplevel)) {
throw new Error("Invalid toplevel scope");
}
// pass 1: setup scope chaining and handle definitions
var scope = this.parent_scope = parent_scope;
var labels = new Map();
var defun = null;
var in_destructuring = null;
var for_scopes = [];
var tw = new TreeWalker((node, descend) => {
if (node.is_block_scope()) {
const save_scope = scope;
node.block_scope = scope = new AST_Scope(node);
scope._block_scope = true;
// AST_Try in the AST sadly *is* (not has) a body itself,
// and its catch and finally branches are children of the AST_Try itself
const parent_scope = node instanceof AST_Catch
? save_scope.parent_scope
: save_scope;
scope.init_scope_vars(parent_scope);
scope.uses_with = save_scope.uses_with;
scope.uses_eval = save_scope.uses_eval;
if (options.safari10) {
if (node instanceof AST_For || node instanceof AST_ForIn) {
for_scopes.push(scope);
}
}
if (node instanceof AST_Switch) {
// XXX: HACK! Ensure the switch expression gets the correct scope (the parent scope) and the body gets the contained scope
// AST_Switch has a scope within the body, but it itself "is a block scope"
// This means the switched expression has to belong to the outer scope
// while the body inside belongs to the switch itself.
// This is pretty nasty and warrants an AST change similar to AST_Try (read above)
const the_block_scope = scope;
scope = save_scope;
node.expression.walk(tw);
scope = the_block_scope;
for (let i = 0; i < node.body.length; i++) {
node.body[i].walk(tw);
}
} else {
descend();
}
scope = save_scope;
return true;
}
if (node instanceof AST_Destructuring) {
const save_destructuring = in_destructuring;
in_destructuring = node;
descend();
in_destructuring = save_destructuring;
return true;
}
if (node instanceof AST_Scope) {
node.init_scope_vars(scope);
var save_scope = scope;
var save_defun = defun;
var save_labels = labels;
defun = scope = node;
labels = new Map();
descend();
scope = save_scope;
defun = save_defun;
labels = save_labels;
return true; // don't descend again in TreeWalker
}
if (node instanceof AST_LabeledStatement) {
var l = node.label;
if (labels.has(l.name)) {
throw new Error(string_template("Label {name} defined twice", l));
}
labels.set(l.name, l);
descend();
labels.delete(l.name);
return true; // no descend again
}
if (node instanceof AST_With) {
for (var s = scope; s; s = s.parent_scope)
s.uses_with = true;
return;
}
if (node instanceof AST_Symbol) {
node.scope = scope;
}
if (node instanceof AST_Label) {
node.thedef = node;
node.references = [];
}
if (node instanceof AST_SymbolLambda) {
defun.def_function(node, node.name == "arguments" ? undefined : defun);
} else if (node instanceof AST_SymbolDefun) {
// Careful here, the scope where this should be defined is
// the parent scope. The reason is that we enter a new
// scope when we encounter the AST_Defun node (which is
// instanceof AST_Scope) but we get to the symbol a bit
// later.
mark_export((node.scope = defun.parent_scope.get_defun_scope()).def_function(node, defun), 1);
} else if (node instanceof AST_SymbolClass) {
mark_export(defun.def_variable(node, defun), 1);
} else if (node instanceof AST_SymbolImport) {
scope.def_variable(node);
} else if (node instanceof AST_SymbolDefClass) {
// This deals with the name of the class being available
// inside the class.
mark_export((node.scope = defun.parent_scope).def_function(node, defun), 1);
} else if (
node instanceof AST_SymbolVar
|| node instanceof AST_SymbolLet
|| node instanceof AST_SymbolConst
|| node instanceof AST_SymbolCatch
) {
var def;
if (node instanceof AST_SymbolBlockDeclaration) {
def = scope.def_variable(node, null);
} else {
def = defun.def_variable(node, node.TYPE == "SymbolVar" ? null : undefined);
}
if (!def.orig.every((sym) => {
if (sym === node) return true;
if (node instanceof AST_SymbolBlockDeclaration) {
return sym instanceof AST_SymbolLambda;
}
return !(sym instanceof AST_SymbolLet || sym instanceof AST_SymbolConst);
})) {
js_error(
`"${node.name}" is redeclared`,
node.start.file,
node.start.line,
node.start.col,
node.start.pos
);
}
if (!(node instanceof AST_SymbolFunarg)) mark_export(def, 2);
if (defun !== scope) {
node.mark_enclosed();
var def = scope.find_variable(node);
if (node.thedef !== def) {
node.thedef = def;
node.reference();
}
}
} else if (node instanceof AST_LabelRef) {
var sym = labels.get(node.name);
if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", {
name: node.name,
line: node.start.line,
col: node.start.col
}));
node.thedef = sym;
}
if (!(scope instanceof AST_Toplevel) && (node instanceof AST_Export || node instanceof AST_Import)) {
js_error(
`"${node.TYPE}" statement may only appear at the top level`,
node.start.file,
node.start.line,
node.start.col,
node.start.pos
);
}
});
this.walk(tw);
function mark_export(def, level) {
if (in_destructuring) {
var i = 0;
do {
level++;
} while (tw.parent(i++) !== in_destructuring);
}
var node = tw.parent(level);
if (def.export = node instanceof AST_Export ? MASK_EXPORT_DONT_MANGLE : 0) {
var exported = node.exported_definition;
if ((exported instanceof AST_Defun || exported instanceof AST_DefClass) && node.is_default) {
def.export = MASK_EXPORT_WANT_MANGLE;
}
}
}
// pass 2: find back references and eval
const is_toplevel = this instanceof AST_Toplevel;
if (is_toplevel) {
this.globals = new Map();
}
var tw = new TreeWalker(node => {
if (node instanceof AST_LoopControl && node.label) {
node.label.thedef.references.push(node);
return true;
}
if (node instanceof AST_SymbolRef) {
var name = node.name;
if (name == "eval" && tw.parent() instanceof AST_Call) {
for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) {
s.uses_eval = true;
}
}
var sym;
if (tw.parent() instanceof AST_NameMapping && tw.parent(1).module_name
|| !(sym = node.scope.find_variable(name))) {
sym = toplevel.def_global(node);
if (node instanceof AST_SymbolExport) sym.export = MASK_EXPORT_DONT_MANGLE;
} else if (sym.scope instanceof AST_Lambda && name == "arguments") {
sym.scope.uses_arguments = true;
}
node.thedef = sym;
node.reference();
if (node.scope.is_block_scope()
&& !(sym.orig[0] instanceof AST_SymbolBlockDeclaration)) {
node.scope = node.scope.get_defun_scope();
}
return true;
}
// ensure mangling works if catch reuses a scope variable
var def;
if (node instanceof AST_SymbolCatch && (def = redefined_catch_def(node.definition()))) {
var s = node.scope;
while (s) {
push_uniq(s.enclosed, def);
if (s === def.scope) break;
s = s.parent_scope;
}
}
});
this.walk(tw);
// pass 3: work around IE8 and Safari catch scope bugs
if (options.ie8 || options.safari10) {
walk(this, node => {
if (node instanceof AST_SymbolCatch) {
var name = node.name;
var refs = node.thedef.references;
var scope = node.scope.get_defun_scope();
var def = scope.find_variable(name)
|| toplevel.globals.get(name)
|| scope.def_variable(node);
refs.forEach(function(ref) {
ref.thedef = def;
ref.reference();
});
node.thedef = def;
node.reference();
return true;
}
});
}
// pass 4: add symbol definitions to loop scopes
// Safari/Webkit bug workaround - loop init let variable shadowing argument.
// https://github.com/mishoo/UglifyJS2/issues/1753
// https://bugs.webkit.org/show_bug.cgi?id=171041
if (options.safari10) {
for (const scope of for_scopes) {
scope.parent_scope.variables.forEach(function(def) {
push_uniq(scope.enclosed, def);
});
}
}
});
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 = new SymbolDef(this, node);
g.undeclared = true;
g.global = true;
globals.set(name, g);
return g;
}
});
AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope) {
this.variables = new Map(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
this.functions = new Map(); // map name to AST_SymbolDefun (functions defined in this scope)
this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
this.parent_scope = parent_scope; // the parent scope
this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
this.cname = -1; // the current index for mangling functions/variables
});
AST_Scope.DEFMETHOD("conflicting_def", function (name) {
return (
this.enclosed.find(def => def.name === name)
|| this.variables.has(name)
|| (this.parent_scope && this.parent_scope.conflicting_def(name))
);
});
AST_Scope.DEFMETHOD("conflicting_def_shallow", function (name) {
return (
this.enclosed.find(def => def.name === name)
|| this.variables.has(name)
);
});
AST_Scope.DEFMETHOD("add_child_scope", function (scope) {
// `scope` is going to be moved into `this` right now.
// Update the required scopes' information
if (scope.parent_scope === this) return;
scope.parent_scope = this;
// TODO uses_with, uses_eval, etc
const scope_ancestry = (() => {
const ancestry = [];
let cur = this;
do {
ancestry.push(cur);
} while ((cur = cur.parent_scope));
ancestry.reverse();
return ancestry;
})();
const new_scope_enclosed_set = new Set(scope.enclosed);
const to_enclose = [];
for (const scope_topdown of scope_ancestry) {
to_enclose.forEach(e => push_uniq(scope_topdown.enclosed, e));
for (const def of scope_topdown.variables.values()) {
if (new_scope_enclosed_set.has(def)) {
push_uniq(to_enclose, def);
push_uniq(scope_topdown.enclosed, def);
}
}
}
});
function find_scopes_visible_from(scopes) {
const found_scopes = new Set();
for (const scope of new Set(scopes)) {
(function bubble_up(scope) {
if (scope == null || found_scopes.has(scope)) return;
found_scopes.add(scope);
bubble_up(scope.parent_scope);
})(scope);
}
return [...found_scopes];
}
// Creates a symbol during compression
AST_Scope.DEFMETHOD("create_symbol", function(SymClass, {
source,
tentative_name,
scope,
conflict_scopes = [scope],
init = null
} = {}) {
let symbol_name;
conflict_scopes = find_scopes_visible_from(conflict_scopes);
if (tentative_name) {
// Implement hygiene (no new names are conflicting with existing names)
tentative_name =
symbol_name =
tentative_name.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/ig, "_");
let i = 0;
while (conflict_scopes.find(s => s.conflicting_def_shallow(symbol_name))) {
symbol_name = tentative_name + "$" + i++;
}
}
if (!symbol_name) {
throw new Error("No symbol name could be generated in create_symbol()");
}
const symbol = make_node(SymClass, source, {
name: symbol_name,
scope
});
this.def_variable(symbol, init || null);
symbol.mark_enclosed();
return symbol;
});
AST_Node.DEFMETHOD("is_block_scope", return_false);
AST_Class.DEFMETHOD("is_block_scope", return_false);
AST_Lambda.DEFMETHOD("is_block_scope", return_false);
AST_Toplevel.DEFMETHOD("is_block_scope", return_false);
AST_SwitchBranch.DEFMETHOD("is_block_scope", return_false);
AST_Block.DEFMETHOD("is_block_scope", return_true);
AST_Scope.DEFMETHOD("is_block_scope", function () {
return this._block_scope || false;
});
AST_IterationStatement.DEFMETHOD("is_block_scope", return_true);
AST_Lambda.DEFMETHOD("init_scope_vars", function() {
AST_Scope.prototype.init_scope_vars.apply(this, arguments);
this.uses_arguments = false;
this.def_variable(new AST_SymbolFunarg({
name: "arguments",
start: this.start,
end: this.end
}));
});
AST_Arrow.DEFMETHOD("init_scope_vars", function() {
AST_Scope.prototype.init_scope_vars.apply(this, arguments);
this.uses_arguments = false;
});
AST_Symbol.DEFMETHOD("mark_enclosed", function() {
var def = this.definition();
var s = this.scope;
while (s) {
push_uniq(s.enclosed, def);
if (s === def.scope) break;
s = s.parent_scope;
}
});
AST_Symbol.DEFMETHOD("reference", function() {
this.definition().references.push(this);
this.mark_enclosed();
});
AST_Scope.DEFMETHOD("find_variable", function(name) {
if (name instanceof AST_Symbol) name = name.name;
return this.variables.get(name)
|| (this.parent_scope && this.parent_scope.find_variable(name));
});
AST_Scope.DEFMETHOD("def_function", function(symbol, init) {
var def = this.def_variable(symbol, init);
if (!def.init || def.init instanceof AST_Defun) def.init = init;
this.functions.set(symbol.name, def);
return def;
});
AST_Scope.DEFMETHOD("def_variable", function(symbol, init) {
var def = this.variables.get(symbol.name);
if (def) {
def.orig.push(symbol);
if (def.init && (def.scope !== symbol.scope || def.init instanceof AST_Function)) {
def.init = init;
}
} else {
def = new SymbolDef(this, symbol, init);
this.variables.set(symbol.name, def);
def.global = !this.parent_scope;
}
return symbol.thedef = def;
});
function next_mangled(scope, options) {
var ext = scope.enclosed;
out: while (true) {
var m = base54(++scope.cname);
if (RESERVED_WORDS.has(m)) continue; // skip over "do"
// https://github.com/mishoo/UglifyJS2/issues/242 -- do not
// shadow a name reserved from mangling.
if (options.reserved.has(m)) continue;
// Functions with short names might collide with base54 output
// and therefore cause collisions when keep_fnames is true.
if (unmangleable_names && unmangleable_names.has(m)) continue out;
// we must ensure that the mangled name does not shadow a name
// from some parent scope that is referenced in this or in
// inner scopes.
for (let i = ext.length; --i >= 0;) {
const def = ext[i];
const name = def.mangled_name || (def.unmangleable(options) && def.name);
if (m == name) continue out;
}
return m;
}
}
AST_Scope.DEFMETHOD("next_mangled", function(options) {
return next_mangled(this, options);
});
AST_Toplevel.DEFMETHOD("next_mangled", function(options) {
let name;
const mangled_names = this.mangled_names;
do {
name = next_mangled(this, options);
} while (mangled_names.has(name));
return name;
});
AST_Function.DEFMETHOD("next_mangled", function(options, def) {
// #179, #326
// in Safari strict mode, something like (function x(x){...}) is a syntax error;
// a function expression's argument cannot shadow the function expression's name
var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();
// the function's mangled_name is null when keep_fnames is true
var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null;
while (true) {
var name = next_mangled(this, options);
if (!tricky_name || tricky_name != name)
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("unreferenced", function() {
return !this.definition().references.length && !this.scope.pinned();
});
AST_Symbol.DEFMETHOD("definition", function() {
return this.thedef;
});
AST_Symbol.DEFMETHOD("global", function() {
return this.thedef.global;
});
AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options) {
options = defaults(options, {
eval : false,
ie8 : false,
keep_classnames: false,
keep_fnames : false,
module : false,
reserved : [],
toplevel : false,
});
if (options.module) options.toplevel = true;
if (!Array.isArray(options.reserved)
&& !(options.reserved instanceof Set)
) {
options.reserved = [];
}
options.reserved = new Set(options.reserved);
// Never mangle arguments
options.reserved.add("arguments");
return options;
});
AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
options = this._default_mangler_options(options);
// We only need to mangle declaration nodes. Special logic wired
// into the code generator will display the mangled name if it's
// present (and for AST_SymbolRef-s it'll use the mangled name of
// the AST_SymbolDeclaration that it points to).
var lname = -1;
var to_mangle = [];
if (options.keep_fnames) {
function_defs = new Set();
}
const mangled_names = this.mangled_names = new Set();
if (options.cache) {
this.globals.forEach(collect);
if (options.cache.props) {
options.cache.props.forEach(function(mangled_name) {
mangled_names.add(mangled_name);
});
}
}
var tw = new TreeWalker(function(node, descend) {
if (node instanceof AST_LabeledStatement) {
// lname is incremented when we get to the AST_Label
var save_nesting = lname;
descend();
lname = save_nesting;
return true; // don't descend again in TreeWalker
}
if (node instanceof AST_Scope) {
node.variables.forEach(collect);
return;
}
if (node.is_block_scope()) {
node.block_scope.variables.forEach(collect);
return;
}
if (
function_defs
&& node instanceof AST_VarDef
&& node.value instanceof AST_Lambda
&& !node.value.name
&& keep_name(options.keep_fnames, node.name.name)
) {
function_defs.add(node.name.definition().id);
return;
}
if (node instanceof AST_Label) {
let name;
do {
name = base54(++lname);
} while (RESERVED_WORDS.has(name));
node.mangled_name = name;
return true;
}
if (!(options.ie8 || options.safari10) && node instanceof AST_SymbolCatch) {
to_mangle.push(node.definition());
return;
}
});
this.walk(tw);
if (options.keep_fnames || options.keep_classnames) {
unmangleable_names = new Set();
// Collect a set of short names which are unmangleable,
// for use in avoiding collisions in next_mangled.
to_mangle.forEach(def => {
if (def.name.length < 6 && def.unmangleable(options)) {
unmangleable_names.add(def.name);
}
});
}
to_mangle.forEach(def => { def.mangle(options); });
function_defs = null;
unmangleable_names = null;
function collect(symbol) {
const should_mangle = !options.reserved.has(symbol.name)
&& !(symbol.export & MASK_EXPORT_DONT_MANGLE);
if (should_mangle) {
to_mangle.push(symbol);
}
}
});
AST_Toplevel.DEFMETHOD("find_colliding_names", function(options) {
const cache = options.cache && options.cache.props;
const avoid = new Set();
options.reserved.forEach(to_avoid);
this.globals.forEach(add_def);
this.walk(new TreeWalker(function(node) {
if (node instanceof AST_Scope) node.variables.forEach(add_def);
if (node instanceof AST_SymbolCatch) add_def(node.definition());
}));
return avoid;
function to_avoid(name) {
avoid.add(name);
}
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 = this._default_mangler_options(options);
var avoid = this.find_colliding_names(options);
var cname = 0;
this.globals.forEach(rename);
this.walk(new TreeWalker(function(node) {
if (node instanceof AST_Scope) node.variables.forEach(rename);
if (node instanceof AST_SymbolCatch) rename(node.definition());
}));
function next_name() {
var name;
do {
name = base54(cname++);
} while (avoid.has(name) || RESERVED_WORDS.has(name));
return name;
}
function rename(def) {
if (def.global && options.cache) return;
if (def.unmangleable(options)) return;
if (options.reserved.has(def.name)) return;
const redefinition = redefined_catch_def(def);
const name = def.name = redefinition ? redefinition.name : next_name();
def.orig.forEach(function(sym) {
sym.name = name;
});
def.references.forEach(function(sym) {
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 = this._default_mangler_options(options);
try {
AST_Node.prototype.print = function(stream, force_parens) {
this._print(stream, force_parens);
if (this instanceof AST_Symbol && !this.unmangleable(options)) {
base54.consider(this.name, -1);
} else if (options.properties) {
if (this instanceof AST_DotHash) {
base54.consider("#" + this.property, -1);
} else if (this instanceof AST_Dot) {
base54.consider(this.property, -1);
} else if (this instanceof AST_Sub) {
skip_string(this.property);
}
}
};
base54.consider(this.print_to_string(), 1);
} finally {
AST_Node.prototype.print = AST_Node.prototype._print;
}
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());
}
}
});
const base54 = (() => {
const leading = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split("");
const digits = "0123456789".split("");
let chars;
let frequency;
function reset() {
frequency = new Map();
leading.forEach(function(ch) {
frequency.set(ch, 0);
});
digits.forEach(function(ch) {
frequency.set(ch, 0);
});
}
base54.consider = function(str, delta) {
for (var i = str.length; --i >= 0;) {
frequency.set(str[i], frequency.get(str[i]) + delta);
}
};
function compare(a, b) {
return frequency.get(b) - frequency.get(a);
}
base54.sort = function() {
chars = mergeSort(leading, compare).concat(mergeSort(digits, compare));
};
base54.reset = reset;
reset();
function base54(num) {
var ret = "", base = 54;
num++;
do {
num--;
ret += chars[num % base];
num = Math.floor(num / base);
base = 64;
} while (num > 0);
return ret;
}
return base54;
})();
export {
base54,
SymbolDef,
};

490
assets_old/node_modules/terser/lib/size.js generated vendored Normal file
View file

@ -0,0 +1,490 @@
import {
AST_Accessor,
AST_Array,
AST_Arrow,
AST_Await,
AST_BigInt,
AST_Binary,
AST_Block,
AST_Break,
AST_Call,
AST_Case,
AST_Class,
AST_ClassPrivateProperty,
AST_ClassProperty,
AST_ConciseMethod,
AST_Conditional,
AST_Const,
AST_Continue,
AST_Debugger,
AST_Default,
AST_Defun,
AST_Destructuring,
AST_Directive,
AST_Do,
AST_Dot,
AST_DotHash,
AST_EmptyStatement,
AST_Expansion,
AST_Export,
AST_False,
AST_For,
AST_ForIn,
AST_Function,
AST_Hole,
AST_If,
AST_Import,
AST_ImportMeta,
AST_Infinity,
AST_LabeledStatement,
AST_Let,
AST_NameMapping,
AST_NaN,
AST_New,
AST_NewTarget,
AST_Node,
AST_Null,
AST_Number,
AST_Object,
AST_ObjectKeyVal,
AST_ObjectGetter,
AST_ObjectSetter,
AST_PrivateGetter,
AST_PrivateMethod,
AST_PrivateSetter,
AST_RegExp,
AST_Return,
AST_Sequence,
AST_String,
AST_Sub,
AST_Super,
AST_Switch,
AST_Symbol,
AST_SymbolClassProperty,
AST_SymbolExportForeign,
AST_SymbolImportForeign,
AST_SymbolRef,
AST_SymbolDeclaration,
AST_TemplateSegment,
AST_TemplateString,
AST_This,
AST_Throw,
AST_Toplevel,
AST_True,
AST_Try,
AST_Catch,
AST_Finally,
AST_Unary,
AST_Undefined,
AST_Var,
AST_VarDef,
AST_While,
AST_With,
AST_Yield,
walk_parent
} from "./ast.js";
import { first_in_statement } from "./utils/first_in_statement.js";
let mangle_options = undefined;
AST_Node.prototype.size = function (compressor, stack) {
mangle_options = compressor && compressor.mangle_options;
let size = 0;
walk_parent(this, (node, info) => {
size += node._size(info);
// Braceless arrow functions have fake "return" statements
if (node instanceof AST_Arrow && node.is_braceless()) {
size += node.body[0].value._size(info);
return true;
}
}, stack || (compressor && compressor.stack));
// just to save a bit of memory
mangle_options = undefined;
return size;
};
AST_Node.prototype._size = () => 0;
AST_Debugger.prototype._size = () => 8;
AST_Directive.prototype._size = function () {
// TODO string encoding stuff
return 2 + this.value.length;
};
const list_overhead = (array) => array.length && array.length - 1;
AST_Block.prototype._size = function () {
return 2 + list_overhead(this.body);
};
AST_Toplevel.prototype._size = function() {
return list_overhead(this.body);
};
AST_EmptyStatement.prototype._size = () => 1;
AST_LabeledStatement.prototype._size = () => 2; // x:
AST_Do.prototype._size = () => 9;
AST_While.prototype._size = () => 7;
AST_For.prototype._size = () => 8;
AST_ForIn.prototype._size = () => 8;
// AST_ForOf inherits ^
AST_With.prototype._size = () => 6;
AST_Expansion.prototype._size = () => 3;
const lambda_modifiers = func =>
(func.is_generator ? 1 : 0) + (func.async ? 6 : 0);
AST_Accessor.prototype._size = function () {
return lambda_modifiers(this) + 4 + list_overhead(this.argnames) + list_overhead(this.body);
};
AST_Function.prototype._size = function (info) {
const first = !!first_in_statement(info);
return (first * 2) + lambda_modifiers(this) + 12 + list_overhead(this.argnames) + list_overhead(this.body);
};
AST_Defun.prototype._size = function () {
return lambda_modifiers(this) + 13 + list_overhead(this.argnames) + list_overhead(this.body);
};
AST_Arrow.prototype._size = function () {
let args_and_arrow = 2 + list_overhead(this.argnames);
if (
!(
this.argnames.length === 1
&& this.argnames[0] instanceof AST_Symbol
)
) {
args_and_arrow += 2;
}
const body_overhead = this.is_braceless() ? 0 : list_overhead(this.body) + 2;
return lambda_modifiers(this) + args_and_arrow + body_overhead;
};
AST_Destructuring.prototype._size = () => 2;
AST_TemplateString.prototype._size = function () {
return 2 + (Math.floor(this.segments.length / 2) * 3); /* "${}" */
};
AST_TemplateSegment.prototype._size = function () {
return this.value.length;
};
AST_Return.prototype._size = function () {
return this.value ? 7 : 6;
};
AST_Throw.prototype._size = () => 6;
AST_Break.prototype._size = function () {
return this.label ? 6 : 5;
};
AST_Continue.prototype._size = function () {
return this.label ? 9 : 8;
};
AST_If.prototype._size = () => 4;
AST_Switch.prototype._size = function () {
return 8 + list_overhead(this.body);
};
AST_Case.prototype._size = function () {
return 5 + list_overhead(this.body);
};
AST_Default.prototype._size = function () {
return 8 + list_overhead(this.body);
};
AST_Try.prototype._size = function () {
return 3 + list_overhead(this.body);
};
AST_Catch.prototype._size = function () {
let size = 7 + list_overhead(this.body);
if (this.argname) {
size += 2;
}
return size;
};
AST_Finally.prototype._size = function () {
return 7 + list_overhead(this.body);
};
/*#__INLINE__*/
const def_size = (size, def) => size + list_overhead(def.definitions);
AST_Var.prototype._size = function () {
return def_size(4, this);
};
AST_Let.prototype._size = function () {
return def_size(4, this);
};
AST_Const.prototype._size = function () {
return def_size(6, this);
};
AST_VarDef.prototype._size = function () {
return this.value ? 1 : 0;
};
AST_NameMapping.prototype._size = function () {
// foreign name isn't mangled
return this.name ? 4 : 0;
};
AST_Import.prototype._size = function () {
// import
let size = 6;
if (this.imported_name) size += 1;
// from
if (this.imported_name || this.imported_names) size += 5;
// braces, and the commas
if (this.imported_names) {
size += 2 + list_overhead(this.imported_names);
}
return size;
};
AST_ImportMeta.prototype._size = () => 11;
AST_Export.prototype._size = function () {
let size = 7 + (this.is_default ? 8 : 0);
if (this.exported_value) {
size += this.exported_value._size();
}
if (this.exported_names) {
// Braces and commas
size += 2 + list_overhead(this.exported_names);
}
if (this.module_name) {
// "from "
size += 5;
}
return size;
};
AST_Call.prototype._size = function () {
if (this.optional) {
return 4 + list_overhead(this.args);
}
return 2 + list_overhead(this.args);
};
AST_New.prototype._size = function () {
return 6 + list_overhead(this.args);
};
AST_Sequence.prototype._size = function () {
return list_overhead(this.expressions);
};
AST_Dot.prototype._size = function () {
if (this.optional) {
return this.property.length + 2;
}
return this.property.length + 1;
};
AST_DotHash.prototype._size = function () {
if (this.optional) {
return this.property.length + 3;
}
return this.property.length + 2;
};
AST_Sub.prototype._size = function () {
return this.optional ? 4 : 2;
};
AST_Unary.prototype._size = function () {
if (this.operator === "typeof") return 7;
if (this.operator === "void") return 5;
return this.operator.length;
};
AST_Binary.prototype._size = function (info) {
if (this.operator === "in") return 4;
let size = this.operator.length;
if (
(this.operator === "+" || this.operator === "-")
&& this.right instanceof AST_Unary && this.right.operator === this.operator
) {
// 1+ +a > needs space between the +
size += 1;
}
if (this.needs_parens(info)) {
size += 2;
}
return size;
};
AST_Conditional.prototype._size = () => 3;
AST_Array.prototype._size = function () {
return 2 + list_overhead(this.elements);
};
AST_Object.prototype._size = function (info) {
let base = 2;
if (first_in_statement(info)) {
base += 2; // parens
}
return base + list_overhead(this.properties);
};
/*#__INLINE__*/
const key_size = key =>
typeof key === "string" ? key.length : 0;
AST_ObjectKeyVal.prototype._size = function () {
return key_size(this.key) + 1;
};
/*#__INLINE__*/
const static_size = is_static => is_static ? 7 : 0;
AST_ObjectGetter.prototype._size = function () {
return 5 + static_size(this.static) + key_size(this.key);
};
AST_ObjectSetter.prototype._size = function () {
return 5 + static_size(this.static) + key_size(this.key);
};
AST_ConciseMethod.prototype._size = function () {
return static_size(this.static) + key_size(this.key) + lambda_modifiers(this);
};
AST_PrivateMethod.prototype._size = function () {
return AST_ConciseMethod.prototype._size.call(this) + 1;
};
AST_PrivateGetter.prototype._size = AST_PrivateSetter.prototype._size = function () {
return AST_ConciseMethod.prototype._size.call(this) + 4;
};
AST_Class.prototype._size = function () {
return (
(this.name ? 8 : 7)
+ (this.extends ? 8 : 0)
);
};
AST_ClassProperty.prototype._size = function () {
return (
static_size(this.static)
+ (typeof this.key === "string" ? this.key.length + 2 : 0)
+ (this.value ? 1 : 0)
);
};
AST_ClassPrivateProperty.prototype._size = function () {
return AST_ClassProperty.prototype._size.call(this) + 1;
};
AST_Symbol.prototype._size = function () {
return !mangle_options || this.definition().unmangleable(mangle_options)
? this.name.length
: 1;
};
// TODO take propmangle into account
AST_SymbolClassProperty.prototype._size = function () {
return this.name.length;
};
AST_SymbolRef.prototype._size = AST_SymbolDeclaration.prototype._size = function () {
const { name, thedef } = this;
if (thedef && thedef.global) return name.length;
if (name === "arguments") return 9;
return AST_Symbol.prototype._size.call(this);
};
AST_NewTarget.prototype._size = () => 10;
AST_SymbolImportForeign.prototype._size = function () {
return this.name.length;
};
AST_SymbolExportForeign.prototype._size = function () {
return this.name.length;
};
AST_This.prototype._size = () => 4;
AST_Super.prototype._size = () => 5;
AST_String.prototype._size = function () {
return this.value.length + 2;
};
AST_Number.prototype._size = function () {
const { value } = this;
if (value === 0) return 1;
if (value > 0 && Math.floor(value) === value) {
return Math.floor(Math.log10(value) + 1);
}
return value.toString().length;
};
AST_BigInt.prototype._size = function () {
return this.value.length;
};
AST_RegExp.prototype._size = function () {
return this.value.toString().length;
};
AST_Null.prototype._size = () => 4;
AST_NaN.prototype._size = () => 3;
AST_Undefined.prototype._size = () => 6; // "void 0"
AST_Hole.prototype._size = () => 0; // comma is taken into account
AST_Infinity.prototype._size = () => 8;
AST_True.prototype._size = () => 4;
AST_False.prototype._size = () => 5;
AST_Await.prototype._size = () => 6;
AST_Yield.prototype._size = () => 6;

114
assets_old/node_modules/terser/lib/sourcemap.js generated vendored Normal file
View file

@ -0,0 +1,114 @@
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
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";
import MOZ_SourceMap from "source-map";
import {
defaults,
} from "./utils/index.js";
// a small wrapper around fitzgen's source-map library
async function SourceMap(options) {
options = defaults(options, {
file : null,
root : null,
orig : null,
orig_line_diff : 0,
dest_line_diff : 0,
});
var orig_map;
var generator = new MOZ_SourceMap.SourceMapGenerator({
file : options.file,
sourceRoot : options.root
});
if (options.orig) {
orig_map = await new MOZ_SourceMap.SourceMapConsumer(options.orig);
orig_map.sources.forEach(function(source) {
var sourceContent = orig_map.sourceContentFor(source, true);
if (sourceContent) {
generator.setSourceContent(source, sourceContent);
}
});
}
function add(source, gen_line, gen_col, orig_line, orig_col, name) {
if (orig_map) {
var info = orig_map.originalPositionFor({
line: orig_line,
column: orig_col
});
if (info.source === null) {
return;
}
source = info.source;
orig_line = info.line;
orig_col = info.column;
name = info.name || name;
}
generator.addMapping({
generated : { line: gen_line + options.dest_line_diff, column: gen_col },
original : { line: orig_line + options.orig_line_diff, column: orig_col },
source : source,
name : name
});
}
return {
add : add,
get : function() { return generator; },
toString : function() { return generator.toString(); },
destroy : function () {
if (orig_map && orig_map.destroy) {
orig_map.destroy();
}
}
};
}
export {
SourceMap,
};

318
assets_old/node_modules/terser/lib/transform.js generated vendored Normal file
View file

@ -0,0 +1,318 @@
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
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";
import {
AST_Array,
AST_Await,
AST_Binary,
AST_Block,
AST_Call,
AST_Case,
AST_Catch,
AST_Chain,
AST_Class,
AST_Conditional,
AST_Definitions,
AST_Destructuring,
AST_Do,
AST_Dot,
AST_Exit,
AST_Expansion,
AST_Export,
AST_For,
AST_ForIn,
AST_If,
AST_Import,
AST_LabeledStatement,
AST_Lambda,
AST_LoopControl,
AST_NameMapping,
AST_Node,
AST_Number,
AST_Object,
AST_ObjectProperty,
AST_PrefixedTemplateString,
AST_Sequence,
AST_SimpleStatement,
AST_Sub,
AST_Switch,
AST_TemplateString,
AST_Try,
AST_Unary,
AST_VarDef,
AST_While,
AST_With,
AST_Yield,
} from "./ast.js";
import {
MAP,
noop,
} from "./utils/index.js";
function def_transform(node, descend) {
node.DEFMETHOD("transform", function(tw, in_list) {
let transformed = undefined;
tw.push(this);
if (tw.before) transformed = tw.before(this, descend, in_list);
if (transformed === undefined) {
transformed = this;
descend(transformed, tw);
if (tw.after) {
const after_ret = tw.after(transformed, in_list);
if (after_ret !== undefined) transformed = after_ret;
}
}
tw.pop();
return transformed;
});
}
function do_list(list, tw) {
return MAP(list, function(node) {
return node.transform(tw, true);
});
}
def_transform(AST_Node, noop);
def_transform(AST_LabeledStatement, function(self, tw) {
self.label = self.label.transform(tw);
self.body = self.body.transform(tw);
});
def_transform(AST_SimpleStatement, function(self, tw) {
self.body = self.body.transform(tw);
});
def_transform(AST_Block, function(self, tw) {
self.body = do_list(self.body, tw);
});
def_transform(AST_Do, function(self, tw) {
self.body = self.body.transform(tw);
self.condition = self.condition.transform(tw);
});
def_transform(AST_While, function(self, tw) {
self.condition = self.condition.transform(tw);
self.body = self.body.transform(tw);
});
def_transform(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_transform(AST_ForIn, function(self, tw) {
self.init = self.init.transform(tw);
self.object = self.object.transform(tw);
self.body = self.body.transform(tw);
});
def_transform(AST_With, function(self, tw) {
self.expression = self.expression.transform(tw);
self.body = self.body.transform(tw);
});
def_transform(AST_Exit, function(self, tw) {
if (self.value) self.value = self.value.transform(tw);
});
def_transform(AST_LoopControl, function(self, tw) {
if (self.label) self.label = self.label.transform(tw);
});
def_transform(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_transform(AST_Switch, function(self, tw) {
self.expression = self.expression.transform(tw);
self.body = do_list(self.body, tw);
});
def_transform(AST_Case, function(self, tw) {
self.expression = self.expression.transform(tw);
self.body = do_list(self.body, tw);
});
def_transform(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_transform(AST_Catch, function(self, tw) {
if (self.argname) self.argname = self.argname.transform(tw);
self.body = do_list(self.body, tw);
});
def_transform(AST_Definitions, function(self, tw) {
self.definitions = do_list(self.definitions, tw);
});
def_transform(AST_VarDef, function(self, tw) {
self.name = self.name.transform(tw);
if (self.value) self.value = self.value.transform(tw);
});
def_transform(AST_Destructuring, function(self, tw) {
self.names = do_list(self.names, tw);
});
def_transform(AST_Lambda, function(self, tw) {
if (self.name) self.name = self.name.transform(tw);
self.argnames = do_list(self.argnames, tw);
if (self.body instanceof AST_Node) {
self.body = self.body.transform(tw);
} else {
self.body = do_list(self.body, tw);
}
});
def_transform(AST_Call, function(self, tw) {
self.expression = self.expression.transform(tw);
self.args = do_list(self.args, tw);
});
def_transform(AST_Sequence, function(self, tw) {
const result = do_list(self.expressions, tw);
self.expressions = result.length
? result
: [new AST_Number({ value: 0 })];
});
def_transform(AST_Dot, function(self, tw) {
self.expression = self.expression.transform(tw);
});
def_transform(AST_Sub, function(self, tw) {
self.expression = self.expression.transform(tw);
self.property = self.property.transform(tw);
});
def_transform(AST_Chain, function(self, tw) {
self.expression = self.expression.transform(tw);
});
def_transform(AST_Yield, function(self, tw) {
if (self.expression) self.expression = self.expression.transform(tw);
});
def_transform(AST_Await, function(self, tw) {
self.expression = self.expression.transform(tw);
});
def_transform(AST_Unary, function(self, tw) {
self.expression = self.expression.transform(tw);
});
def_transform(AST_Binary, function(self, tw) {
self.left = self.left.transform(tw);
self.right = self.right.transform(tw);
});
def_transform(AST_Conditional, function(self, tw) {
self.condition = self.condition.transform(tw);
self.consequent = self.consequent.transform(tw);
self.alternative = self.alternative.transform(tw);
});
def_transform(AST_Array, function(self, tw) {
self.elements = do_list(self.elements, tw);
});
def_transform(AST_Object, function(self, tw) {
self.properties = do_list(self.properties, tw);
});
def_transform(AST_ObjectProperty, 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_transform(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_transform(AST_Expansion, function(self, tw) {
self.expression = self.expression.transform(tw);
});
def_transform(AST_NameMapping, function(self, tw) {
self.foreign_name = self.foreign_name.transform(tw);
self.name = self.name.transform(tw);
});
def_transform(AST_Import, function(self, tw) {
if (self.imported_name) self.imported_name = self.imported_name.transform(tw);
if (self.imported_names) do_list(self.imported_names, tw);
self.module_name = self.module_name.transform(tw);
});
def_transform(AST_Export, function(self, tw) {
if (self.exported_definition) self.exported_definition = self.exported_definition.transform(tw);
if (self.exported_value) self.exported_value = self.exported_value.transform(tw);
if (self.exported_names) do_list(self.exported_names, tw);
if (self.module_name) self.module_name = self.module_name.transform(tw);
});
def_transform(AST_TemplateString, function(self, tw) {
self.segments = do_list(self.segments, tw);
});
def_transform(AST_PrefixedTemplateString, function(self, tw) {
self.prefix = self.prefix.transform(tw);
self.template_string = self.template_string.transform(tw);
});

View file

@ -0,0 +1,50 @@
import {
AST_Binary,
AST_Conditional,
AST_Dot,
AST_Object,
AST_Sequence,
AST_Statement,
AST_Sub,
AST_UnaryPostfix,
AST_PrefixedTemplateString
} from "../ast.js";
// 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) {
let node = stack.parent(-1);
for (let i = 0, p; p = stack.parent(i); i++) {
if (p instanceof AST_Statement && p.body === node)
return true;
if ((p instanceof AST_Sequence && p.expressions[0] === node) ||
(p.TYPE === "Call" && p.expression === node) ||
(p instanceof AST_PrefixedTemplateString && p.prefix === node) ||
(p instanceof AST_Dot && p.expression === node) ||
(p instanceof AST_Sub && p.expression === node) ||
(p instanceof AST_Conditional && p.condition === node) ||
(p instanceof AST_Binary && p.left === node) ||
(p instanceof AST_UnaryPostfix && p.expression === node)
) {
node = p;
} else {
return false;
}
}
}
// Returns whether the leftmost item in the expression is an object
function left_is_object(node) {
if (node instanceof AST_Object) return true;
if (node instanceof AST_Sequence) return left_is_object(node.expressions[0]);
if (node.TYPE === "Call") return left_is_object(node.expression);
if (node instanceof AST_PrefixedTemplateString) return left_is_object(node.prefix);
if (node instanceof AST_Dot || node instanceof AST_Sub) return left_is_object(node.expression);
if (node instanceof AST_Conditional) return left_is_object(node.condition);
if (node instanceof AST_Binary) return left_is_object(node.left);
if (node instanceof AST_UnaryPostfix) return left_is_object(node.expression);
return false;
}
export { first_in_statement, left_is_object };

304
assets_old/node_modules/terser/lib/utils/index.js generated vendored Normal file
View file

@ -0,0 +1,304 @@
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
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.includes(name);
}
class DefaultsError extends Error {
constructor(msg, defs) {
super();
this.name = "DefaultsError";
this.message = msg;
this.defs = defs;
}
}
function defaults(args, defs, croak) {
if (args === true) {
args = {};
}
if (args != null && typeof args === "object") {
args = Object.assign({}, args);
}
const ret = args || {};
if (croak) for (const i in ret) if (HOP(ret, i) && !HOP(defs, i)) {
throw new DefaultsError("`" + i + "` is not a supported option", defs);
}
for (const i in defs) if (HOP(defs, i)) {
if (!args || !HOP(args, i)) {
ret[i] = defs[i];
} else if (i === "ecma") {
let ecma = args[i] | 0;
if (ecma > 5 && ecma < 2015) ecma += 2009;
ret[i] = ecma;
} else {
ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
}
}
return ret;
}
function noop() {}
function return_false() { return false; }
function return_true() { return true; }
function return_this() { return this; }
function return_null() { return null; }
var MAP = (function() {
function MAP(a, f, backwards) {
var ret = [], top = [], i;
function doit() {
var val = f(a[i], i);
var is_last = val instanceof Last;
if (is_last) val = val.v;
if (val instanceof AtTop) {
val = val.v;
if (val instanceof Splice) {
top.push.apply(top, backwards ? val.v.slice().reverse() : val.v);
} else {
top.push(val);
}
} else if (val !== skip) {
if (val instanceof Splice) {
ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v);
} else {
ret.push(val);
}
}
return is_last;
}
if (Array.isArray(a)) {
if (backwards) {
for (i = a.length; --i >= 0;) if (doit()) break;
ret.reverse();
top.reverse();
} else {
for (i = 0; i < a.length; ++i) if (doit()) break;
}
} else {
for (i in a) if (HOP(a, i)) if (doit()) break;
}
return top.concat(ret);
}
MAP.at_top = function(val) { return new AtTop(val); };
MAP.splice = function(val) { return new Splice(val); };
MAP.last = function(val) { return new Last(val); };
var skip = MAP.skip = {};
function AtTop(val) { this.v = val; }
function Splice(val) { this.v = val; }
function Last(val) { this.v = val; }
return MAP;
})();
function make_node(ctor, orig, props) {
if (!props) props = {};
if (orig) {
if (!props.start) props.start = orig.start;
if (!props.end) props.end = orig.end;
}
return new ctor(props);
}
function push_uniq(array, el) {
if (!array.includes(el))
array.push(el);
}
function string_template(text, props) {
return text.replace(/{(.+?)}/g, function(str, p) {
return props && props[p];
});
}
function remove(array, el) {
for (var i = array.length; --i >= 0;) {
if (array[i] === el) array.splice(i, 1);
}
}
function mergeSort(array, cmp) {
if (array.length < 2) return array.slice();
function merge(a, b) {
var r = [], ai = 0, bi = 0, i = 0;
while (ai < a.length && bi < b.length) {
cmp(a[ai], b[bi]) <= 0
? r[i++] = a[ai++]
: r[i++] = b[bi++];
}
if (ai < a.length) r.push.apply(r, a.slice(ai));
if (bi < b.length) r.push.apply(r, b.slice(bi));
return r;
}
function _ms(a) {
if (a.length <= 1)
return a;
var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);
left = _ms(left);
right = _ms(right);
return merge(left, right);
}
return _ms(array);
}
function makePredicate(words) {
if (!Array.isArray(words)) words = words.split(" ");
return new Set(words);
}
function map_add(map, key, value) {
if (map.has(key)) {
map.get(key).push(value);
} else {
map.set(key, [ value ]);
}
}
function map_from_object(obj) {
var map = new Map();
for (var key in obj) {
if (HOP(obj, key) && key.charAt(0) === "$") {
map.set(key.substr(1), obj[key]);
}
}
return map;
}
function map_to_object(map) {
var obj = Object.create(null);
map.forEach(function (value, key) {
obj["$" + key] = value;
});
return obj;
}
function HOP(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
function keep_name(keep_setting, name) {
return keep_setting === true
|| (keep_setting instanceof RegExp && keep_setting.test(name));
}
var lineTerminatorEscape = {
"\0": "0",
"\n": "n",
"\r": "r",
"\u2028": "u2028",
"\u2029": "u2029",
};
function regexp_source_fix(source) {
// V8 does not escape line terminators in regexp patterns in node 12
// We'll also remove literal \0
return source.replace(/[\0\n\r\u2028\u2029]/g, function (match, offset) {
var escaped = source[offset - 1] == "\\"
&& (source[offset - 2] != "\\"
|| /(?:^|[^\\])(?:\\{2})*$/.test(source.slice(0, offset - 1)));
return (escaped ? "" : "\\") + lineTerminatorEscape[match];
});
}
const all_flags = "gimuy";
function sort_regexp_flags(flags) {
const existing_flags = new Set(flags.split(""));
let out = "";
for (const flag of all_flags) {
if (existing_flags.has(flag)) {
out += flag;
existing_flags.delete(flag);
}
}
if (existing_flags.size) {
// Flags Terser doesn't know about
existing_flags.forEach(flag => { out += flag; });
}
return out;
}
function has_annotation(node, annotation) {
return node._annotations & annotation;
}
function set_annotation(node, annotation) {
node._annotations |= annotation;
}
export {
characters,
defaults,
HOP,
keep_name,
make_node,
makePredicate,
map_add,
map_from_object,
map_to_object,
MAP,
member,
mergeSort,
noop,
push_uniq,
regexp_source_fix,
remove,
return_false,
return_null,
return_this,
return_true,
sort_regexp_flags,
string_template,
has_annotation,
set_annotation
};

27
assets_old/node_modules/terser/main.js generated vendored Normal file
View file

@ -0,0 +1,27 @@
import "./lib/transform.js";
import "./lib/mozilla-ast.js";
import { minify } from "./lib/minify.js";
export { minify } from "./lib/minify.js";
export { run_cli as _run_cli } from "./lib/cli.js";
export async function _default_options() {
const defs = {};
Object.keys(infer_options({ 0: 0 })).forEach((component) => {
const options = infer_options({
[component]: {0: 0}
});
if (options) defs[component] = options;
});
return defs;
}
async function infer_options(options) {
try {
await minify("", options);
} catch (error) {
return error.defs;
}
}

View file

@ -0,0 +1,419 @@
2.20.3 / 2019-10-11
==================
* Support Node.js 0.10 (Revert #1059)
* Ran "npm unpublish commander@2.20.2". There is no 2.20.2.
2.20.1 / 2019-09-29
==================
* Improve executable subcommand tracking
* Update dev dependencies
2.20.0 / 2019-04-02
==================
* fix: resolve symbolic links completely when hunting for subcommands (#935)
* Update index.d.ts (#930)
* Update Readme.md (#924)
* Remove --save option as it isn't required anymore (#918)
* Add link to the license file (#900)
* Added example of receiving args from options (#858)
* Added missing semicolon (#882)
* Add extension to .eslintrc (#876)
2.19.0 / 2018-10-02
==================
* Removed newline after Options and Commands headers (#864)
* Bugfix - Error output (#862)
* Fix to change default value to string (#856)
2.18.0 / 2018-09-07
==================
* Standardize help output (#853)
* chmod 644 travis.yml (#851)
* add support for execute typescript subcommand via ts-node (#849)
2.17.1 / 2018-08-07
==================
* Fix bug in command emit (#844)
2.17.0 / 2018-08-03
==================
* fixed newline output after help information (#833)
* Fix to emit the action even without command (#778)
* npm update (#823)
2.16.0 / 2018-06-29
==================
* Remove Makefile and `test/run` (#821)
* Make 'npm test' run on Windows (#820)
* Add badge to display install size (#807)
* chore: cache node_modules (#814)
* chore: remove Node.js 4 (EOL), add Node.js 10 (#813)
* fixed typo in readme (#812)
* Fix types (#804)
* Update eslint to resolve vulnerabilities in lodash (#799)
* updated readme with custom event listeners. (#791)
* fix tests (#794)
2.15.0 / 2018-03-07
==================
* Update downloads badge to point to graph of downloads over time instead of duplicating link to npm
* Arguments description
2.14.1 / 2018-02-07
==================
* Fix typing of help function
2.14.0 / 2018-02-05
==================
* only register the option:version event once
* Fixes issue #727: Passing empty string for option on command is set to undefined
* enable eqeqeq rule
* resolves #754 add linter configuration to project
* resolves #560 respect custom name for version option
* document how to override the version flag
* document using options per command
2.13.0 / 2018-01-09
==================
* Do not print default for --no-
* remove trailing spaces in command help
* Update CI's Node.js to LTS and latest version
* typedefs: Command and Option types added to commander namespace
2.12.2 / 2017-11-28
==================
* fix: typings are not shipped
2.12.1 / 2017-11-23
==================
* Move @types/node to dev dependency
2.12.0 / 2017-11-22
==================
* add attributeName() method to Option objects
* Documentation updated for options with --no prefix
* typings: `outputHelp` takes a string as the first parameter
* typings: use overloads
* feat(typings): update to match js api
* Print default value in option help
* Fix translation error
* Fail when using same command and alias (#491)
* feat(typings): add help callback
* fix bug when description is add after command with options (#662)
* Format js code
* Rename History.md to CHANGELOG.md (#668)
* feat(typings): add typings to support TypeScript (#646)
* use current node
2.11.0 / 2017-07-03
==================
* Fix help section order and padding (#652)
* feature: support for signals to subcommands (#632)
* Fixed #37, --help should not display first (#447)
* Fix translation errors. (#570)
* Add package-lock.json
* Remove engines
* Upgrade package version
* Prefix events to prevent conflicts between commands and options (#494)
* Removing dependency on graceful-readlink
* Support setting name in #name function and make it chainable
* Add .vscode directory to .gitignore (Visual Studio Code metadata)
* Updated link to ruby commander in readme files
2.10.0 / 2017-06-19
==================
* Update .travis.yml. drop support for older node.js versions.
* Fix require arguments in README.md
* On SemVer you do not start from 0.0.1
* Add missing semi colon in readme
* Add save param to npm install
* node v6 travis test
* Update Readme_zh-CN.md
* Allow literal '--' to be passed-through as an argument
* Test subcommand alias help
* link build badge to master branch
* Support the alias of Git style sub-command
* added keyword commander for better search result on npm
* Fix Sub-Subcommands
* test node.js stable
* Fixes TypeError when a command has an option called `--description`
* Update README.md to make it beginner friendly and elaborate on the difference between angled and square brackets.
* Add chinese Readme file
2.9.0 / 2015-10-13
==================
* Add option `isDefault` to set default subcommand #415 @Qix-
* Add callback to allow filtering or post-processing of help text #434 @djulien
* Fix `undefined` text in help information close #414 #416 @zhiyelee
2.8.1 / 2015-04-22
==================
* Back out `support multiline description` Close #396 #397
2.8.0 / 2015-04-07
==================
* Add `process.execArg` support, execution args like `--harmony` will be passed to sub-commands #387 @DigitalIO @zhiyelee
* Fix bug in Git-style sub-commands #372 @zhiyelee
* Allow commands to be hidden from help #383 @tonylukasavage
* When git-style sub-commands are in use, yet none are called, display help #382 @claylo
* Add ability to specify arguments syntax for top-level command #258 @rrthomas
* Support multiline descriptions #208 @zxqfox
2.7.1 / 2015-03-11
==================
* Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367.
2.7.0 / 2015-03-09
==================
* Fix git-style bug when installed globally. Close #335 #349 @zhiyelee
* Fix collisions when option and first arg have same name. Close #346 #347 @tonylukasavage
* Add support for camelCase on `opts()`. Close #353 @nkzawa
* Add node.js 0.12 and io.js to travis.yml
* Allow RegEx options. #337 @palanik
* Fixes exit code when sub-command failing. Close #260 #332 @pirelenito
* git-style `bin` files in $PATH make sense. Close #196 #327 @zhiyelee
2.6.0 / 2014-12-30
==================
* added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee
* Add application description to the help msg. Close #112 @dalssoft
2.5.1 / 2014-12-15
==================
* fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee
2.5.0 / 2014-10-24
==================
* add support for variadic arguments. Closes #277 @whitlockjc
2.4.0 / 2014-10-17
==================
* fixed a bug on executing the coercion function of subcommands option. Closes #270
* added `Command.prototype.name` to retrieve command name. Closes #264 #266 @tonylukasavage
* added `Command.prototype.opts` to retrieve all the options as a simple object of key-value pairs. Closes #262 @tonylukasavage
* fixed a bug on subcommand name. Closes #248 @jonathandelgado
* fixed function normalize doesnt honor option terminator. Closes #216 @abbr
2.3.0 / 2014-07-16
==================
* add command alias'. Closes PR #210
* fix: Typos. Closes #99
* fix: Unused fs module. Closes #217
2.2.0 / 2014-03-29
==================
* add passing of previous option value
* fix: support subcommands on windows. Closes #142
* Now the defaultValue passed as the second argument of the coercion function.
2.1.0 / 2013-11-21
==================
* add: allow cflag style option params, unit test, fixes #174
2.0.0 / 2013-07-18
==================
* remove input methods (.prompt, .confirm, etc)
1.3.2 / 2013-07-18
==================
* add support for sub-commands to co-exist with the original command
1.3.1 / 2013-07-18
==================
* add quick .runningCommand hack so you can opt-out of other logic when running a sub command
1.3.0 / 2013-07-09
==================
* add EACCES error handling
* fix sub-command --help
1.2.0 / 2013-06-13
==================
* allow "-" hyphen as an option argument
* support for RegExp coercion
1.1.1 / 2012-11-20
==================
* add more sub-command padding
* fix .usage() when args are present. Closes #106
1.1.0 / 2012-11-16
==================
* add git-style executable subcommand support. Closes #94
1.0.5 / 2012-10-09
==================
* fix `--name` clobbering. Closes #92
* fix examples/help. Closes #89
1.0.4 / 2012-09-03
==================
* add `outputHelp()` method.
1.0.3 / 2012-08-30
==================
* remove invalid .version() defaulting
1.0.2 / 2012-08-24
==================
* add `--foo=bar` support [arv]
* fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus]
1.0.1 / 2012-08-03
==================
* fix issue #56
* fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode())
1.0.0 / 2012-07-05
==================
* add support for optional option descriptions
* add defaulting of `.version()` to package.json's version
0.6.1 / 2012-06-01
==================
* Added: append (yes or no) on confirmation
* Added: allow node.js v0.7.x
0.6.0 / 2012-04-10
==================
* Added `.prompt(obj, callback)` support. Closes #49
* Added default support to .choose(). Closes #41
* Fixed the choice example
0.5.1 / 2011-12-20
==================
* Fixed `password()` for recent nodes. Closes #36
0.5.0 / 2011-12-04
==================
* Added sub-command option support [itay]
0.4.3 / 2011-12-04
==================
* Fixed custom help ordering. Closes #32
0.4.2 / 2011-11-24
==================
* Added travis support
* Fixed: line-buffered input automatically trimmed. Closes #31
0.4.1 / 2011-11-18
==================
* Removed listening for "close" on --help
0.4.0 / 2011-11-15
==================
* Added support for `--`. Closes #24
0.3.3 / 2011-11-14
==================
* Fixed: wait for close event when writing help info [Jerry Hamlet]
0.3.2 / 2011-11-01
==================
* Fixed long flag definitions with values [felixge]
0.3.1 / 2011-10-31
==================
* Changed `--version` short flag to `-V` from `-v`
* Changed `.version()` so it's configurable [felixge]
0.3.0 / 2011-10-31
==================
* Added support for long flags only. Closes #18
0.2.1 / 2011-10-24
==================
* "node": ">= 0.4.x < 0.7.0". Closes #20
0.2.0 / 2011-09-26
==================
* Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs]
0.1.0 / 2011-08-24
==================
* Added support for custom `--help` output
0.0.5 / 2011-08-18
==================
* Changed: when the user enters nothing prompt for password again
* Fixed issue with passwords beginning with numbers [NuckChorris]
0.0.4 / 2011-08-15
==================
* Fixed `Commander#args`
0.0.3 / 2011-08-15
==================
* Added default option value support
0.0.2 / 2011-08-15
==================
* Added mask support to `Command#password(str[, mask], fn)`
* Added `Command#password(str, fn)`
0.0.1 / 2010-01-03
==================
* Initial release

View file

@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,428 @@
# Commander.js
[![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js)
[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)
[![Join the chat at https://gitter.im/tj/commander.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander).
[API documentation](http://tj.github.com/commander.js/)
## Installation
$ npm install commander
## Option parsing
Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq-sauce', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);
console.log('you ordered a pizza with:');
if (program.peppers) console.log(' - peppers');
if (program.pineapple) console.log(' - pineapple');
if (program.bbqSauce) console.log(' - bbq');
console.log(' - %s cheese', program.cheese);
```
Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.
Note that multi-word options starting with `--no` prefix negate the boolean value of the following word. For example, `--no-sauce` sets the value of `program.sauce` to false.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.option('--no-sauce', 'Remove sauce')
.parse(process.argv);
console.log('you ordered a pizza');
if (program.sauce) console.log(' with sauce');
else console.log(' without sauce');
```
To get string arguments from options you will need to use angle brackets <> for required inputs or square brackets [] for optional inputs.
e.g. ```.option('-m --myarg [myVar]', 'my super cool description')```
Then to access the input if it was passed in.
e.g. ```var myInput = program.myarg```
**NOTE**: If you pass a argument without using brackets the example above will return true and not the value passed in.
## Version option
Calling the `version` implicitly adds the `-V` and `--version` options to the command.
When either of these options is present, the command prints the version number and exits.
$ ./examples/pizza -V
0.0.1
If you want your program to respond to the `-v` option instead of the `-V` option, simply pass custom flags to the `version` method using the same syntax as the `option` method.
```js
program
.version('0.0.1', '-v, --version')
```
The version flags can be named anything, but the long option is required.
## Command-specific options
You can attach options to a command.
```js
#!/usr/bin/env node
var program = require('commander');
program
.command('rm <dir>')
.option('-r, --recursive', 'Remove recursively')
.action(function (dir, cmd) {
console.log('remove ' + dir + (cmd.recursive ? ' recursively' : ''))
})
program.parse(process.argv)
```
A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.
## Coercion
```js
function range(val) {
return val.split('..').map(Number);
}
function list(val) {
return val.split(',');
}
function collect(val, memo) {
memo.push(val);
return memo;
}
function increaseVerbosity(v, total) {
return total + 1;
}
program
.version('0.1.0')
.usage('[options] <file ...>')
.option('-i, --integer <n>', 'An integer argument', parseInt)
.option('-f, --float <n>', 'A float argument', parseFloat)
.option('-r, --range <a>..<b>', 'A range', range)
.option('-l, --list <items>', 'A list', list)
.option('-o, --optional [value]', 'An optional value')
.option('-c, --collect [value]', 'A repeatable value', collect, [])
.option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
.parse(process.argv);
console.log(' int: %j', program.integer);
console.log(' float: %j', program.float);
console.log(' optional: %j', program.optional);
program.range = program.range || [];
console.log(' range: %j..%j', program.range[0], program.range[1]);
console.log(' list: %j', program.list);
console.log(' collect: %j', program.collect);
console.log(' verbosity: %j', program.verbose);
console.log(' args: %j', program.args);
```
## Regular Expression
```js
program
.version('0.1.0')
.option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')
.option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)
.parse(process.argv);
console.log(' size: %j', program.size);
console.log(' drink: %j', program.drink);
```
## Variadic arguments
The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to
append `...` to the argument name. Here is an example:
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.command('rmdir <dir> [otherDirs...]')
.action(function (dir, otherDirs) {
console.log('rmdir %s', dir);
if (otherDirs) {
otherDirs.forEach(function (oDir) {
console.log('rmdir %s', oDir);
});
}
});
program.parse(process.argv);
```
An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed
to your action as demonstrated above.
## Specify the argument syntax
```js
#!/usr/bin/env node
var program = require('commander');
program
.version('0.1.0')
.arguments('<cmd> [env]')
.action(function (cmd, env) {
cmdValue = cmd;
envValue = env;
});
program.parse(process.argv);
if (typeof cmdValue === 'undefined') {
console.error('no command given!');
process.exit(1);
}
console.log('command:', cmdValue);
console.log('environment:', envValue || "no environment given");
```
Angled brackets (e.g. `<cmd>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input.
## Git-style sub-commands
```js
// file: ./examples/pm
var program = require('commander');
program
.version('0.1.0')
.command('install [name]', 'install one or more packages')
.command('search [query]', 'search with optional query')
.command('list', 'list packages installed', {isDefault: true})
.parse(process.argv);
```
When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools.
The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`.
Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the subcommand from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.
If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
### `--harmony`
You can enable `--harmony` option in two ways:
* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version dont support this pattern.
* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process.
## Automated --help
The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
```
$ ./examples/pizza --help
Usage: pizza [options]
An application for pizzas ordering
Options:
-h, --help output usage information
-V, --version output the version number
-p, --peppers Add peppers
-P, --pineapple Add pineapple
-b, --bbq Add bbq sauce
-c, --cheese <type> Add the specified type of cheese [marble]
-C, --no-cheese You do not want any cheese
```
## Custom help
You can display arbitrary `-h, --help` information
by listening for "--help". Commander will automatically
exit once you are done so that the remainder of your program
does not execute causing undesired behaviors, for example
in the following executable "stuff" will not output when
`--help` is used.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.option('-f, --foo', 'enable some foo')
.option('-b, --bar', 'enable some bar')
.option('-B, --baz', 'enable some baz');
// must be before .parse() since
// node's emit() is immediate
program.on('--help', function(){
console.log('')
console.log('Examples:');
console.log(' $ custom-help --help');
console.log(' $ custom-help -h');
});
program.parse(process.argv);
console.log('stuff');
```
Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:
```
Usage: custom-help [options]
Options:
-h, --help output usage information
-V, --version output the version number
-f, --foo enable some foo
-b, --bar enable some bar
-B, --baz enable some baz
Examples:
$ custom-help --help
$ custom-help -h
```
## .outputHelp(cb)
Output help information without exiting.
Optional callback cb allows post-processing of help text before it is displayed.
If you want to display help by default (e.g. if no command was provided), you can use something like:
```js
var program = require('commander');
var colors = require('colors');
program
.version('0.1.0')
.command('getstream [url]', 'get stream URL')
.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp(make_red);
}
function make_red(txt) {
return colors.red(txt); //display the help text in red on the console
}
```
## .help(cb)
Output help information and exit immediately.
Optional callback cb allows post-processing of help text before it is displayed.
## Custom event listeners
You can execute custom actions by listening to command and option events.
```js
program.on('option:verbose', function () {
process.env.VERBOSE = this.verbose;
});
// error on unknown commands
program.on('command:*', function () {
console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' '));
process.exit(1);
});
```
## Examples
```js
var program = require('commander');
program
.version('0.1.0')
.option('-C, --chdir <path>', 'change the working directory')
.option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
.option('-T, --no-tests', 'ignore test hook');
program
.command('setup [env]')
.description('run setup commands for all envs')
.option("-s, --setup_mode [mode]", "Which setup mode to use")
.action(function(env, options){
var mode = options.setup_mode || "normal";
env = env || 'all';
console.log('setup for %s env(s) with %s mode', env, mode);
});
program
.command('exec <cmd>')
.alias('ex')
.description('execute the given remote cmd')
.option("-e, --exec_mode <mode>", "Which exec mode to use")
.action(function(cmd, options){
console.log('exec "%s" using %s mode', cmd, options.exec_mode);
}).on('--help', function() {
console.log('');
console.log('Examples:');
console.log('');
console.log(' $ deploy exec sequential');
console.log(' $ deploy exec async');
});
program
.command('*')
.action(function(env){
console.log('deploying "%s"', env);
});
program.parse(process.argv);
```
More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
## License
[MIT](https://github.com/tj/commander.js/blob/master/LICENSE)

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,38 @@
{
"name": "commander",
"version": "2.20.3",
"description": "the complete solution for node.js command-line programs",
"keywords": [
"commander",
"command",
"option",
"parser"
],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/tj/commander.js.git"
},
"scripts": {
"lint": "eslint index.js",
"test": "node test/run.js && npm run test-typings",
"test-typings": "tsc -p tsconfig.json"
},
"main": "index",
"files": [
"index.js",
"typings/index.d.ts"
],
"dependencies": {},
"devDependencies": {
"@types/node": "^12.7.8",
"eslint": "^6.4.0",
"should": "^13.2.3",
"sinon": "^7.5.0",
"standard": "^14.3.1",
"ts-node": "^8.4.1",
"typescript": "^3.6.3"
},
"typings": "typings/index.d.ts"
}

View file

@ -0,0 +1,310 @@
// Type definitions for commander 2.11
// Project: https://github.com/visionmedia/commander.js
// Definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace local {
class Option {
flags: string;
required: boolean;
optional: boolean;
bool: boolean;
short?: string;
long: string;
description: string;
/**
* Initialize a new `Option` with the given `flags` and `description`.
*
* @param {string} flags
* @param {string} [description]
*/
constructor(flags: string, description?: string);
}
class Command extends NodeJS.EventEmitter {
[key: string]: any;
args: string[];
/**
* Initialize a new `Command`.
*
* @param {string} [name]
*/
constructor(name?: string);
/**
* Set the program version to `str`.
*
* This method auto-registers the "-V, --version" flag
* which will print the version number when passed.
*
* @param {string} str
* @param {string} [flags]
* @returns {Command} for chaining
*/
version(str: string, flags?: string): Command;
/**
* Add command `name`.
*
* The `.action()` callback is invoked when the
* command `name` is specified via __ARGV__,
* and the remaining arguments are applied to the
* function for access.
*
* When the `name` is "*" an un-matched command
* will be passed as the first arg, followed by
* the rest of __ARGV__ remaining.
*
* @example
* program
* .version('0.0.1')
* .option('-C, --chdir <path>', 'change the working directory')
* .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
* .option('-T, --no-tests', 'ignore test hook')
*
* program
* .command('setup')
* .description('run remote setup commands')
* .action(function() {
* console.log('setup');
* });
*
* program
* .command('exec <cmd>')
* .description('run the given remote command')
* .action(function(cmd) {
* console.log('exec "%s"', cmd);
* });
*
* program
* .command('teardown <dir> [otherDirs...]')
* .description('run teardown commands')
* .action(function(dir, otherDirs) {
* console.log('dir "%s"', dir);
* if (otherDirs) {
* otherDirs.forEach(function (oDir) {
* console.log('dir "%s"', oDir);
* });
* }
* });
*
* program
* .command('*')
* .description('deploy the given env')
* .action(function(env) {
* console.log('deploying "%s"', env);
* });
*
* program.parse(process.argv);
*
* @param {string} name
* @param {string} [desc] for git-style sub-commands
* @param {CommandOptions} [opts] command options
* @returns {Command} the new command
*/
command(name: string, desc?: string, opts?: commander.CommandOptions): Command;
/**
* Define argument syntax for the top-level command.
*
* @param {string} desc
* @returns {Command} for chaining
*/
arguments(desc: string): Command;
/**
* Parse expected `args`.
*
* For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
*
* @param {string[]} args
* @returns {Command} for chaining
*/
parseExpectedArgs(args: string[]): Command;
/**
* Register callback `fn` for the command.
*
* @example
* program
* .command('help')
* .description('display verbose help')
* .action(function() {
* // output help here
* });
*
* @param {(...args: any[]) => void} fn
* @returns {Command} for chaining
*/
action(fn: (...args: any[]) => void): Command;
/**
* Define option with `flags`, `description` and optional
* coercion `fn`.
*
* The `flags` string should contain both the short and long flags,
* separated by comma, a pipe or space. The following are all valid
* all will output this way when `--help` is used.
*
* "-p, --pepper"
* "-p|--pepper"
* "-p --pepper"
*
* @example
* // simple boolean defaulting to false
* program.option('-p, --pepper', 'add pepper');
*
* --pepper
* program.pepper
* // => Boolean
*
* // simple boolean defaulting to true
* program.option('-C, --no-cheese', 'remove cheese');
*
* program.cheese
* // => true
*
* --no-cheese
* program.cheese
* // => false
*
* // required argument
* program.option('-C, --chdir <path>', 'change the working directory');
*
* --chdir /tmp
* program.chdir
* // => "/tmp"
*
* // optional argument
* program.option('-c, --cheese [type]', 'add cheese [marble]');
*
* @param {string} flags
* @param {string} [description]
* @param {((arg1: any, arg2: any) => void) | RegExp} [fn] function or default
* @param {*} [defaultValue]
* @returns {Command} for chaining
*/
option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command;
option(flags: string, description?: string, defaultValue?: any): Command;
/**
* Allow unknown options on the command line.
*
* @param {boolean} [arg] if `true` or omitted, no error will be thrown for unknown options.
* @returns {Command} for chaining
*/
allowUnknownOption(arg?: boolean): Command;
/**
* Parse `argv`, settings options and invoking commands when defined.
*
* @param {string[]} argv
* @returns {Command} for chaining
*/
parse(argv: string[]): Command;
/**
* Parse options from `argv` returning `argv` void of these options.
*
* @param {string[]} argv
* @returns {ParseOptionsResult}
*/
parseOptions(argv: string[]): commander.ParseOptionsResult;
/**
* Return an object containing options as key-value pairs
*
* @returns {{[key: string]: any}}
*/
opts(): { [key: string]: any };
/**
* Set the description to `str`.
*
* @param {string} str
* @param {{[argName: string]: string}} argsDescription
* @return {(Command | string)}
*/
description(str: string, argsDescription?: {[argName: string]: string}): Command;
description(): string;
/**
* Set an alias for the command.
*
* @param {string} alias
* @return {(Command | string)}
*/
alias(alias: string): Command;
alias(): string;
/**
* Set or get the command usage.
*
* @param {string} str
* @return {(Command | string)}
*/
usage(str: string): Command;
usage(): string;
/**
* Set the name of the command.
*
* @param {string} str
* @return {Command}
*/
name(str: string): Command;
/**
* Get the name of the command.
*
* @return {string}
*/
name(): string;
/**
* Output help information for this command.
*
* @param {(str: string) => string} [cb]
*/
outputHelp(cb?: (str: string) => string): void;
/** Output help information and exit.
*
* @param {(str: string) => string} [cb]
*/
help(cb?: (str: string) => string): never;
}
}
declare namespace commander {
type Command = local.Command
type Option = local.Option
interface CommandOptions {
noHelp?: boolean;
isDefault?: boolean;
}
interface ParseOptionsResult {
args: string[];
unknown: string[];
}
interface CommanderStatic extends Command {
Command: typeof local.Command;
Option: typeof local.Option;
CommandOptions: CommandOptions;
ParseOptionsResult: ParseOptionsResult;
}
}
declare const commander: commander.CommanderStatic;
export = commander;

View file

@ -0,0 +1,344 @@
# Change Log
## 0.7.3
* Fix a bug where nested uses of `SourceMapConsumer` could result in a
`TypeError`. [#338](https://github.com/mozilla/source-map/issues/338)
[#330](https://github.com/mozilla/source-map/issues/330)
[#319](https://github.com/mozilla/source-map/issues/319)
## 0.7.2
* Another 3x speed up in `SourceMapConsumer`. Read about it here:
http://fitzgeraldnick.com/2018/02/26/speed-without-wizardry.html
## 0.7.1
* Updated TypeScript typings. [#321][]
[#321]: https://github.com/mozilla/source-map/pull/321
## 0.7.0
* `SourceMapConsumer` now uses WebAssembly, and is **much** faster! Read about
it here:
https://hacks.mozilla.org/2018/01/oxidizing-source-maps-with-rust-and-webassembly/
* **Breaking change:** `new SourceMapConsumer` now returns a `Promise` object
that resolves to the newly constructed `SourceMapConsumer` instance, rather
than returning the new instance immediately.
* **Breaking change:** when you're done using a `SourceMapConsumer` instance,
you must call `SourceMapConsumer.prototype.destroy` on it. After calling
`destroy`, you must not use the instance again.
* **Breaking change:** `SourceMapConsumer` used to be able to handle lines,
columns numbers and source and name indices up to `2^53 - 1` (aka
`Number.MAX_SAFE_INTEGER`). It can now only handle them up to `2^32 - 1`.
* **Breaking change:** The `source-map` library now uses modern ECMAScript-isms:
`let`, arrow functions, `async`, etc. Use Babel to compile it down to
ECMAScript 5 if you need to support older JavaScript environments.
* **Breaking change:** Drop support for Node < 8. If you want to support older
versions of node, please use v0.6 or below.
## 0.5.6
* Fix for regression when people were using numbers as names in source maps. See
#236.
## 0.5.5
* Fix "regression" of unsupported, implementation behavior that half the world
happens to have come to depend on. See #235.
* Fix regression involving function hoisting in SpiderMonkey. See #233.
## 0.5.4
* Large performance improvements to source-map serialization. See #228 and #229.
## 0.5.3
* Do not include unnecessary distribution files. See
commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86.
## 0.5.2
* Include browser distributions of the library in package.json's `files`. See
issue #212.
## 0.5.1
* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See
ff05274becc9e6e1295ed60f3ea090d31d843379.
## 0.5.0
* Node 0.8 is no longer supported.
* Use webpack instead of dryice for bundling.
* Big speedups serializing source maps. See pull request #203.
* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that
explicitly start with the source root. See issue #199.
## 0.4.4
* Fix an issue where using a `SourceMapGenerator` after having created a
`SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See
issue #191.
* Fix an issue with where `SourceMapGenerator` would mistakenly consider
different mappings as duplicates of each other and avoid generating them. See
issue #192.
## 0.4.3
* A very large number of performance improvements, particularly when parsing
source maps. Collectively about 75% of time shaved off of the source map
parsing benchmark!
* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy
searching in the presence of a column option. See issue #177.
* Fix a bug with joining a source and its source root when the source is above
the root. See issue #182.
* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to
determine when all sources' contents are inlined into the source map. See
issue #190.
## 0.4.2
* Add an `.npmignore` file so that the benchmarks aren't pulled down by
dependent projects. Issue #169.
* Add an optional `column` argument to
`SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines
with no mappings. Issues #172 and #173.
## 0.4.1
* Fix accidentally defining a global variable. #170.
## 0.4.0
* The default direction for fuzzy searching was changed back to its original
direction. See #164.
* There is now a `bias` option you can supply to `SourceMapConsumer` to control
the fuzzy searching direction. See #167.
* About an 8% speed up in parsing source maps. See #159.
* Added a benchmark for parsing and generating source maps.
## 0.3.0
* Change the default direction that searching for positions fuzzes when there is
not an exact match. See #154.
* Support for environments using json2.js for JSON serialization. See #156.
## 0.2.0
* Support for consuming "indexed" source maps which do not have any remote
sections. See pull request #127. This introduces a minor backwards
incompatibility if you are monkey patching `SourceMapConsumer.prototype`
methods.
## 0.1.43
* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue
#148 for some discussion and issues #150, #151, and #152 for implementations.
## 0.1.42
* Fix an issue where `SourceNode`s from different versions of the source-map
library couldn't be used in conjunction with each other. See issue #142.
## 0.1.41
* Fix a bug with getting the source content of relative sources with a "./"
prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768).
* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the
column span of each mapping.
* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find
all generated positions associated with a given original source and line.
## 0.1.40
* Performance improvements for parsing source maps in SourceMapConsumer.
## 0.1.39
* Fix a bug where setting a source's contents to null before any source content
had been set before threw a TypeError. See issue #131.
## 0.1.38
* Fix a bug where finding relative paths from an empty path were creating
absolute paths. See issue #129.
## 0.1.37
* Fix a bug where if the source root was an empty string, relative source paths
would turn into absolute source paths. Issue #124.
## 0.1.36
* Allow the `names` mapping property to be an empty string. Issue #121.
## 0.1.35
* A third optional parameter was added to `SourceNode.fromStringWithSourceMap`
to specify a path that relative sources in the second parameter should be
relative to. Issue #105.
* If no file property is given to a `SourceMapGenerator`, then the resulting
source map will no longer have a `null` file property. The property will
simply not exist. Issue #104.
* Fixed a bug where consecutive newlines were ignored in `SourceNode`s.
Issue #116.
## 0.1.34
* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103.
* Fix bug involving source contents and the
`SourceMapGenerator.prototype.applySourceMap`. Issue #100.
## 0.1.33
* Fix some edge cases surrounding path joining and URL resolution.
* Add a third parameter for relative path to
`SourceMapGenerator.prototype.applySourceMap`.
* Fix issues with mappings and EOLs.
## 0.1.32
* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns
(issue 92).
* Fixed test runner to actually report number of failed tests as its process
exit code.
* Fixed a typo when reporting bad mappings (issue 87).
## 0.1.31
* Delay parsing the mappings in SourceMapConsumer until queried for a source
location.
* Support Sass source maps (which at the time of writing deviate from the spec
in small ways) in SourceMapConsumer.
## 0.1.30
* Do not join source root with a source, when the source is a data URI.
* Extend the test runner to allow running single specific test files at a time.
* Performance improvements in `SourceNode.prototype.walk` and
`SourceMapConsumer.prototype.eachMapping`.
* Source map browser builds will now work inside Workers.
* Better error messages when attempting to add an invalid mapping to a
`SourceMapGenerator`.
## 0.1.29
* Allow duplicate entries in the `names` and `sources` arrays of source maps
(usually from TypeScript) we are parsing. Fixes github issue 72.
## 0.1.28
* Skip duplicate mappings when creating source maps from SourceNode; github
issue 75.
## 0.1.27
* Don't throw an error when the `file` property is missing in SourceMapConsumer,
we don't use it anyway.
## 0.1.26
* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70.
## 0.1.25
* Make compatible with browserify
## 0.1.24
* Fix issue with absolute paths and `file://` URIs. See
https://bugzilla.mozilla.org/show_bug.cgi?id=885597
## 0.1.23
* Fix issue with absolute paths and sourcesContent, github issue 64.
## 0.1.22
* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21.
## 0.1.21
* Fixed handling of sources that start with a slash so that they are relative to
the source root's host.
## 0.1.20
* Fixed github issue #43: absolute URLs aren't joined with the source root
anymore.
## 0.1.19
* Using Travis CI to run tests.
## 0.1.18
* Fixed a bug in the handling of sourceRoot.
## 0.1.17
* Added SourceNode.fromStringWithSourceMap.
## 0.1.16
* Added missing documentation.
* Fixed the generating of empty mappings in SourceNode.
## 0.1.15
* Added SourceMapGenerator.applySourceMap.
## 0.1.14
* The sourceRoot is now handled consistently.
## 0.1.13
* Added SourceMapGenerator.fromSourceMap.
## 0.1.12
* SourceNode now generates empty mappings too.
## 0.1.11
* Added name support to SourceNode.
## 0.1.10
* Added sourcesContent support to the customer and generator.

View file

@ -0,0 +1,28 @@
Copyright (c) 2009-2011, Mozilla Foundation and contributors
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 names of the Mozilla Foundation nor the names of project
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 HOLDER 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.

View file

@ -0,0 +1,822 @@
# Source Map
[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)
[![Coverage Status](https://coveralls.io/repos/github/mozilla/source-map/badge.svg)](https://coveralls.io/github/mozilla/source-map)
[![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map)
This is a library to generate and consume the source map format
[described here][format].
[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
## Use with Node
$ npm install source-map
## Use on the Web
<script src="https://unpkg.com/source-map@0.7.3/dist/source-map.js"></script>
<script>
sourceMap.SourceMapConsumer.initialize({
"lib/mappings.wasm": "https://unpkg.com/source-map@0.7.3/lib/mappings.wasm"
});
</script>
--------------------------------------------------------------------------------
<!-- `npm run toc` to regenerate the Table of Contents -->
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## 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)
- [SourceMapConsumer.initialize(options)](#sourcemapconsumerinitializeoptions)
- [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
- [SourceMapConsumer.with](#sourcemapconsumerwith)
- [SourceMapConsumer.prototype.destroy()](#sourcemapconsumerprototypedestroy)
- [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)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Examples
### Consuming a source map
```js
const 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'
};
const whatever = await SourceMapConsumer.with(rawSourceMap, null, consumer => {
console.log(consumer.sources);
// [ 'http://example.com/www/js/one.js',
// 'http://example.com/www/js/two.js' ]
console.log(consumer.originalPositionFor({
line: 2,
column: 28
}));
// { source: 'http://example.com/www/js/two.js',
// line: 2,
// column: 10,
// name: 'n' }
console.log(consumer.generatedPositionFor({
source: 'http://example.com/www/js/two.js',
line: 2,
column: 10
}));
// { line: 2, column: 28 }
consumer.eachMapping(function (m) {
// ...
});
return computeWhatever();
});
```
### 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.
#### SourceMapConsumer.initialize(options)
When using `SourceMapConsumer` outside of node.js, for example on the Web, it
needs to know from what URL to load `lib/mappings.wasm`. You must inform it by
calling `initialize` before constructing any `SourceMapConsumer`s.
The options object has the following properties:
* `"lib/mappings.wasm"`: A `String` containing the URL of the
`lib/mappings.wasm` file.
```js
sourceMap.SourceMapConsumer.initialize({
"lib/mappings.wasm": "https://example.com/source-map/lib/mappings.wasm"
});
```
#### 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.
The promise of the constructed souce map consumer is returned.
When the `SourceMapConsumer` will no longer be used anymore, you must call its
`destroy` method.
```js
const consumer = await new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
doStuffWith(consumer);
consumer.destroy();
```
Alternatively, you can use `SourceMapConsumer.with` to avoid needing to remember
to call `destroy`.
#### SourceMapConsumer.with
Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl`
(see the `SourceMapConsumer` constructor for details. Then, invoke the `async
function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait
for `f` to complete, call `destroy` on the consumer, and return `f`'s return
value.
You must not use the consumer after `f` completes!
By using `with`, you do not have to remember to manually call `destroy` on
the consumer, since it will be called automatically once `f` completes.
```js
const xSquared = await SourceMapConsumer.with(
myRawSourceMap,
null,
async function (consumer) {
// Use `consumer` inside here and don't worry about remembering
// to call `destroy`.
const x = await whatever(consumer);
return x * x;
}
);
// You may not use that `consumer` anymore out here; it has
// been destroyed. But you can use `xSquared`.
console.log(xSquared);
```
#### SourceMapConsumer.prototype.destroy()
Free this source map consumer's associated wasm data that is manually-managed.
```js
consumer.destroy();
```
Alternatively, you can use `SourceMapConsumer.with` to avoid needing to remember
to call `destroy`.
#### 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
const consumer = await new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
const 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] }
```

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,100 @@
/* -*- 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
*/
/**
* 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.
*/
class ArraySet {
constructor() {
this._array = [];
this._set = new Map();
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
static fromArray(aArray, aAllowDuplicates) {
const set = new ArraySet();
for (let 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
*/
size() {
return this._set.size;
}
/**
* Add the given string to this set.
*
* @param String aStr
*/
add(aStr, aAllowDuplicates) {
const isDuplicate = this.has(aStr);
const idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
this._set.set(aStr, idx);
}
}
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
has(aStr) {
return this._set.has(aStr);
}
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
indexOf(aStr) {
const idx = this._set.get(aStr);
if (idx >= 0) {
return idx;
}
throw new Error('"' + aStr + '" is not in the set.');
}
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
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.
*/
toArray() {
return this._array.slice();
}
}
exports.ArraySet = ArraySet;

View file

@ -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
*
* 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.
*/
const 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
const VLQ_BASE_SHIFT = 5;
// binary: 100000
const VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
const VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
const 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
*/
// eslint-disable-next-line no-unused-vars
function fromVLQSigned(aValue) {
const isNegative = (aValue & 1) === 1;
const shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
let encoded = "";
let digit;
let 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;
};

View file

@ -0,0 +1,18 @@
/* -*- 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
*/
const 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);
};

View file

@ -0,0 +1,107 @@
/* -*- 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.
const mid = Math.floor((aHigh - aLow) / 2) + aLow;
const 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;
}
return mid;
}
// 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;
}
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;
}
let 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;
};

View file

@ -0,0 +1,80 @@
/* -*- 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
*/
const util = require("./util");
/**
* Determine whether mappingB is after mappingA with respect to generated
* position.
*/
function generatedPositionAfter(mappingA, mappingB) {
// Optimized for most common case
const lineA = mappingA.generatedLine;
const lineB = mappingB.generatedLine;
const columnA = mappingA.generatedColumn;
const 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 negligible overhead in general
* case for a large speedup in case of mappings being added in order.
*/
class MappingList {
constructor() {
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.
*/
unsortedForEach(aCallback, aThisArg) {
this._array.forEach(aCallback, aThisArg);
}
/**
* Add the given source mapping.
*
* @param Object aMapping
*/
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.
*/
toArray() {
if (!this._sorted) {
this._array.sort(util.compareByGeneratedPositionsInflated);
this._sorted = true;
}
return this._array;
}
}
exports.MappingList = MappingList;

Binary file not shown.

View file

@ -0,0 +1,40 @@
if (typeof fetch === "function") {
// Web version of reading a wasm file into an array buffer.
let mappingsWasmUrl = null;
module.exports = function readWasm() {
if (typeof mappingsWasmUrl !== "string") {
throw new Error("You must provide the URL of lib/mappings.wasm by calling " +
"SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) " +
"before using SourceMapConsumer");
}
return fetch(mappingsWasmUrl)
.then(response => response.arrayBuffer());
};
module.exports.initialize = url => mappingsWasmUrl = url;
} else {
// Node version of reading a wasm file into an array buffer.
const fs = require("fs");
const path = require("path");
module.exports = function readWasm() {
return new Promise((resolve, reject) => {
const wasmPath = path.join(__dirname, "mappings.wasm");
fs.readFile(wasmPath, null, (error, data) => {
if (error) {
reject(error);
return;
}
resolve(data.buffer);
});
});
};
module.exports.initialize = _ => {
console.debug("SourceMapConsumer.initialize is a no-op when running in node.js");
};
}

File diff suppressed because it is too large Load diff

View file

@ -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
*/
const base64VLQ = require("./base64-vlq");
const util = require("./util");
const ArraySet = require("./array-set").ArraySet;
const 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.
*/
class SourceMapGenerator {
constructor(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;
}
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
static fromSourceMap(aSourceMapConsumer) {
const sourceRoot = aSourceMapConsumer.sourceRoot;
const generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot
});
aSourceMapConsumer.eachMapping(function(mapping) {
const 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) {
let sourceRelative = sourceFile;
if (sourceRoot !== null) {
sourceRelative = util.relative(sourceRoot, sourceFile);
}
if (!generator._sources.has(sourceRelative)) {
generator._sources.add(sourceRelative);
}
const 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.
*/
addMapping(aArgs) {
const generated = util.getArg(aArgs, "generated");
const original = util.getArg(aArgs, "original", null);
let source = util.getArg(aArgs, "source", null);
let 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,
name
});
}
/**
* Set the source content for a source file.
*/
setSourceContent(aSourceFile, aSourceContent) {
let 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.
*/
applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
let 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;
}
const 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.
const newSources = this._mappings.toArray().length > 0
? new ArraySet()
: this._sources;
const 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.
const 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;
}
}
}
const source = mapping.source;
if (source != null && !newSources.has(source)) {
newSources.add(source);
}
const 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(srcFile) {
const content = aSourceMapConsumer.sourceContentFor(srcFile);
if (content != null) {
if (aSourceMapPath != null) {
srcFile = util.join(aSourceMapPath, srcFile);
}
if (sourceRoot != null) {
srcFile = util.relative(sourceRoot, srcFile);
}
this.setSourceContent(srcFile, 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.
*/
_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.
} 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.
} 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.
*/
_serializeMappings() {
let previousGeneratedColumn = 0;
let previousGeneratedLine = 1;
let previousOriginalColumn = 0;
let previousOriginalLine = 0;
let previousName = 0;
let previousSource = 0;
let result = "";
let next;
let mapping;
let nameIdx;
let sourceIdx;
const mappings = this._mappings.toArray();
for (let 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;
}
_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function(source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot != null) {
source = util.relative(aSourceRoot, source);
}
const key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
? this._sourcesContents[key]
: null;
}, this);
}
/**
* Externalize the source map.
*/
toJSON() {
const 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.
*/
toString() {
return JSON.stringify(this.toJSON());
}
}
SourceMapGenerator.prototype._version = 3;
exports.SourceMapGenerator = SourceMapGenerator;

View file

@ -0,0 +1,404 @@
/* -*- 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
*/
const SourceMapGenerator = require("./source-map-generator").SourceMapGenerator;
const 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).
const REGEX_NEWLINE = /(\r?\n)/;
// Newline character code for charCodeAt() comparisons
const 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!
const 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.
*/
class SourceNode {
constructor(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.
*/
static fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
const 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`.
const remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
let remainingLinesIndex = 0;
const shiftNextLine = function() {
const lineContents = getNextLine();
// The last line of a file might not have a newline.
const newLine = getNextLine() || "";
return lineContents + newLine;
function getNextLine() {
return remainingLinesIndex < remainingLines.length ?
remainingLines[remainingLinesIndex++] : undefined;
}
};
// We need to remember the position of "remainingLines"
let 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.
let lastMapping = null;
let nextLine;
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"
nextLine = remainingLines[remainingLinesIndex] || "";
const 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) {
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) {
const 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 {
const 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.
*/
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.
*/
prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (let 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.
*/
walk(aFn) {
let chunk;
for (let 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.
*/
join(aSep) {
let newChildren;
let i;
const 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.
*/
replaceRight(aPattern, aReplacement) {
const 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
*/
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.
*/
walkSourceContents(aFn) {
for (let i = 0, len = this.children.length; i < len; i++) {
if (this.children[i][isSourceNode]) {
this.children[i].walkSourceContents(aFn);
}
}
const sources = Object.keys(this.sourceContents);
for (let 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.
*/
toString() {
let str = "";
this.walk(function(chunk) {
str += chunk;
});
return str;
}
/**
* Returns the string representation of this source node along with a source
* map.
*/
toStringWithSourceMap(aArgs) {
const generated = {
code: "",
line: 1,
column: 0
};
const map = new SourceMapGenerator(aArgs);
let sourceMappingActive = false;
let lastOriginalSource = null;
let lastOriginalLine = null;
let lastOriginalColumn = null;
let 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 (let 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 };
}
}
exports.SourceNode = SourceNode;

View file

@ -0,0 +1,546 @@
/* -*- 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;
}
throw new Error('"' + aName + '" is a required argument.');
}
exports.getArg = getArg;
const urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
const dataUrlRegexp = /^data:.+\,.+$/;
function urlParse(aUrl) {
const 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) {
let 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;
const MAX_CACHED_INPUTS = 32;
/**
* Takes some function `f(input) -> result` and returns a memoized version of
* `f`.
*
* We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
* memoization is a dumb-simple, linear least-recently-used cache.
*/
function lruMemoize(f) {
const cache = [];
return function(input) {
for (let i = 0; i < cache.length; i++) {
if (cache[i].input === input) {
const temp = cache[0];
cache[0] = cache[i];
cache[i] = temp;
return cache[0].result;
}
}
const result = f(input);
cache.unshift({
input,
result,
});
if (cache.length > MAX_CACHED_INPUTS) {
cache.pop();
}
return result;
};
}
/**
* Normalizes a path, or the path portion of a URL:
*
* - Replaces consecutive slashes with one slash.
* - Removes unnecessary '.' parts.
* - Removes unnecessary '<dir>/..' parts.
*
* Based on code in the Node.js 'path' core module.
*
* @param aPath The path or url to normalize.
*/
const normalize = lruMemoize(function normalize(aPath) {
let path = aPath;
const url = urlParse(aPath);
if (url) {
if (!url.path) {
return aPath;
}
path = url.path;
}
const isAbsolute = exports.isAbsolute(path);
// Split the path into parts between `/` characters. This is much faster than
// using `.split(/\/+/g)`.
const parts = [];
let start = 0;
let i = 0;
while (true) {
start = i;
i = path.indexOf("/", start);
if (i === -1) {
parts.push(path.slice(start));
break;
} else {
parts.push(path.slice(start, i));
while (i < path.length && path[i] === "/") {
i++;
}
}
}
let up = 0;
for (i = parts.length - 1; i >= 0; i--) {
const 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 = ".";
}
const aPathUrl = urlParse(aPath);
const 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);
}
const 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.
let level = 0;
while (aPath.indexOf(aRoot + "/") !== 0) {
const 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;
const supportsNullProto = (function() {
const 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;
}
const length = s.length;
if (length < 9 /* "__proto__".length */) {
return false;
}
/* eslint-disable no-multi-spaces */
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;
}
/* eslint-enable no-multi-spaces */
for (let 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) {
let 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) {
let 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) {
let 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) {
const parsed = urlParse(sourceMapURL);
if (!parsed) {
throw new Error("sourceMapURL could not be parsed");
}
if (parsed.path) {
// Strip the last path component, but keep the "/".
const 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;

View file

@ -0,0 +1,107 @@
const readWasm = require("../lib/read-wasm");
/**
* Provide the JIT with a nice shape / hidden class.
*/
function Mapping() {
this.generatedLine = 0;
this.generatedColumn = 0;
this.lastGeneratedColumn = null;
this.source = null;
this.originalLine = null;
this.originalColumn = null;
this.name = null;
}
let cachedWasm = null;
module.exports = function wasm() {
if (cachedWasm) {
return cachedWasm;
}
const callbackStack = [];
cachedWasm = readWasm().then(buffer => {
return WebAssembly.instantiate(buffer, {
env: {
mapping_callback(
generatedLine,
generatedColumn,
hasLastGeneratedColumn,
lastGeneratedColumn,
hasOriginal,
source,
originalLine,
originalColumn,
hasName,
name
) {
const mapping = new Mapping();
// JS uses 1-based line numbers, wasm uses 0-based.
mapping.generatedLine = generatedLine + 1;
mapping.generatedColumn = generatedColumn;
if (hasLastGeneratedColumn) {
// JS uses inclusive last generated column, wasm uses exclusive.
mapping.lastGeneratedColumn = lastGeneratedColumn - 1;
}
if (hasOriginal) {
mapping.source = source;
// JS uses 1-based line numbers, wasm uses 0-based.
mapping.originalLine = originalLine + 1;
mapping.originalColumn = originalColumn;
if (hasName) {
mapping.name = name;
}
}
callbackStack[callbackStack.length - 1](mapping);
},
start_all_generated_locations_for() { console.time("all_generated_locations_for"); },
end_all_generated_locations_for() { console.timeEnd("all_generated_locations_for"); },
start_compute_column_spans() { console.time("compute_column_spans"); },
end_compute_column_spans() { console.timeEnd("compute_column_spans"); },
start_generated_location_for() { console.time("generated_location_for"); },
end_generated_location_for() { console.timeEnd("generated_location_for"); },
start_original_location_for() { console.time("original_location_for"); },
end_original_location_for() { console.timeEnd("original_location_for"); },
start_parse_mappings() { console.time("parse_mappings"); },
end_parse_mappings() { console.timeEnd("parse_mappings"); },
start_sort_by_generated_location() { console.time("sort_by_generated_location"); },
end_sort_by_generated_location() { console.timeEnd("sort_by_generated_location"); },
start_sort_by_original_location() { console.time("sort_by_original_location"); },
end_sort_by_original_location() { console.timeEnd("sort_by_original_location"); },
}
});
}).then(Wasm => {
return {
exports: Wasm.instance.exports,
withMappingCallback: (mappingCallback, f) => {
callbackStack.push(mappingCallback);
try {
f();
} finally {
callbackStack.pop();
}
}
};
}).then(null, e => {
cachedWasm = null;
throw e;
});
return cachedWasm;
};

View file

@ -0,0 +1,90 @@
{
"name": "source-map",
"description": "Generates and consumes source maps",
"version": "0.7.3",
"homepage": "https://github.com/mozilla/source-map",
"author": "Nick Fitzgerald <nfitzgerald@mozilla.com>",
"contributors": [
"Tobias Koppers <tobias.koppers@googlemail.com>",
"Duncan Beevers <duncan@dweebd.com>",
"Stephen Crane <scrane@mozilla.com>",
"Ryan Seddon <seddon.ryan@gmail.com>",
"Miles Elam <miles.elam@deem.com>",
"Mihai Bazon <mihai.bazon@gmail.com>",
"Michael Ficarra <github.public.email@michael.ficarra.me>",
"Todd Wolfson <todd@twolfson.com>",
"Alexander Solovyov <alexander@solovyov.net>",
"Felix Gnass <fgnass@gmail.com>",
"Conrad Irwin <conrad.irwin@gmail.com>",
"usrbincc <usrbincc@yahoo.com>",
"David Glasser <glasser@davidglasser.net>",
"Chase Douglas <chase@newrelic.com>",
"Evan Wallace <evan.exe@gmail.com>",
"Heather Arthur <fayearthur@gmail.com>",
"Hugh Kennedy <hughskennedy@gmail.com>",
"David Glasser <glasser@davidglasser.net>",
"Simon Lydell <simon.lydell@gmail.com>",
"Jmeas Smith <jellyes2@gmail.com>",
"Michael Z Goddard <mzgoddard@gmail.com>",
"azu <azu@users.noreply.github.com>",
"John Gozde <john@gozde.ca>",
"Adam Kirkton <akirkton@truefitinnovation.com>",
"Chris Montgomery <christopher.montgomery@dowjones.com>",
"J. Ryan Stinnett <jryans@gmail.com>",
"Jack Herrington <jherrington@walmartlabs.com>",
"Chris Truter <jeffpalentine@gmail.com>",
"Daniel Espeset <daniel@danielespeset.com>",
"Jamie Wong <jamie.lf.wong@gmail.com>",
"Eddy Bruël <ejpbruel@mozilla.com>",
"Hawken Rives <hawkrives@gmail.com>",
"Gilad Peleg <giladp007@gmail.com>",
"djchie <djchie.dev@gmail.com>",
"Gary Ye <garysye@gmail.com>",
"Nicolas Lalevée <nicolas.lalevee@hibnet.org>"
],
"repository": {
"type": "git",
"url": "http://github.com/mozilla/source-map.git"
},
"main": "./source-map.js",
"types": "./source-map.d.ts",
"files": [
"source-map.js",
"source-map.d.ts",
"lib/",
"dist/source-map.js"
],
"engines": {
"node": ">= 8"
},
"license": "BSD-3-Clause",
"scripts": {
"lint": "eslint *.js lib/ test/",
"prebuild": "npm run lint",
"build": "webpack --color",
"pretest": "npm run build",
"test": "node test/run-tests.js",
"precoverage": "npm run build",
"coverage": "nyc node test/run-tests.js",
"setup": "mkdir -p coverage && cp -n .waiting.html coverage/index.html || true",
"dev:live": "live-server --port=4103 --ignorePattern='(js|css|png)$' coverage",
"dev:watch": "watch 'npm run coverage' lib/ test/",
"predev": "npm run setup",
"dev": "npm-run-all -p --silent dev:*",
"clean": "rm -rf coverage .nyc_output",
"toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md"
},
"devDependencies": {
"doctoc": "^0.15.0",
"eslint": "^4.19.1",
"live-server": "^1.2.0",
"npm-run-all": "^4.1.2",
"nyc": "^11.7.1",
"watch": "^1.0.2",
"webpack": "^3.10"
},
"nyc": {
"reporter": "html"
},
"typings": "source-map"
}

View file

@ -0,0 +1,369 @@
// Type definitions for source-map 0.7
// Project: https://github.com/mozilla/source-map
// Definitions by: Morten Houston Ludvigsen <https://github.com/MortenHoustonLudvigsen>,
// Ron Buckton <https://github.com/rbuckton>,
// John Vilk <https://github.com/jvilk>
// Definitions: https://github.com/mozilla/source-map
export type SourceMapUrl = string;
export interface StartOfSourceMap {
file?: string;
sourceRoot?: string;
skipValidation?: boolean;
}
export interface RawSourceMap {
version: number;
sources: string[];
names: string[];
sourceRoot?: string;
sourcesContent?: string[];
mappings: string;
file: string;
}
export interface RawIndexMap extends StartOfSourceMap {
version: number;
sections: RawSection[];
}
export interface RawSection {
offset: Position;
map: RawSourceMap;
}
export interface Position {
line: number;
column: number;
}
export interface NullablePosition {
line: number | null;
column: number | null;
lastColumn: number | null;
}
export interface MappedPosition {
source: string;
line: number;
column: number;
name?: string;
}
export interface NullableMappedPosition {
source: string | null;
line: number | null;
column: number | null;
name: string | null;
}
export interface MappingItem {
source: string;
generatedLine: number;
generatedColumn: number;
originalLine: number;
originalColumn: number;
name: string;
}
export interface Mapping {
generated: Position;
original: Position;
source: string;
name?: string;
}
export interface CodeWithSourceMap {
code: string;
map: SourceMapGenerator;
}
export interface SourceMapConsumer {
/**
* Compute the last column for each generated mapping. The last column is
* inclusive.
*/
computeColumnSpans(): void;
/**
* 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.
* - column: The column number in the generated source.
* - 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.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
originalPositionFor(generatedPosition: Position & { bias?: number }): NullableMappedPosition;
/**
* 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.
* - column: The column number in the original source.
* - 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.
* - column: The column number in the generated source, or null.
*/
generatedPositionFor(originalPosition: MappedPosition & { bias?: number }): NullablePosition;
/**
* 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.
* - column: Optional. the column number in the original source.
*
* and an array of objects is returned, each with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
allGeneratedPositionsFor(originalPosition: MappedPosition): NullablePosition[];
/**
* Return true if we have the source content for every source in the source
* map, false otherwise.
*/
hasContentsOfAllSources(): boolean;
/**
* 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.
*/
sourceContentFor(source: string, returnNullOnMissing?: boolean): string | null;
/**
* Iterate over each mapping between an original source/line/column and a
* generated line/column in this source map.
*
* @param callback
* The function that is called with each mapping.
* @param context
* Optional. If specified, this object will be the value of `this` every
* time that `aCallback` is called.
* @param 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`.
*/
eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void;
/**
* Free this source map consumer's associated wasm data that is manually-managed.
* Alternatively, you can use SourceMapConsumer.with to avoid needing to remember to call destroy.
*/
destroy(): void;
}
export interface SourceMapConsumerConstructor {
prototype: SourceMapConsumer;
GENERATED_ORDER: number;
ORIGINAL_ORDER: number;
GREATEST_LOWER_BOUND: number;
LEAST_UPPER_BOUND: number;
new (rawSourceMap: RawSourceMap, sourceMapUrl?: SourceMapUrl): Promise<BasicSourceMapConsumer>;
new (rawSourceMap: RawIndexMap, sourceMapUrl?: SourceMapUrl): Promise<IndexedSourceMapConsumer>;
new (rawSourceMap: RawSourceMap | RawIndexMap | string, sourceMapUrl?: SourceMapUrl): Promise<BasicSourceMapConsumer | IndexedSourceMapConsumer>;
/**
* Create a BasicSourceMapConsumer from a SourceMapGenerator.
*
* @param sourceMap
* The source map that will be consumed.
*/
fromSourceMap(sourceMap: SourceMapGenerator, sourceMapUrl?: SourceMapUrl): Promise<BasicSourceMapConsumer>;
/**
* Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl`
* (see the `SourceMapConsumer` constructor for details. Then, invoke the `async
* function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait
* for `f` to complete, call `destroy` on the consumer, and return `f`'s return
* value.
*
* You must not use the consumer after `f` completes!
*
* By using `with`, you do not have to remember to manually call `destroy` on
* the consumer, since it will be called automatically once `f` completes.
*
* ```js
* const xSquared = await SourceMapConsumer.with(
* myRawSourceMap,
* null,
* async function (consumer) {
* // Use `consumer` inside here and don't worry about remembering
* // to call `destroy`.
*
* const x = await whatever(consumer);
* return x * x;
* }
* );
*
* // You may not use that `consumer` anymore out here; it has
* // been destroyed. But you can use `xSquared`.
* console.log(xSquared);
* ```
*/
with<T>(rawSourceMap: RawSourceMap | RawIndexMap | string, sourceMapUrl: SourceMapUrl | null | undefined, callback: (consumer: BasicSourceMapConsumer | IndexedSourceMapConsumer) => Promise<T> | T): Promise<T>;
}
export const SourceMapConsumer: SourceMapConsumerConstructor;
export interface BasicSourceMapConsumer extends SourceMapConsumer {
file: string;
sourceRoot: string;
sources: string[];
sourcesContent: string[];
}
export interface BasicSourceMapConsumerConstructor {
prototype: BasicSourceMapConsumer;
new (rawSourceMap: RawSourceMap | string): Promise<BasicSourceMapConsumer>;
/**
* Create a BasicSourceMapConsumer from a SourceMapGenerator.
*
* @param sourceMap
* The source map that will be consumed.
*/
fromSourceMap(sourceMap: SourceMapGenerator): Promise<BasicSourceMapConsumer>;
}
export const BasicSourceMapConsumer: BasicSourceMapConsumerConstructor;
export interface IndexedSourceMapConsumer extends SourceMapConsumer {
sources: string[];
}
export interface IndexedSourceMapConsumerConstructor {
prototype: IndexedSourceMapConsumer;
new (rawSourceMap: RawIndexMap | string): Promise<IndexedSourceMapConsumer>;
}
export const IndexedSourceMapConsumer: IndexedSourceMapConsumerConstructor;
export class SourceMapGenerator {
constructor(startOfSourceMap?: StartOfSourceMap);
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param sourceMapConsumer The SourceMap.
*/
static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator;
/**
* 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.
*/
addMapping(mapping: Mapping): void;
/**
* Set the source content for a source file.
*/
setSourceContent(sourceFile: string, sourceContent: string): void;
/**
* 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 sourceMapConsumer The source map to be applied.
* @param sourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
* @param sourceMapPath 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.
*/
applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void;
toString(): string;
toJSON(): RawSourceMap;
}
export class SourceNode {
children: SourceNode[];
sourceContents: any;
line: number;
column: number;
source: string;
name: string;
constructor();
constructor(
line: number | null,
column: number | null,
source: string | null,
chunks?: Array<(string | SourceNode)> | SourceNode | string,
name?: string
);
static fromStringWithSourceMap(
code: string,
sourceMapConsumer: SourceMapConsumer,
relativePath?: string
): SourceNode;
add(chunk: Array<(string | SourceNode)> | SourceNode | string): SourceNode;
prepend(chunk: Array<(string | SourceNode)> | SourceNode | string): SourceNode;
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;
}

View file

@ -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;

149
assets_old/node_modules/terser/package.json generated vendored Normal file
View file

@ -0,0 +1,149 @@
{
"name": "terser",
"description": "JavaScript parser, mangler/compressor and beautifier toolkit for ES6+",
"homepage": "https://terser.org",
"author": "Mihai Bazon <mihai.bazon@gmail.com> (http://lisperator.net/)",
"license": "BSD-2-Clause",
"version": "5.6.1",
"engines": {
"node": ">=10"
},
"maintainers": [
"Fábio Santos <fabiosantosart@gmail.com>"
],
"repository": "https://github.com/terser/terser",
"main": "dist/bundle.min.js",
"type": "module",
"module": "./main.js",
"exports": {
".": [
{
"import": "./main.js",
"require": "./dist/bundle.min.js"
},
"./dist/bundle.min.js"
],
"./package": "./package.json",
"./package.json": "./package.json"
},
"types": "tools/terser.d.ts",
"bin": {
"terser": "bin/terser"
},
"files": [
"bin",
"dist",
"lib",
"tools",
"LICENSE",
"README.md",
"CHANGELOG.md",
"PATRONS.md",
"main.js"
],
"dependencies": {
"commander": "^2.20.0",
"source-map": "~0.7.2",
"source-map-support": "~0.5.19"
},
"devDependencies": {
"@ls-lint/ls-lint": "^1.9.2",
"acorn": "^8.0.5",
"astring": "^1.6.2",
"eslint": "^7.19.0",
"eslump": "^2.0.0",
"esm": "^3.2.25",
"mocha": "^8.2.1",
"pre-commit": "^1.2.2",
"rimraf": "^3.0.2",
"rollup": "2.38.4",
"semver": "^7.3.4"
},
"scripts": {
"test": "node test/compress.js && mocha test/mocha",
"test:compress": "node test/compress.js",
"test:mocha": "mocha test/mocha",
"lint": "eslint lib",
"lint-fix": "eslint --fix lib",
"ls-lint": "ls-lint",
"build": "rimraf dist/bundle* && rollup --config --silent",
"prepare": "npm run build",
"postversion": "echo 'Remember to update the changelog!'"
},
"keywords": [
"uglify",
"terser",
"uglify-es",
"uglify-js",
"minify",
"minifier",
"javascript",
"ecmascript",
"es5",
"es6",
"es7",
"es8",
"es2015",
"es2016",
"es2017",
"async",
"await"
],
"eslintConfig": {
"parserOptions": {
"sourceType": "module",
"ecmaVersion": "2020"
},
"env": {
"node": true,
"browser": true,
"es2020": true
},
"globals": {
"describe": false,
"it": false,
"require": false,
"global": false,
"process": false
},
"rules": {
"brace-style": [
"error",
"1tbs",
{
"allowSingleLine": true
}
],
"quotes": [
"error",
"double",
"avoid-escape"
],
"no-debugger": "error",
"no-undef": "error",
"no-unused-vars": [
"error",
{
"varsIgnorePattern": "^_$"
}
],
"no-tabs": "error",
"semi": [
"error",
"always"
],
"no-extra-semi": "error",
"no-irregular-whitespace": "error",
"space-before-blocks": [
"error",
"always"
]
}
},
"pre-commit": [
"build",
"lint-fix",
"ls-lint",
"test"
]
}

7771
assets_old/node_modules/terser/tools/domprops.js generated vendored Normal file

File diff suppressed because it is too large Load diff

7
assets_old/node_modules/terser/tools/exit.cjs generated vendored Normal file
View file

@ -0,0 +1,7 @@
// workaround for tty output truncation upon process.exit()
// https://github.com/nodejs/node/issues/6456
[process.stdout, process.stderr].forEach((s) => {
s && s.isTTY && s._handle && s._handle.setBlocking &&
s._handle.setBlocking(true)
});

55
assets_old/node_modules/terser/tools/props.html generated vendored Normal file
View file

@ -0,0 +1,55 @@
<html>
<head>
</head>
<body>
<script>(function(){
var props = {};
function addObject(obj) {
if (obj == null) return;
try {
Object.getOwnPropertyNames(obj).forEach(add);
} catch(ex) {}
if (obj.prototype) {
Object.getOwnPropertyNames(obj.prototype).forEach(add);
}
if (typeof obj == "function") {
try {
Object.getOwnPropertyNames(new obj).forEach(add);
} catch(ex) {}
}
}
function add(name) {
props[name] = true;
}
Object.getOwnPropertyNames(window).forEach(function(thing){
addObject(window[thing]);
});
try {
addObject(new Event("click"));
addObject(new Event("contextmenu"));
addObject(new Event("mouseup"));
addObject(new Event("mousedown"));
addObject(new Event("keydown"));
addObject(new Event("keypress"));
addObject(new Event("keyup"));
} catch(ex) {}
var ta = document.createElement("textarea");
ta.style.width = "100%";
ta.style.height = "20em";
ta.style.boxSizing = "border-box";
ta.value = 'export var domprops = ' + JSON.stringify(Object.keys(props).sort(cmp), null, 4);
document.body.appendChild(ta);
function cmp(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
return a < b ? -1 : a > b ? 1 : 0;
}
})();</script>
</body>
</html>

170
assets_old/node_modules/terser/tools/terser.d.ts generated vendored Normal file
View file

@ -0,0 +1,170 @@
/// <reference lib="es2015" />
import { RawSourceMap } from 'source-map';
export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020;
export interface ParseOptions {
bare_returns?: boolean;
ecma?: ECMA;
html5_comments?: boolean;
shebang?: boolean;
}
export interface CompressOptions {
arguments?: boolean;
arrows?: boolean;
booleans_as_integers?: boolean;
booleans?: boolean;
collapse_vars?: boolean;
comparisons?: boolean;
computed_props?: boolean;
conditionals?: boolean;
dead_code?: boolean;
defaults?: boolean;
directives?: boolean;
drop_console?: boolean;
drop_debugger?: boolean;
ecma?: ECMA;
evaluate?: boolean;
expression?: boolean;
global_defs?: object;
hoist_funs?: boolean;
hoist_props?: boolean;
hoist_vars?: boolean;
ie8?: boolean;
if_return?: boolean;
inline?: boolean | InlineFunctions;
join_vars?: boolean;
keep_classnames?: boolean | RegExp;
keep_fargs?: boolean;
keep_fnames?: boolean | RegExp;
keep_infinity?: boolean;
loops?: boolean;
module?: boolean;
negate_iife?: boolean;
passes?: number;
properties?: boolean;
pure_funcs?: string[];
pure_getters?: boolean | 'strict';
reduce_funcs?: boolean;
reduce_vars?: boolean;
sequences?: boolean | number;
side_effects?: boolean;
switches?: boolean;
toplevel?: boolean;
top_retain?: null | string | string[] | RegExp;
typeofs?: boolean;
unsafe_arrows?: boolean;
unsafe?: boolean;
unsafe_comps?: boolean;
unsafe_Function?: boolean;
unsafe_math?: boolean;
unsafe_symbols?: boolean;
unsafe_methods?: boolean;
unsafe_proto?: boolean;
unsafe_regexp?: boolean;
unsafe_undefined?: boolean;
unused?: boolean;
}
export enum InlineFunctions {
Disabled = 0,
SimpleFunctions = 1,
WithArguments = 2,
WithArgumentsAndVariables = 3
}
export interface MangleOptions {
eval?: boolean;
keep_classnames?: boolean | RegExp;
keep_fnames?: boolean | RegExp;
module?: boolean;
properties?: boolean | ManglePropertiesOptions;
reserved?: string[];
safari10?: boolean;
toplevel?: boolean;
}
export interface ManglePropertiesOptions {
builtins?: boolean;
debug?: boolean;
keep_quoted?: boolean | 'strict';
regex?: RegExp | string;
reserved?: string[];
}
export interface FormatOptions {
ascii_only?: boolean;
/** @deprecated Not implemented anymore */
beautify?: boolean;
braces?: boolean;
comments?: boolean | 'all' | 'some' | RegExp | ( (node: any, comment: {
value: string,
type: 'comment1' | 'comment2' | 'comment3' | 'comment4',
pos: number,
line: number,
col: number,
}) => boolean );
ecma?: ECMA;
ie8?: boolean;
indent_level?: number;
indent_start?: number;
inline_script?: boolean;
keep_quoted_props?: boolean;
max_line_len?: number | false;
preamble?: string;
preserve_annotations?: boolean;
quote_keys?: boolean;
quote_style?: OutputQuoteStyle;
safari10?: boolean;
semicolons?: boolean;
shebang?: boolean;
shorthand?: boolean;
source_map?: SourceMapOptions;
webkit?: boolean;
width?: number;
wrap_iife?: boolean;
wrap_func_args?: boolean;
}
export enum OutputQuoteStyle {
PreferDouble = 0,
AlwaysSingle = 1,
AlwaysDouble = 2,
AlwaysOriginal = 3
}
export interface MinifyOptions {
compress?: boolean | CompressOptions;
ecma?: ECMA;
ie8?: boolean;
keep_classnames?: boolean | RegExp;
keep_fnames?: boolean | RegExp;
mangle?: boolean | MangleOptions;
module?: boolean;
nameCache?: object;
format?: FormatOptions;
/** @deprecated */
output?: FormatOptions;
parse?: ParseOptions;
safari10?: boolean;
sourceMap?: boolean | SourceMapOptions;
toplevel?: boolean;
}
export interface MinifyOutput {
code?: string;
map?: RawSourceMap | string;
}
export interface SourceMapOptions {
/** Source map object, 'inline' or source map file content */
content?: RawSourceMap | string;
includeSources?: boolean;
filename?: string;
root?: string;
url?: string | 'inline';
}
export function minify(files: string | string[] | { [file: string]: string }, options?: MinifyOptions): Promise<MinifyOutput>;